OSDN Git Service

Added LaTex image insert & edit
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / NeverNote.java
1 /*
2  * This file is part of NeverNote 
3  * Copyright 2009 Randy Baumgarte
4  * 
5  * This file may be licensed under the terms of of the
6  * GNU General Public License Version 2 (the ``GPL'').
7  *
8  * Software distributed under the License is distributed
9  * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10  * express or implied. See the GPL for the specific language
11  * governing rights and limitations.
12  *
13  * You should have received a copy of the GPL along with this
14  * program. If not, go to http://www.gnu.org/licenses/gpl.html
15  * or write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18 */
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
45
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
50
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QModelIndex;
79 import com.trolltech.qt.core.QSize;
80 import com.trolltech.qt.core.QTemporaryFile;
81 import com.trolltech.qt.core.QTextCodec;
82 import com.trolltech.qt.core.QThreadPool;
83 import com.trolltech.qt.core.QTimer;
84 import com.trolltech.qt.core.QTranslator;
85 import com.trolltech.qt.core.QUrl;
86 import com.trolltech.qt.core.Qt;
87 import com.trolltech.qt.core.Qt.BGMode;
88 import com.trolltech.qt.core.Qt.ItemDataRole;
89 import com.trolltech.qt.core.Qt.SortOrder;
90 import com.trolltech.qt.core.Qt.WidgetAttribute;
91 import com.trolltech.qt.gui.QAbstractItemView;
92 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
93 import com.trolltech.qt.gui.QAction;
94 import com.trolltech.qt.gui.QApplication;
95 import com.trolltech.qt.gui.QCloseEvent;
96 import com.trolltech.qt.gui.QColor;
97 import com.trolltech.qt.gui.QComboBox;
98 import com.trolltech.qt.gui.QCursor;
99 import com.trolltech.qt.gui.QDesktopServices;
100 import com.trolltech.qt.gui.QDialog;
101 import com.trolltech.qt.gui.QFileDialog;
102 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
103 import com.trolltech.qt.gui.QFileDialog.FileMode;
104 import com.trolltech.qt.gui.QGridLayout;
105 import com.trolltech.qt.gui.QHBoxLayout;
106 import com.trolltech.qt.gui.QIcon;
107 import com.trolltech.qt.gui.QImage;
108 import com.trolltech.qt.gui.QKeySequence;
109 import com.trolltech.qt.gui.QLabel;
110 import com.trolltech.qt.gui.QMainWindow;
111 import com.trolltech.qt.gui.QMenu;
112 import com.trolltech.qt.gui.QMessageBox;
113 import com.trolltech.qt.gui.QMessageBox.StandardButton;
114 import com.trolltech.qt.gui.QPainter;
115 import com.trolltech.qt.gui.QPalette.ColorRole;
116 import com.trolltech.qt.gui.QPixmap;
117 import com.trolltech.qt.gui.QPrintDialog;
118 import com.trolltech.qt.gui.QPrinter;
119 import com.trolltech.qt.gui.QShortcut;
120 import com.trolltech.qt.gui.QSizePolicy;
121 import com.trolltech.qt.gui.QSizePolicy.Policy;
122 import com.trolltech.qt.gui.QSpinBox;
123 import com.trolltech.qt.gui.QSplashScreen;
124 import com.trolltech.qt.gui.QSplitter;
125 import com.trolltech.qt.gui.QStatusBar;
126 import com.trolltech.qt.gui.QSystemTrayIcon;
127 import com.trolltech.qt.gui.QTableWidgetItem;
128 import com.trolltech.qt.gui.QTextEdit;
129 import com.trolltech.qt.gui.QToolBar;
130 import com.trolltech.qt.gui.QTreeWidgetItem;
131 import com.trolltech.qt.network.QNetworkAccessManager;
132 import com.trolltech.qt.network.QNetworkReply;
133 import com.trolltech.qt.network.QNetworkRequest;
134 import com.trolltech.qt.webkit.QWebPage.WebAction;
135 import com.trolltech.qt.webkit.QWebSettings;
136
137 import cx.fbn.nevernote.config.InitializationException;
138 import cx.fbn.nevernote.config.StartupConfig;
139 import cx.fbn.nevernote.dialog.AccountDialog;
140 import cx.fbn.nevernote.dialog.ConfigDialog;
141 import cx.fbn.nevernote.dialog.DBEncryptDialog;
142 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
143 import cx.fbn.nevernote.dialog.DatabaseStatus;
144 import cx.fbn.nevernote.dialog.FindDialog;
145 import cx.fbn.nevernote.dialog.IgnoreSync;
146 import cx.fbn.nevernote.dialog.LogFileDialog;
147 import cx.fbn.nevernote.dialog.LoginDialog;
148 import cx.fbn.nevernote.dialog.NotebookArchive;
149 import cx.fbn.nevernote.dialog.NotebookEdit;
150 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
151 import cx.fbn.nevernote.dialog.PublishNotebook;
152 import cx.fbn.nevernote.dialog.SavedSearchEdit;
153 import cx.fbn.nevernote.dialog.SetIcon;
154 import cx.fbn.nevernote.dialog.ShareNotebook;
155 import cx.fbn.nevernote.dialog.StackNotebook;
156 import cx.fbn.nevernote.dialog.TagEdit;
157 import cx.fbn.nevernote.dialog.ThumbnailViewer;
158 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
159 import cx.fbn.nevernote.dialog.WatchFolder;
160 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
161 import cx.fbn.nevernote.filters.FilterEditorTags;
162 import cx.fbn.nevernote.gui.AttributeTreeWidget;
163 import cx.fbn.nevernote.gui.BrowserWindow;
164 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
165 import cx.fbn.nevernote.gui.ExternalBrowse;
166 import cx.fbn.nevernote.gui.MainMenuBar;
167 import cx.fbn.nevernote.gui.NotebookTreeWidget;
168 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
169 import cx.fbn.nevernote.gui.SearchPanel;
170 import cx.fbn.nevernote.gui.TableView;
171 import cx.fbn.nevernote.gui.TagTreeWidget;
172 import cx.fbn.nevernote.gui.Thumbnailer;
173 import cx.fbn.nevernote.gui.TrashTreeWidget;
174 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
175 import cx.fbn.nevernote.sql.DatabaseConnection;
176 import cx.fbn.nevernote.sql.WatchFolderRecord;
177 import cx.fbn.nevernote.threads.IndexRunner;
178 import cx.fbn.nevernote.threads.SyncRunner;
179 import cx.fbn.nevernote.threads.ThumbnailRunner;
180 import cx.fbn.nevernote.utilities.AESEncrypter;
181 import cx.fbn.nevernote.utilities.ApplicationLogger;
182 import cx.fbn.nevernote.utilities.FileImporter;
183 import cx.fbn.nevernote.utilities.FileUtils;
184 import cx.fbn.nevernote.utilities.ListManager;
185 import cx.fbn.nevernote.utilities.SyncTimes;
186 import cx.fbn.nevernote.xml.ExportData;
187 import cx.fbn.nevernote.xml.ImportData;
188 import cx.fbn.nevernote.xml.NoteFormatter;
189
190
191 public class NeverNote extends QMainWindow{
192         
193         QStatusBar                              statusBar;                                      // Application status bar
194         
195         DatabaseConnection              conn;
196         
197         MainMenuBar                             menuBar;                                        // Main menu bar
198         FindDialog                              find;                                           // Text search in note dialog
199         List<String>                    emitLog;                                        // Messages displayed in the status bar;
200         QSystemTrayIcon                 trayIcon;                                       // little tray icon
201         QMenu                                   trayMenu;                                       // System tray menu
202         QAction                                 trayExitAction;                         // Exit the application
203         QAction                                 trayShowAction;                         // toggle the show/hide action          
204         QAction                                 trayAddNoteAction;                      // Add a note from the system tray
205         QNetworkAccessManager   versionChecker;                         // Used when checking for new versions
206         
207     NotebookTreeWidget          notebookTree;                           // List of notebooks
208     AttributeTreeWidget         attributeTree;                          // List of note attributes
209     TagTreeWidget                       tagTree;                                        // list of user created tags
210     SavedSearchTreeWidget       savedSearchTree;                        // list of saved searches
211     TrashTreeWidget                     trashTree;                                      // Trashcan
212     TableView                           noteTableView;                          //      List of notes (the widget).
213
214     public BrowserWindow        browserWindow;                          // Window containing browser & labels
215     public QToolBar             toolBar;                                        // The tool bar under the menu
216     QComboBox                           searchField;                            // search filter bar on the toolbar;
217     QShortcut                           searchShortcut;                         // Shortcut to search bar
218     boolean                                     searchPerformed = false;        // Search was done?
219     QuotaProgressBar            quotaBar;                                       // The current quota usage
220     
221     ApplicationLogger           logger;
222     List<String>                        selectedNotebookGUIDs;          // List of notebook GUIDs
223     List<String>                        selectedTagGUIDs;                       // List of selected tag GUIDs
224     List<String>                        selectedNoteGUIDs;                      // List of selected notes
225     String                                      selectedSavedSearchGUID;        // Currently selected saved searches
226     private final HashMap<String, ExternalBrowse>       externalWindows;        // Notes being edited by an external window;
227     
228     NoteFilter                          filter;                                         // Note filter
229     String                                      currentNoteGuid;                        // GUID of the current note 
230     Note                                        currentNote;                            // The currently viewed note
231     boolean                                     noteDirty;                                      // Has the note been changed?
232     boolean                             inkNote;                   // if this is an ink note, it is read only
233     boolean                                     readOnly;                                       // Is this note read-only?
234         
235   
236     ListManager                         listManager;                                    // DB runnable task
237     
238     List<QTemporaryFile>        tempFiles;                                      // Array of temporary files;
239     
240     QTimer                                      indexTimer;                                     // timer to start the index thread
241     IndexRunner                         indexRunner;                            // thread to index notes
242     QThread                                     indexThread;
243     
244     QTimer                                      syncTimer;                                      // Sync on an interval
245     QTimer                                      syncDelayTimer;                         // Sync delay to free up database
246     SyncRunner                          syncRunner;                                     // thread to do a sync.
247     QThread                                     syncThread;                                     // Thread which talks to evernote
248     ThumbnailRunner                     thumbnailRunner;                        // Runner for thumbnail thread
249     QThread                                     thumbnailThread;                        // Thread that generates pretty pictures
250     QTimer                                      saveTimer;                                      // Timer to save note contents
251     
252     QTimer                                      authTimer;                                      // Refresh authentication
253     QTimer                                      externalFileSaveTimer;          // Save files altered externally
254     QTimer                                      thumbnailTimer;                         // Wakeup & scan for thumbnails
255     List<String>                        externalFiles;                          // External files to save later
256     List<String>                        importFilesKeep;                        // Auto-import files to save later
257     List<String>                        importFilesDelete;                      // Auto-import files to save later
258     
259     int                                         indexTime;                                      // how often to try and index
260     boolean                                     indexRunning;                           // Is indexing running?
261     boolean                                     indexDisabled;                          // Is indexing disabled?
262     
263     int                                         syncThreadsReady;                       // number of sync threads that are free
264     int                                         syncTime;                                       // Sync interval
265     boolean                                     syncRunning;                            // Is sync running?
266     boolean                                     automaticSync;                          // do sync automatically?
267     QTreeWidgetItem                     attributeTreeSelected;
268
269     QAction                             prevButton;                                     // Go to the previous item viewed
270     QAction                             nextButton;                                     // Go to the next item in the history
271     QAction                             downButton;                                     // Go to the next item in the list
272     QAction                             upButton;                                       // Go to the prev. item in the list;
273     QAction                             synchronizeButton;                      // Synchronize with Evernote
274     QAction                             allNotesButton;                         // Reset & view all notes
275     QTimer                              synchronizeAnimationTimer;      // Timer to change animation button
276     int                                 synchronizeIconAngle;           // Used to rotate sync icon
277     QAction                     printButton;                            // Print Button
278     QAction                             tagButton;                                      // Tag edit button
279     QAction                             attributeButton;                        // Attribute information button
280     QAction                     emailButton;                            // Email button
281     QAction                     deleteButton;                           // Delete button
282     QAction                             newButton;                                      // new Note Button;
283     QSpinBox                    zoomSpinner;                            // Zoom zoom
284     QAction                             searchClearButton;                      // Clear the search field
285     
286     SearchPanel                 searchLayout;                           // Widget to hold search field, zoom, & quota
287     
288     QSplitter                   mainLeftRightSplitter;          // main splitter for left/right side
289     QSplitter                   leftSplitter1;                          // first left hand splitter
290     QSplitter                   browserIndexSplitter;           // splitter between note index & note text
291     
292     QFileSystemWatcher  importKeepWatcher;                      // Watch & keep auto-import
293     QFileSystemWatcher  importDeleteWatcher;            // Watch & Delete auto-import
294     List<String>                importedFiles;                          // History of imported files (so we don't import twice)
295     
296     OnlineNoteHistory   historyWindow;                          // online history window 
297     List<NoteVersionId> versions;                                       // history versions
298     
299     QTimer                              threadMonitorTimer;                     // Timer to watch threads.
300     int                                 dbThreadDeadCount=0;            // number of consecutive dead times for the db thread
301     int                                 syncThreadDeadCount=0;          // number of consecutive dead times for the sync thread
302     int                                 indexThreadDeadCount=0;         // number of consecutive dead times for the index thread
303     int                                 notebookThreadDeadCount=0;      // number of consecutive dead times for the notebook thread
304     int                                 tagDeadCount=0;                         // number of consecutive dead times for the tag thread
305     int                                 trashDeadCount=0;                       // number of consecutive dead times for the trash thread
306     int                                 saveThreadDeadCount=0;          // number of consecutive dead times for the save thread
307     boolean                             disableTagThreadCheck=false;
308     boolean                             disableNotebookThreadCheck=false;
309     boolean                             disableTrashThreadCheck=false;
310     boolean                             disableSaveThreadCheck=false;
311     boolean                             disableSyncThreadCheck=false;
312     boolean                             disableIndexThreadCheck=false;
313     
314     HashMap<String, String>             noteCache;                      // Cash of note content 
315     HashMap<String, Boolean>    readOnlyCache;          // List of cashe notes that are read-only
316     HashMap<String, Boolean>    inkNoteCache;           // List of cache notes that are ink notes 
317     List<String>                historyGuids;                           // GUIDs of previously viewed items
318     int                                 historyPosition;                        // Position within the viewed items
319     boolean                             fromHistory;                            // Is this from the history queue?
320     String                              trashNoteGuid;                          // Guid to restore / set into or out of trash to save position
321     List<Thumbnailer>   thumbGenerators;                                // generate preview image
322     ThumbnailViewer             thumbnailViewer;                        // View preview thumbnail; 
323     boolean                             encryptOnShutdown;                      // should I encrypt when I close?
324     boolean                             decryptOnShutdown;                      // should I decrypt on shutdown;
325     String                              encryptCipher;                          // What cipher should I use?
326     Signal0                     minimizeToTray;
327     boolean                             windowMaximized = false;        // Keep track of the window state for restores
328     List<String>                pdfReadyQueue;                          // Queue of PDFs that are ready to be rendered.
329     List<QPixmap>               syncIcons;                                      // Array of icons used in sync animation
330     private boolean             closeAction = false;            // Used to say when to close or when to minimize
331     private static Logger log = Logger.getLogger(NeverNote.class); 
332     private String              saveLastPath;                           // last path we used
333     private final QTimer                messageTimer;                           // Timer to clear the status message.
334     private long                blockTime;                                      // When the app. is blocked, this is the time to unblock it.
335     
336     
337     String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
338         
339         
340     //***************************************************************
341     //***************************************************************
342     //** Constructor & main entry point
343     //***************************************************************
344     //***************************************************************
345     // Application Constructor  
346         @SuppressWarnings("static-access")
347         public NeverNote(DatabaseConnection dbConn)  {
348                 conn = dbConn;          
349                 if (conn.getConnection() == null) {
350                         String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
351                                 "is accessing the database or NeverNote is already running.\n\n" +
352                                 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
353                         
354             QMessageBox.critical(null, tr("Database Connection Error") ,msg);
355                         System.exit(16);
356                 }
357
358 //              thread().setPriority(Thread.MAX_PRIORITY);
359                 
360                 logger = new ApplicationLogger("nevernote.log");
361                 logger.log(logger.HIGH, "Starting Application");
362                 
363                 decryptOnShutdown = false;
364                 encryptOnShutdown = false;
365                 conn.checkDatabaseVersion();
366                 
367                 
368                 
369                 // Start building the invalid XML tables
370                 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
371                 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
372                 
373                 for (int i=0; i<elements.size(); i++) {
374                         Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
375                 }
376                 
377                 logger.log(logger.EXTREME, "Starting GUI build");
378
379                 QTranslator nevernoteTranslator = new QTranslator();
380                 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
381                 QApplication.instance().installTranslator(nevernoteTranslator);
382
383                 Global.originalPalette = QApplication.palette();
384                 QApplication.setStyle(Global.getStyle());
385                 if (Global.useStandardPalette())
386                         QApplication.setPalette(QApplication.style().standardPalette());
387         setWindowTitle("NeverNote");
388
389         mainLeftRightSplitter = new QSplitter();
390         setCentralWidget(mainLeftRightSplitter);
391         leftSplitter1 = new QSplitter();
392         leftSplitter1.setOrientation(Qt.Orientation.Vertical);
393                 
394         browserIndexSplitter = new QSplitter();
395         browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
396         
397         //* Setup threads & thread timers
398         int indexRunnerCount = Global.getIndexThreads();
399         indexRunnerCount = 1;
400         QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5);     // increase max thread count
401
402                 logger.log(logger.EXTREME, "Building list manager");
403         listManager = new ListManager(conn, logger);
404         
405                 logger.log(logger.EXTREME, "Building index runners & timers");
406         indexRunner = new IndexRunner("indexRunner.log", 
407                         Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
408                         Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
409                 indexThread = new QThread(indexRunner, "Index Thread");
410         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
411                 indexThread.start();
412                 
413         synchronizeAnimationTimer = new QTimer();
414         synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
415         
416                 indexTimer = new QTimer();
417                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
418                 indexTimer.start(indexTime);  // Start indexing timer
419                 indexTimer.timeout.connect(this, "indexTimer()");
420                 indexDisabled = false;
421                 indexRunning = false;
422                                 
423                 logger.log(logger.EXTREME, "Setting sync thread & timers");
424                 syncThreadsReady=1;
425                 syncRunner = new SyncRunner("syncRunner.log", 
426                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
427                                 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
428                 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
429                 syncTimer = new QTimer();
430                 syncTimer.timeout.connect(this, "syncTimer()");
431         syncRunner.status.message.connect(this, "setMessage(String)");
432         syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
433         syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
434         syncRunning = false;    
435                 if (syncTime > 0) {
436                         automaticSync = true;
437                         syncTimer.start(syncTime*60*1000);
438                 } else {
439                         automaticSync = false;
440                         syncTimer.stop();
441                 }
442                 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
443                 syncThread = new QThread(syncRunner, "Synchronization Thread");
444                 syncThread.start();
445                 
446                 
447                 logger.log(logger.EXTREME, "Starting thumnail thread");
448                 pdfReadyQueue = new ArrayList<String>();
449                 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", 
450                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
451                                 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
452                 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
453                 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
454                 thumbnailThread.start();
455                 thumbGenerators = new ArrayList<Thumbnailer>();
456                 thumbnailTimer = new QTimer();
457                 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
458                 thumbnailTimer();
459                 thumbnailTimer.setInterval(500*1000);  // Thumbnail every minute
460                 thumbnailTimer.start();
461                 
462                 logger.log(logger.EXTREME, "Starting authentication timer");
463                 authTimer = new QTimer();
464                 authTimer.timeout.connect(this, "authTimer()");
465                 authTimer.start(1000*60*15);
466                 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
467                 
468                 logger.log(logger.EXTREME, "Setting save note timer");
469                 saveTimer = new QTimer();
470                 saveTimer.timeout.connect(this, "saveNote()");
471                 if (Global.getAutoSaveInterval() > 0) {
472                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval()); 
473                         saveTimer.start();
474                 }
475                 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
476                 
477                 logger.log(logger.EXTREME, "Starting external file monitor timer");
478                 externalFileSaveTimer = new QTimer();
479                 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
480                 externalFileSaveTimer.setInterval(1000*5);   // save every 5 seconds;
481                 externalFiles = new ArrayList<String>();
482                 importFilesDelete = new ArrayList<String>();
483                 importFilesKeep = new ArrayList<String>();
484                 externalFileSaveTimer.start();
485                 
486         notebookTree = new NotebookTreeWidget(conn);
487         attributeTree = new AttributeTreeWidget();
488         tagTree = new TagTreeWidget(conn);
489         savedSearchTree = new SavedSearchTreeWidget();
490         trashTree = new TrashTreeWidget();
491         noteTableView = new TableView(logger, listManager);
492         
493         
494         searchField = new QComboBox();
495         searchField.setObjectName("searchField");
496         //setStyleSheet("QComboBox#searchField { background-color: yellow }");
497         searchField.setEditable(true);
498         searchField.activatedIndex.connect(this, "searchFieldChanged()");
499         searchField.setDuplicatesEnabled(false);
500         searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
501         searchShortcut = new QShortcut(this);
502         setupShortcut(searchShortcut, "Focus_Search");
503         searchShortcut.activated.connect(this, "focusSearch()");
504         
505         quotaBar = new QuotaProgressBar();
506         // Setup the zoom
507         zoomSpinner = new QSpinBox();
508         zoomSpinner.setMinimum(10);
509         zoomSpinner.setMaximum(1000);
510         zoomSpinner.setAccelerated(true);
511         zoomSpinner.setSingleStep(10);
512         zoomSpinner.setValue(100);
513         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
514         
515         searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
516         
517         
518         QGridLayout leftGrid = new QGridLayout();
519         leftSplitter1.setContentsMargins(5, 0, 0, 7);
520         leftSplitter1.setLayout(leftGrid);
521         leftGrid.addWidget(searchLayout,1,1);
522         leftGrid.addWidget(tagTree,2,1);
523         leftGrid.addWidget(attributeTree,3,1);
524         leftGrid.addWidget(savedSearchTree,4,1);
525         leftGrid.addWidget(trashTree,5, 1);
526         
527         // Setup the browser window
528         noteCache = new HashMap<String,String>();
529         readOnlyCache = new HashMap<String, Boolean>();
530         inkNoteCache = new HashMap<String, Boolean>();
531         browserWindow = new BrowserWindow(conn);
532
533         mainLeftRightSplitter.addWidget(leftSplitter1);
534         mainLeftRightSplitter.addWidget(browserIndexSplitter);
535         
536         if (Global.getListView() == Global.View_List_Wide) {
537                 browserIndexSplitter.addWidget(noteTableView);
538                 browserIndexSplitter.addWidget(browserWindow); 
539         } else {
540                 mainLeftRightSplitter.addWidget(noteTableView);
541                 mainLeftRightSplitter.addWidget(browserWindow); 
542         }
543         
544         // Setup the thumbnail viewer
545         thumbnailViewer = new ThumbnailViewer();
546         thumbnailViewer.upArrow.connect(this, "upAction()");
547         thumbnailViewer.downArrow.connect(this, "downAction()");
548         thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
549         thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
550         
551         //Setup external browser manager
552         externalWindows = new HashMap<String, ExternalBrowse>();
553
554         listManager.loadNotesIndex();
555         initializeNotebookTree();
556         initializeTagTree();
557         initializeSavedSearchTree();
558         attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
559         attributeTreeSelected = null;
560         initializeNoteTable();    
561
562                 selectedNoteGUIDs = new ArrayList<String>();
563                 statusBar = new QStatusBar();
564                 setStatusBar(statusBar);
565                 menuBar = new MainMenuBar(this);
566                 emitLog = new ArrayList<String>();
567                 
568                 tagTree.setDeleteAction(menuBar.tagDeleteAction);
569                 tagTree.setEditAction(menuBar.tagEditAction);
570                 tagTree.setAddAction(menuBar.tagAddAction);
571                 tagTree.setIconAction(menuBar.tagIconAction);
572                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
573                 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
574                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
575                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
576                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
577                 
578                 if (!Global.isWindowVisible("zoom")) {
579                         searchLayout.hideZoom();
580                         menuBar.hideZoom.setChecked(false);
581                 } 
582         
583                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
584                 notebookTree.setEditAction(menuBar.notebookEditAction);
585                 notebookTree.setAddAction(menuBar.notebookAddAction);
586                 notebookTree.setIconAction(menuBar.notebookIconAction);
587                 notebookTree.setStackAction(menuBar.notebookStackAction);
588                 notebookTree.setPublishAction(menuBar.notebookPublishAction);
589                 notebookTree.setShareAction(menuBar.notebookShareAction);
590                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
591                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
592                 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
593             notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
594                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
595
596                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
597                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
598                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
599                 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
600                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
601                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
602                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
603                         
604                 noteTableView.setAddAction(menuBar.noteAdd);
605                 noteTableView.setDeleteAction(menuBar.noteDelete);
606                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
607                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
608                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
609                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
610                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
611                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
612                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
613                 
614                 quotaBar.setMouseClickAction(menuBar.accountAction);
615                 
616                 trashTree.load();
617         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
618                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
619                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
620                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
621                 trashTree.updateCounts(listManager.getTrashCount());
622                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
623                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
624
625                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
626                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
627                 
628                 if (!Global.isWindowVisible("editorButtonBar"))
629                         toggleEditorButtonBar();
630                 if (!Global.isWindowVisible("leftPanel"))
631                         menuBar.hideLeftSide.setChecked(true);
632                 if (Global.isWindowVisible("noteInformation"))
633                         toggleNoteInformation();
634                 quotaBar.setVisible(Global.isWindowVisible("quota"));
635                 if (!quotaBar.isVisible())
636                         menuBar.hideQuota.setChecked(false);
637                 searchField.setVisible(Global.isWindowVisible("searchField"));
638                 if (!searchField.isVisible())
639                         menuBar.hideSearch.setChecked(false);
640                 
641                 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
642                         searchLayout.hide();
643                 
644                 setMenuBar(menuBar);
645                 setupToolBar();
646                 find = new FindDialog();
647                 find.getOkButton().clicked.connect(this, "doFindText()");
648                 
649                 // Setup the tray icon menu bar
650                 trayShowAction = new QAction("Show/Hide", this);
651                 trayExitAction = new QAction("Exit", this);
652                 trayAddNoteAction = new QAction("Add Note", this);
653                 
654                 trayExitAction.triggered.connect(this, "closeNeverNote()");
655                 trayAddNoteAction.triggered.connect(this, "addNote()");
656                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
657                 
658                 trayMenu = new QMenu(this);
659                 trayMenu.addAction(trayAddNoteAction);
660                 trayMenu.addAction(trayShowAction);
661                 trayMenu.addAction(trayExitAction);
662                 
663                 
664                 trayIcon = new QSystemTrayIcon(this);
665                 trayIcon.setToolTip("NeverNote");
666                 trayIcon.setContextMenu(trayMenu);
667                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
668
669                 currentNoteGuid="";
670                 currentNoteGuid = Global.getLastViewedNoteGuid();
671         historyGuids = new ArrayList<String>();
672         historyPosition = 0;
673         fromHistory = false;
674                 noteDirty = false;
675                 if (!currentNoteGuid.trim().equals("")) {
676                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
677                 }
678                 
679                 noteIndexUpdated(true);
680                 showColumns();
681                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
682                 if (menuBar.showEditorBar.isChecked())
683                 showEditorButtons(browserWindow);
684                 tagIndexUpdated(true);
685                 savedSearchIndexUpdated();
686                 notebookIndexUpdated();
687                 updateQuotaBar();
688         setupSyncSignalListeners();        
689         setupBrowserSignalListeners();
690         setupIndexListeners();
691               
692         
693         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
694         tagTree.showAllTags(true);
695
696                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
697         setWindowIcon(appIcon);
698         trayIcon.setIcon(appIcon);
699         if (Global.showTrayIcon())
700                 trayIcon.show();
701         else
702                 trayIcon.hide();
703         
704         scrollToGuid(currentNoteGuid);
705         if (Global.automaticLogin()) {
706                 remoteConnect();
707                 if (Global.isConnected)
708                         syncTimer();
709         }
710         setupFolderImports();
711         
712         loadStyleSheet();
713         restoreWindowState(true);
714         
715         if (Global.mimicEvernoteInterface) {
716                 notebookTree.selectGuid("");
717         }
718         
719         threadMonitorTimer = new QTimer();
720         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
721         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
722         
723         historyGuids.add(currentNoteGuid);
724         historyPosition = 1;
725         
726         menuBar.blockSignals(true);
727         menuBar.narrowListView.blockSignals(true);
728         menuBar.wideListView.blockSignals(true);
729         if (Global.getListView() == Global.View_List_Narrow) { 
730                 menuBar.narrowListView.setChecked(true);
731         }
732         else{ 
733                 menuBar.wideListView.setChecked(true);
734         }
735         menuBar.blockSignals(false);
736         menuBar.narrowListView.blockSignals(false);
737         menuBar.wideListView.blockSignals(false);
738
739         if (Global.getListView() == Global.View_List_Wide) {
740                 browserIndexSplitter.addWidget(noteTableView);
741                 browserIndexSplitter.addWidget(browserWindow); 
742         } else {
743                 mainLeftRightSplitter.addWidget(noteTableView);
744                 mainLeftRightSplitter.addWidget(browserWindow); 
745         }
746         
747                 messageTimer = new QTimer();
748                 messageTimer.timeout.connect(this, "clearMessage()");
749                 messageTimer.setInterval(1000*15);
750                 clearMessage();
751         
752         int sortCol = Global.getSortColumn();
753                 int sortOrder = Global.getSortOrder();
754                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
755                 if (Global.checkVersionUpgrade())
756                         checkForUpdates();
757         }
758                 
759         // Main entry point
760         public static void main(String[] args) {
761                 log.setLevel(Level.FATAL);
762                 QApplication.initialize(args);
763                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
764                 QSplashScreen splash = new QSplashScreen(pixmap);
765                 boolean showSplash;
766                 
767                 DatabaseConnection dbConn;
768
769         try {
770             initializeGlobalSettings(args);
771
772             showSplash = Global.isWindowVisible("SplashScreen");
773             if (showSplash)
774                 splash.show();
775
776             dbConn = setupDatabaseConnection();
777
778             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
779             Global.getFileManager().purgeResDirectory(true);
780
781         } catch (InitializationException e) {
782             // Fatal
783             e.printStackTrace();
784             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
785             return;
786         }
787
788         NeverNote application = new NeverNote(dbConn);
789
790                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
791                 if (Global.startMinimized()) 
792                         application.showMinimized();
793                 else {
794                         if (Global.wasWindowMaximized())
795                                 application.showMaximized();
796                         else
797                                 application.show();
798                 }
799                 
800                 if (showSplash)
801                         splash.finish(application);
802                 QApplication.exec();
803                 System.out.println("Goodbye.");
804                 QApplication.exit();
805         }
806
807     /**
808      * Open the internal database, or create if not present
809      *
810      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
811      */
812     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
813         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
814         
815         File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
816                 boolean dbExists = f.exists(); 
817                 if (!dbExists)
818                         Global.setDatabaseUrl("");
819         
820         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
821             boolean goodCheck = false;
822             while (!goodCheck) {
823                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
824                 dialog.exec();
825                 if (!dialog.okPressed())
826                     System.exit(0);
827                 Global.cipherPassword = dialog.getPassword();
828                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
829                         Global.getDatabaseUserPassword(), Global.cipherPassword);
830             }
831         }
832         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), 
833                         Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
834                         Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
835        return dbConn;
836     }
837     
838     // Encrypt the database upon shutdown
839     private void encryptOnShutdown() {
840         String dbPath= Global.getFileManager().getDbDirPath("");
841         String dbName = "NeverNote";
842         try {
843                 Statement st = conn.getConnection().createStatement();  
844                 st.execute("shutdown");
845                 if (QMessageBox.question(this, tr("Are you sure"), 
846                                 tr("Are you sure you wish to encrypt the database?"),
847                                 QMessageBox.StandardButton.Yes, 
848                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
849                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
850                         Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
851                         QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
852                 }
853         } catch (SQLException e) {
854                         e.printStackTrace();
855                 }       
856     }
857     
858     // Decrypt the database upon shutdown
859     private void decryptOnShutdown() {
860         String dbPath= Global.getFileManager().getDbDirPath("");
861         String dbName = "NeverNote";
862         try {
863                 Statement st = conn.getConnection().createStatement();  
864                 st.execute("shutdown");
865                 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
866                         encryptCipher = "AES";
867                 else
868                         encryptCipher = "XTEA";
869                 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure", 
870                                 "Are you sure you wish to decrypt the database?"),
871                                 QMessageBox.StandardButton.Yes, 
872                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
873
874                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
875                         Global.setDatabaseUrl("");
876                         QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
877                 }
878                 } catch (SQLException e) {
879                         e.printStackTrace();
880                 }       
881     }
882     /**
883      * Encrypt/Decrypt the local database
884      **/
885     public void doDatabaseEncrypt() {
886         // The database is not currently encrypted
887         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
888                 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
889                                 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
890                                 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
891                                 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
892                                 "Do you wish to proceed?"),
893                                 QMessageBox.StandardButton.Yes, 
894                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
895                                 return;
896                 }
897                 DBEncryptDialog dialog = new DBEncryptDialog();
898                 dialog.exec();
899                 if (dialog.okPressed()) {
900                         Global.cipherPassword = dialog.getPassword();
901                         encryptOnShutdown  = true;
902                         encryptCipher = dialog.getEncryptionMethod();
903                 }
904         } else {
905             DBEncryptDialog dialog = new DBEncryptDialog();
906             dialog.setWindowTitle("Database Decryption");
907             dialog.hideEncryption();
908             dialog.exec();
909             if (dialog.okPressed()) {
910                 if (!dialog.getPassword().equals(Global.cipherPassword)) {
911                         QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
912                         return;
913                 }
914                 decryptOnShutdown  = true;
915                 encryptCipher = "";
916             }
917         }
918         return;
919     }
920
921         private static void initializeGlobalSettings(String[] args) throws InitializationException {
922                 StartupConfig   startupConfig = new StartupConfig();
923
924         for (String arg : args) {
925             String lower = arg.toLowerCase();
926             if (lower.startsWith("--name="))
927                startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
928             if (lower.startsWith("--home="))
929                startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
930             if (lower.startsWith("--disable-viewing"))
931                startupConfig.setDisableViewing(true);
932         }
933                 Global.setup(startupConfig);
934     }
935
936     // Exit point
937         @Override
938         public void closeEvent(QCloseEvent event) {     
939                 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
940                         event.ignore();
941                         hide();
942                         return;
943                 }
944                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
945                 waitCursor(true);
946                 
947                 if (currentNote!= null & browserWindow!=null) {
948                         if (!currentNote.getTitle().equals(browserWindow.getTitle()))
949                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
950                 }
951                 saveNote();
952                 setMessage(tr("Beginning shutdown."));
953                 
954                 // Close down external windows
955                 Collection<ExternalBrowse> windows = externalWindows.values();
956                 Iterator<ExternalBrowse> iterator = windows.iterator();
957                 while (iterator.hasNext()) {
958                         ExternalBrowse browser = iterator.next();
959                         browser.windowClosing.disconnect();
960                         browser.close();
961                 }
962                 
963                 
964                 externalFileEditedSaver();
965                 if (Global.isConnected && Global.synchronizeOnClose()) {
966                         setMessage(tr("Performing synchronization before closing."));
967                         syncRunner.syncNeeded = true;
968                         syncRunner.addWork("SYNC");
969                 } else {
970                         syncRunner.keepRunning = false;
971                 }
972                 syncRunner.addWork("STOP");
973                 setMessage("Closing Program.");
974                 threadMonitorTimer.stop();
975
976                 thumbnailRunner.addWork("STOP");
977                 indexRunner.addWork("STOP");
978                 saveNote();
979                 listManager.stop();
980                 saveWindowState();
981
982                 if (tempFiles != null)
983                         tempFiles.clear();
984
985                 browserWindow.noteSignal.tagsChanged.disconnect();
986                 browserWindow.noteSignal.titleChanged.disconnect();
987                 browserWindow.noteSignal.noteChanged.disconnect();
988                 browserWindow.noteSignal.notebookChanged.disconnect();
989                 browserWindow.noteSignal.createdDateChanged.disconnect();
990                 browserWindow.noteSignal.alteredDateChanged.disconnect();
991                 syncRunner.searchSignal.listChanged.disconnect();
992                 syncRunner.tagSignal.listChanged.disconnect();
993         syncRunner.notebookSignal.listChanged.disconnect();
994         syncRunner.noteIndexSignal.listChanged.disconnect();
995
996                 if (isVisible())
997                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
998                 saveNoteColumnPositions();
999                 saveNoteIndexWidth();
1000                 
1001                 int width = notebookTree.columnWidth(0);
1002                 Global.setColumnWidth("notebookTreeName", width);
1003                 width = tagTree.columnWidth(0);
1004                 Global.setColumnWidth("tagTreeName", width);
1005                 
1006                 Global.saveWindowMaximized(isMaximized());
1007                 Global.saveCurrentNoteGuid(currentNoteGuid);
1008                         
1009                 int sortCol = noteTableView.proxyModel.sortColumn();
1010                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1011                 Global.setSortColumn(sortCol);
1012                 Global.setSortOrder(sortOrder);
1013                 
1014                 hide();
1015                 trayIcon.hide();
1016                 Global.keepRunning = false;
1017                 try {
1018                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1019                         if (indexRunner.thread().isAlive())
1020                                 indexRunner.thread().join(50);
1021                         if (!indexRunner.thread().isAlive())
1022                                 logger.log(logger.MEDIUM, "Index thread has stopped");
1023                         else {
1024                                 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1025                                 indexRunner.thread().interrupt();
1026                         }
1027                 } catch (InterruptedException e1) {
1028                         e1.printStackTrace();
1029                 }
1030                 
1031                 if (!syncRunner.thread().isAlive()) {
1032                         logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1033                         if (syncRunner.thread().isAlive()) {
1034                                 System.out.println(tr("Synchronizing.  Please be patient."));
1035                                 for(;syncRunner.thread().isAlive();) {
1036                                         try {
1037                                                 wait(10);
1038                                         } catch (InterruptedException e) {
1039                                                 e.printStackTrace();
1040                                         }
1041                                 }
1042                         }
1043                         logger.log(logger.MEDIUM, "Sync thread has stopped");
1044                 }
1045
1046                 if (encryptOnShutdown) {
1047                         encryptOnShutdown();
1048                 }
1049                 if (decryptOnShutdown) {
1050                         decryptOnShutdown();
1051                 }
1052                 try {
1053                         Global.getFileManager().purgeResDirectory(false);
1054                 } catch (InitializationException e) {
1055                         System.out.println(tr("Empty res directory purge failed"));
1056                         e.printStackTrace();
1057                 }
1058                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1059         }
1060
1061         @SuppressWarnings("unused")
1062         private void closeNeverNote() {
1063                 closeAction = true;
1064                 close();
1065         }
1066         public void setMessage(String s) {
1067                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1068                 
1069                 statusBar.show();
1070                 logger.log(logger.HIGH, "Message: " +s);
1071                 statusBar.showMessage(s);
1072                 emitLog.add(s);
1073                 
1074
1075                 messageTimer.stop();
1076                 messageTimer.setSingleShot(true);
1077                 messageTimer.start();
1078                 
1079                 
1080                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1081         }
1082         
1083         private void clearMessage() {
1084                 statusBar.clearMessage();
1085                 statusBar.hide();
1086         }
1087                 
1088         private void waitCursor(boolean wait) {
1089                 if (wait) {
1090                         if (QApplication.overrideCursor() == null)
1091                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1092                 }
1093                 else {
1094                         while (QApplication.overrideCursor() != null)
1095                                 QApplication.restoreOverrideCursor();
1096                 }
1097                 listManager.refreshCounters();
1098         }
1099         
1100         private void setupIndexListeners() {
1101 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1102 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1103                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1104                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1105         }
1106         private void setupSyncSignalListeners() {
1107                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1108         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1109         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1110         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1111         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1112         
1113                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1114                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1115                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1116                 
1117                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1118                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1119                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1120                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1121                 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1122                 
1123                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1124         }
1125         
1126         private void setupBrowserSignalListeners() {
1127                 setupBrowserWindowListeners(browserWindow, true);
1128         }
1129
1130         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1131                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1132                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1133             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1134             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1135             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1136             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1137             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1138             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1139             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1140             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1141             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1142             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1143             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1144             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1145             if (master) browser.focusLost.connect(this, "saveNote()");
1146             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1147         }
1148
1149         //**************************************************
1150         //* Setup shortcuts
1151         //**************************************************
1152         private void setupShortcut(QShortcut action, String text) {
1153                 if (!Global.shortcutKeys.containsAction(text))
1154                         return;
1155                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1156         }
1157         
1158         //***************************************************************
1159         //***************************************************************
1160         //* Settings and look & feel
1161         //***************************************************************
1162         //***************************************************************
1163         @SuppressWarnings("unused")
1164         private void settings() {
1165                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1166                 saveNoteColumnPositions();
1167                 saveNoteIndexWidth();
1168                 showColumns();
1169         ConfigDialog settings = new ConfigDialog(this);
1170         String dateFormat = Global.getDateFormat();
1171         String timeFormat = Global.getTimeFormat();
1172         
1173                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1174                 indexTimer.start(indexTime);  // reset indexing timer
1175         
1176         settings.exec();
1177         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1178         if (Global.showTrayIcon())
1179                 trayIcon.show();
1180         else
1181                 trayIcon.hide();
1182         showColumns();
1183         if (menuBar.showEditorBar.isChecked())
1184                 showEditorButtons(browserWindow);
1185         
1186         // Reset the save timer
1187         if (Global.getAutoSaveInterval() > 0)
1188                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1189         else
1190                 saveTimer.stop();
1191         
1192         // This is a hack to force a reload of the index in case the date or time changed.
1193 //        if (!dateFormat.equals(Global.getDateFormat()) ||
1194 //                      !timeFormat.equals(Global.getTimeFormat())) {
1195                 noteCache.clear();
1196                 readOnlyCache.clear();
1197                 inkNoteCache.clear();
1198                 noteIndexUpdated(true);
1199 //        }
1200         
1201         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1202         }
1203         // Restore things to the way they were
1204         private void restoreWindowState(boolean mainWindow) {
1205                 // We need to name things or this doesn't work.
1206                 setObjectName("NeverNote");
1207                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1208                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1209                 leftSplitter1.setObjectName("leftSplitter1");   
1210                 
1211                 // Restore the actual positions.
1212                 if (mainWindow)
1213                         restoreGeometry(Global.restoreGeometry(objectName()));
1214         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1215         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1216         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1217        
1218         }
1219         // Save window positions for the next start
1220         private void saveWindowState() {
1221                 Global.saveGeometry(objectName(), saveGeometry());
1222                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1223                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1224                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1225         }    
1226         // Load the style sheet
1227         private void loadStyleSheet() {
1228                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1229                 fileName = Global.getFileManager().getQssDirPath("default.qss");
1230                 QFile file = new QFile(fileName);
1231                 
1232                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1233                 if (!file.exists()) {
1234                         fileName = Global.getFileManager().getQssDirPath("default.qss");
1235                         file = new QFile(fileName);
1236                 }
1237                 file.open(OpenModeFlag.ReadOnly);
1238                 String styleSheet = file.readAll().toString();
1239                 file.close();
1240                 setStyleSheet(styleSheet);
1241         }
1242         // Save column positions for the next time
1243         private void saveNoteColumnPositions() {
1244                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1245                 Global.setColumnPosition("noteTableCreationPosition", position);
1246                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1247                 Global.setColumnPosition("noteTableTagPosition", position);
1248                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1249                 Global.setColumnPosition("noteTableNotebookPosition", position);
1250                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1251                 Global.setColumnPosition("noteTableChangedPosition", position);
1252                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1253                 Global.setColumnPosition("noteTableAuthorPosition", position);
1254                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1255                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1256                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1257                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1258                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1259                 Global.setColumnPosition("noteTableTitlePosition", position);
1260                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1261                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1262                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1263                 Global.setColumnPosition("noteTableGuidPosition", position);
1264                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1265                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1266
1267         }
1268         // Save column widths for the next time
1269         private void saveNoteIndexWidth() {
1270                 int width;
1271         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1272         Global.setColumnWidth("noteTableCreationPosition", width);
1273                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1274                 Global.setColumnWidth("noteTableChangedPosition", width);
1275                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1276                 Global.setColumnWidth("noteTableGuidPosition", width);
1277                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1278                 Global.setColumnWidth("noteTableNotebookPosition", width);
1279                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1280                 Global.setColumnWidth("noteTableTagPosition", width);
1281                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1282                 Global.setColumnWidth("noteTableTitlePosition", width);
1283                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1284                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1285                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1286                 Global.setColumnWidth("noteTableAuthorPosition", width);
1287                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1288                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1289                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1290                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1291                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1292                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1293                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1294                 Global.setColumnWidth("noteTableGuidPosition", width);
1295         }
1296         
1297         private void toggleSearchWindow() {
1298                 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1299         searchLayout.toggleSearchField();
1300         menuBar.hideSearch.setChecked(searchField.isVisible());
1301         Global.saveWindowVisible("searchField", searchField.isVisible());
1302         logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1303     }   
1304         private void toggleQuotaWindow() {
1305                 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1306         searchLayout.toggleQuotaBar();
1307         menuBar.hideQuota.setChecked(quotaBar.isVisible());
1308         Global.saveWindowVisible("quota", quotaBar.isVisible());
1309         logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1310     }   
1311         private void toggleZoomWindow() {
1312                 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1313         searchLayout.toggleZoom();
1314         menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1315         Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1316         logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1317     }   
1318         
1319         
1320         
1321     //***************************************************************
1322     //***************************************************************
1323     //** These functions deal with Notebook menu items
1324     //***************************************************************
1325     //***************************************************************
1326     // Setup the tree containing the user's notebooks.
1327     private void initializeNotebookTree() {       
1328         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1329 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1330         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1331         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1332         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1333     }   
1334     // Listener when a notebook is selected
1335         private void notebookTreeSelection() {
1336                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1337
1338                 clearTrashFilter();
1339                 clearAttributeFilter();
1340                 clearSavedSearchFilter();
1341                 if (Global.mimicEvernoteInterface) {
1342                         clearTagFilter();
1343                         searchField.clear();
1344                 }
1345                 menuBar.noteRestoreAction.setVisible(false);            
1346         menuBar.notebookEditAction.setEnabled(true);
1347         menuBar.notebookDeleteAction.setEnabled(true);
1348         menuBar.notebookPublishAction.setEnabled(true);
1349         menuBar.notebookShareAction.setEnabled(true);
1350         menuBar.notebookIconAction.setEnabled(true);
1351         menuBar.notebookStackAction.setEnabled(true);
1352         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1353         selectedNotebookGUIDs.clear();
1354                 String guid = "";
1355                 String stackName = "";
1356                 if (selections.size() > 0) {
1357                 guid = (selections.get(0).text(2));
1358                 stackName = selections.get(0).text(0);
1359         }
1360                 if (!Global.mimicEvernoteInterface) {
1361                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1362                         if (selections.size()==0) {
1363                                 selectedNotebookGUIDs.clear();
1364                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1365                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1366                                 }
1367                                 menuBar.notebookEditAction.setEnabled(false);
1368                                 menuBar.notebookDeleteAction.setEnabled(false);
1369                                 menuBar.notebookStackAction.setEnabled(false);
1370                                 menuBar.notebookIconAction.setEnabled(false);
1371                         }
1372                 }
1373         if (!guid.equals("") && !guid.equals("STACK")) {
1374                 selectedNotebookGUIDs.add(guid);
1375                 menuBar.notebookIconAction.setEnabled(true);
1376         } else {
1377                 menuBar.notebookIconAction.setEnabled(true);
1378                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1379                                 Notebook book = listManager.getNotebookIndex().get(j);
1380                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1381                                         selectedNotebookGUIDs.add(book.getGuid());
1382                         }
1383         }
1384         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1385         listManager.loadNotesIndex();
1386         noteIndexUpdated(false);
1387         listManager.refreshCounters = true;
1388         listManager.refreshCounters();
1389                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1390
1391     }
1392     private void clearNotebookFilter() {
1393         notebookTree.blockSignals(true);
1394         notebookTree.clearSelection();
1395                 menuBar.noteRestoreAction.setVisible(false);
1396         menuBar.notebookEditAction.setEnabled(false);
1397         menuBar.notebookDeleteAction.setEnabled(false);
1398         selectedNotebookGUIDs.clear();
1399         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1400         notebookTree.blockSignals(false);
1401     }
1402         // Triggered when the notebook DB has been updated
1403         private void notebookIndexUpdated() {
1404                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1405         
1406                 // Get the possible icons
1407                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1408         notebookTree.setIcons(icons);
1409         
1410         if (selectedNotebookGUIDs == null)
1411                         selectedNotebookGUIDs = new ArrayList<String>();
1412                 List<Notebook> books = conn.getNotebookTable().getAll();
1413                 for (int i=books.size()-1; i>=0; i--) {
1414                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1415                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1416                                         books.remove(i);
1417                                         j=listManager.getArchiveNotebookIndex().size();
1418                                 }
1419                         }
1420                 }
1421                 
1422                 
1423                 listManager.countNotebookResults(listManager.getNoteIndex());
1424                 notebookTree.blockSignals(true);
1425         notebookTree.load(books, listManager.getLocalNotebooks());
1426         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1427                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1428                 if (!found)
1429                         selectedNotebookGUIDs.remove(i);
1430         }
1431         listManager.refreshCounters = true;
1432         listManager.refreshCounters();
1433         notebookTree.blockSignals(false);
1434         
1435                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1436     }
1437     // Show/Hide note information
1438         private void toggleNotebookWindow() {
1439                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1440                 searchLayout.toggleNotebook();
1441         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1442         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1443         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1444     }   
1445         // Add a new notebook
1446         @SuppressWarnings("unused")
1447         private void addNotebook() {
1448                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1449                 NotebookEdit edit = new NotebookEdit();
1450                 edit.setNotebooks(listManager.getNotebookIndex());
1451                 edit.exec();
1452         
1453                 if (!edit.okPressed())
1454                         return;
1455         
1456                 Calendar currentTime = new GregorianCalendar();
1457                 Long l = new Long(currentTime.getTimeInMillis());
1458                 String randint = new String(Long.toString(l));
1459         
1460                 Notebook newBook = new Notebook();
1461                 newBook.setUpdateSequenceNum(0);
1462                 newBook.setGuid(randint);
1463                 newBook.setName(edit.getNotebook());
1464                 newBook.setServiceCreated(new Date().getTime());
1465                 newBook.setServiceUpdated(new Date().getTime());
1466                 newBook.setDefaultNotebook(false);
1467                 newBook.setPublished(false);
1468                 
1469                 listManager.getNotebookIndex().add(newBook);
1470                 if (edit.isLocal())
1471                         listManager.getLocalNotebooks().add(newBook.getGuid());
1472                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1473                 notebookIndexUpdated();
1474                 listManager.countNotebookResults(listManager.getNoteIndex());
1475 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1476                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1477         }
1478         // Edit an existing notebook
1479         @SuppressWarnings("unused")
1480         private void stackNotebook() {
1481                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1482                 StackNotebook edit = new StackNotebook();
1483                 
1484                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1485                 QTreeWidgetItem currentSelection;
1486                 for (int i=0; i<selections.size(); i++) {
1487                         currentSelection = selections.get(0);
1488                         String guid = currentSelection.text(2);
1489                         if (guid.equalsIgnoreCase("")) {
1490                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1491                                  return;
1492                         }
1493                         if (guid.equalsIgnoreCase("STACK")) {
1494                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1495                                  return;
1496                         }
1497                 }
1498
1499                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1500
1501                 
1502                 edit.exec();
1503         
1504                 if (!edit.okPressed())
1505                         return;
1506         
1507                 String stack = edit.getStackName();
1508                 
1509                 for (int i=0; i<selections.size(); i++) {
1510                         currentSelection = selections.get(i);
1511                         String guid = currentSelection.text(2);
1512                         listManager.updateNotebookStack(guid, stack);
1513                 }
1514                 notebookIndexUpdated();
1515                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1516         }
1517         // Edit an existing notebook
1518         @SuppressWarnings("unused")
1519         private void editNotebook() {
1520                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1521                 NotebookEdit edit = new NotebookEdit();
1522                 
1523                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1524                 QTreeWidgetItem currentSelection;
1525                 currentSelection = selections.get(0);
1526                 edit.setNotebook(currentSelection.text(0));
1527                 
1528                 String guid = currentSelection.text(2);
1529                 if (!guid.equalsIgnoreCase("STACK")) {
1530                         edit.setTitle(tr("Edit Notebook"));
1531                         edit.setNotebooks(listManager.getNotebookIndex());
1532                         edit.setLocalCheckboxEnabled(false);
1533                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1534                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1535                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1536                                         i=listManager.getNotebookIndex().size();
1537                                 }
1538                         }
1539                 } else {
1540                         edit.setTitle(tr("Edit Stack"));
1541                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1542                         edit.hideLocalCheckbox();
1543                         edit.hideDefaultCheckbox();
1544                 }
1545                 
1546                 edit.exec();
1547         
1548                 if (!edit.okPressed())
1549                         return;
1550         
1551                 
1552                 if (guid.equalsIgnoreCase("STACK")) {
1553                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1554                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1555                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1556                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1557                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1558                         }
1559                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1560                         currentSelection.setText(0, edit.getNotebook());
1561                         return;
1562                 }
1563                 
1564                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1565                 currentSelection.setText(0, edit.getNotebook());
1566                 
1567                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1568                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1569                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1570                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1571                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1572                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1573                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1574                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1575                                 }
1576                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1577                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1578                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1579                                         linkedNotebook.setShareName(edit.getNotebook());
1580                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1581                                 }
1582                                 i=listManager.getNotebookIndex().size();
1583                         }
1584                 }
1585                 
1586                 // Build a list of non-closed notebooks
1587                 List<Notebook> nbooks = new ArrayList<Notebook>();
1588                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1589                         boolean found=false;
1590                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1591                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1592                                         found = true;
1593                         }
1594                         if (!found)
1595                                 nbooks.add(listManager.getNotebookIndex().get(i));
1596                 }
1597                 
1598                 
1599                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1600                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1601                 browserWindow.setNotebookList(filteredBooks);
1602                 Iterator<String> set = externalWindows.keySet().iterator();
1603                 while(set.hasNext())
1604                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1605                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1606         }
1607         // Publish a notebook
1608         @SuppressWarnings("unused")
1609         private void publishNotebook() {
1610                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1611                 QTreeWidgetItem currentSelection;
1612                 currentSelection = selections.get(0);
1613                 String guid = currentSelection.text(2);
1614
1615                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1616                         return;
1617                 
1618                 Notebook n = null;
1619                 int position = 0;
1620                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1621                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1622                                 n = listManager.getNotebookIndex().get(i);
1623                                 position = i;
1624                                 i = listManager.getNotebookIndex().size();
1625                         }
1626                 }
1627                 if (n == null)
1628                         return;
1629                 
1630                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1631                 publish.exec();
1632                 
1633                 if (!publish.okClicked()) 
1634                         return;
1635                 
1636                 Publishing p = publish.getPublishing();
1637                 boolean isPublished = !publish.isStopPressed();
1638                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1639                 n.setPublished(isPublished);
1640                 n.setPublishing(p);
1641                 listManager.getNotebookIndex().set(position, n);
1642                 notebookIndexUpdated();
1643         }
1644         // Publish a notebook
1645         @SuppressWarnings("unused")
1646         private void shareNotebook() {
1647                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1648                 QTreeWidgetItem currentSelection;
1649                 currentSelection = selections.get(0);
1650                 String guid = currentSelection.text(2);
1651
1652                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1653                         return;
1654                 
1655                 Notebook n = null;;
1656                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1657                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1658                                 n = listManager.getNotebookIndex().get(i);
1659                                 i = listManager.getNotebookIndex().size();
1660                         }
1661                 }
1662                                 
1663                 String authToken = null;
1664                 if (syncRunner.isConnected)
1665                         authToken = syncRunner.authToken;
1666                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1667                 share.exec();
1668                 
1669         }
1670
1671         // Delete an existing notebook
1672         @SuppressWarnings("unused")
1673         private void deleteNotebook() {
1674                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1675                 boolean stacksFound = false;
1676                 boolean notebooksFound = false;
1677                 boolean assigned = false;
1678                 // Check if any notes have this notebook
1679                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1680         for (int i=0; i<selections.size(); i++) {
1681                 QTreeWidgetItem currentSelection;
1682                 currentSelection = selections.get(i);
1683                 String guid = currentSelection.text(2);
1684                 if (!guid.equalsIgnoreCase("STACK")) {
1685                         notebooksFound = true;
1686                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1687                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1688                                 if (noteGuid.equals(guid)) {
1689                                         assigned = true;
1690                                         j=listManager.getNoteIndex().size();
1691                                         i=selections.size();
1692                                 }
1693                         }
1694                 } else {
1695                         stacksFound = true;
1696                 }
1697         }
1698                 if (assigned) {
1699                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1700                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1701                         return;
1702                 }
1703                 
1704                 if (conn.getNotebookTable().getAll().size() == 1) {
1705                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1706                         return;
1707                 }
1708         
1709         // If all notebooks are clear, verify the delete
1710                 String msg1 = new String(tr("Delete selected notebooks?"));
1711                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1712                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1713                                 " not deleted unless selected?"));
1714                 String msg = "";
1715                 if (stacksFound && notebooksFound)
1716                         msg = msg3;
1717                 if (!stacksFound && notebooksFound)
1718                         msg = msg1;
1719                 if (stacksFound && !notebooksFound)
1720                         msg = msg2;
1721                 if (QMessageBox.question(this, tr("Confirmation"), msg,
1722                         QMessageBox.StandardButton.Yes, 
1723                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1724                         return;
1725                 }
1726                 
1727                 // If confirmed, delete the notebook
1728         for (int i=selections.size()-1; i>=0; i--) {
1729                 QTreeWidgetItem currentSelection;
1730                 currentSelection = selections.get(i);
1731                 String guid = currentSelection.text(2);
1732                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1733                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1734                         listManager.renameStack(currentSelection.text(0), "");
1735                 } else {
1736                         conn.getNotebookTable().expungeNotebook(guid, true);
1737                         listManager.deleteNotebook(guid);
1738                 }
1739         }
1740
1741                 notebookIndexUpdated();
1742 //        notebookTreeSelection();
1743 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1744 //        listManager.countNotebookResults(listManager.getNoteIndex());
1745         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1746         }
1747         // A note's notebook has been updated
1748         @SuppressWarnings("unused")
1749         private void updateNoteNotebook(String guid, String notebookGuid) {
1750                 
1751                 // Update the list manager
1752                 listManager.updateNoteNotebook(guid, notebookGuid);
1753                 listManager.countNotebookResults(listManager.getNoteIndex());
1754 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1755                 
1756                 // Find the name of the notebook
1757                 String notebookName = null;
1758                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1759                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1760                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1761                                 break;
1762                         }
1763                 }
1764                 
1765                 // If we found the name, update the browser window
1766                 if (notebookName != null) {
1767                         updateListNoteNotebook(guid, notebookName);
1768                         if (guid.equals(currentNoteGuid)) {
1769                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1770                                 if (pos >=0)
1771                                         browserWindow.notebookBox.setCurrentIndex(pos);
1772                         }
1773                 }
1774                 
1775                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1776                 if (guid.equals(currentNoteGuid)) {
1777                         if (currentNote != null) {
1778                                 currentNote.setNotebookGuid(notebookGuid);
1779                         }
1780                 }
1781         }
1782         // Open/close notebooks
1783         @SuppressWarnings("unused")
1784         private void closeNotebooks() {
1785                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1786                 na.exec();
1787                 if (!na.okClicked())
1788                         return;
1789                 
1790                 waitCursor(true);
1791                 listManager.getArchiveNotebookIndex().clear();
1792                 
1793                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1794                         String text = na.getClosedBookList().takeItem(i).text();
1795                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1796                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1797                                         Notebook n = listManager.getNotebookIndex().get(j);
1798                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1799                                         listManager.getArchiveNotebookIndex().add(n);
1800                                         j=listManager.getNotebookIndex().size();
1801                                 }
1802                         }
1803                 }
1804                 
1805                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1806                         String text = na.getOpenBookList().takeItem(i).text();
1807                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1808                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1809                                         Notebook n = listManager.getNotebookIndex().get(j);
1810                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1811                                         j=listManager.getNotebookIndex().size();
1812                                 }
1813                         }
1814                 }
1815                 notebookTreeSelection();
1816                 listManager.loadNotesIndex();
1817                 notebookIndexUpdated();
1818                 noteIndexUpdated(false);
1819                 reloadTagTree(true);
1820 //              noteIndexUpdated(false);
1821                 
1822                 // Build a list of non-closed notebooks
1823                 List<Notebook> nbooks = new ArrayList<Notebook>();
1824                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1825                         boolean found=false;
1826                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1827                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1828                                         found = true;
1829                         }
1830                         if (!found)
1831                                 nbooks.add(listManager.getNotebookIndex().get(i));
1832                 }
1833                 
1834                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1835                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1836                 browserWindow.setNotebookList(filteredBooks);
1837                 
1838                 // Update any external windows
1839                 Iterator<String> set = externalWindows.keySet().iterator();
1840                 while(set.hasNext())
1841                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1842                 
1843                 waitCursor(false);
1844         }
1845         // Change the notebook's icon
1846         @SuppressWarnings("unused")
1847         private void setNotebookIcon() {
1848                 boolean stackSelected = false;
1849                 boolean allNotebookSelected = false;
1850                 
1851                 QTreeWidgetItem currentSelection;
1852                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1853                 if (selections.size() == 0)
1854                         return;
1855                 
1856                 currentSelection = selections.get(0);   
1857                 String guid = currentSelection.text(2);
1858                 if (guid.equalsIgnoreCase(""))
1859                         allNotebookSelected = true;
1860                 if (guid.equalsIgnoreCase("STACK"))
1861                         stackSelected = true;
1862
1863                 QIcon currentIcon = currentSelection.icon(0);
1864                 QIcon icon;
1865                 SetIcon dialog;
1866                 
1867                 if (!stackSelected && !allNotebookSelected) {
1868                         icon = conn.getNotebookTable().getIcon(guid);
1869                         if (icon == null) {
1870                                 dialog = new SetIcon(currentIcon, saveLastPath);
1871                                 dialog.setUseDefaultIcon(true);
1872                         } else {
1873                                 dialog = new SetIcon(icon, saveLastPath);
1874                                 dialog.setUseDefaultIcon(false);
1875                         }
1876                 } else {
1877                         if (stackSelected) {
1878                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1879                         } else {
1880                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
1881                         }
1882                         if (icon == null) {
1883                                 dialog = new SetIcon(currentIcon, saveLastPath);
1884                                 dialog.setUseDefaultIcon(true);
1885                         } else {
1886                                 dialog = new SetIcon(icon, saveLastPath);
1887                                 dialog.setUseDefaultIcon(false);
1888                         }
1889                 }
1890                 dialog.exec();
1891                 if (dialog.okPressed()) {
1892                 saveLastPath = dialog.getPath();
1893
1894                         QIcon newIcon = dialog.getIcon();
1895                         if (stackSelected) {
1896                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1897                                 if (newIcon == null) {
1898                                         newIcon = new QIcon(iconPath+"books2.png");
1899                                 }
1900                                 currentSelection.setIcon(0,newIcon);
1901                                 return;
1902                         }
1903                         if (allNotebookSelected) {
1904                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1905                                 if (newIcon == null) {
1906                                         newIcon = new QIcon(iconPath+"notebook-green.png");
1907                                 }
1908                                 currentSelection.setIcon(0,newIcon);
1909                                 return;
1910                         }
1911                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1912                         if (newIcon == null) {
1913                                 boolean isPublished = false;;
1914                                 boolean found = false;
1915                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1916                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1917                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1918                                                 found = true;
1919                                         }
1920                                 }
1921                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1922                         }
1923                         currentSelection.setIcon(0, newIcon);
1924                 }
1925         
1926         }
1927         
1928         
1929     //***************************************************************
1930     //***************************************************************
1931     //** These functions deal with Tag menu items
1932     //***************************************************************
1933     //***************************************************************
1934         // Add a new notebook
1935         @SuppressWarnings("unused")
1936         private void addTag() {
1937                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1938                 TagEdit edit = new TagEdit();
1939                 edit.setTagList(listManager.getTagIndex());
1940                 edit.exec();
1941         
1942                 if (!edit.okPressed())
1943                         return;
1944         
1945                 Calendar currentTime = new GregorianCalendar();
1946                 Long l = new Long(currentTime.getTimeInMillis());
1947                 String randint = new String(Long.toString(l));
1948         
1949                 Tag newTag = new Tag();
1950                 newTag.setUpdateSequenceNum(0);
1951                 newTag.setGuid(randint);
1952                 newTag.setName(edit.getTag());
1953                 conn.getTagTable().addTag(newTag, true);
1954                 listManager.getTagIndex().add(newTag);
1955                 reloadTagTree(true);
1956                 
1957                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1958         }
1959         @SuppressWarnings("unused")
1960         private void reloadTagTree() {
1961                 reloadTagTree(false);
1962         }
1963         private void reloadTagTree(boolean reload) {
1964                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1965                 tagIndexUpdated(reload);
1966                 boolean filter = false;
1967                 if (reload)
1968                         listManager.countTagResults(listManager.getNoteIndex());
1969                 if (notebookTree.selectedItems().size() > 0 
1970                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1971                                                   filter = true;
1972                 if (tagTree.selectedItems().size() > 0)
1973                         filter = true;
1974                 tagTree.showAllTags(!filter);
1975                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1976         }
1977         // Edit an existing tag
1978         @SuppressWarnings("unused")
1979         private void editTag() {
1980                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1981                 TagEdit edit = new TagEdit();
1982                 edit.setTitle("Edit Tag");
1983                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1984                 QTreeWidgetItem currentSelection;
1985                 currentSelection = selections.get(0);
1986                 edit.setTag(currentSelection.text(0));
1987                 edit.setTagList(listManager.getTagIndex());
1988                 edit.exec();
1989         
1990                 if (!edit.okPressed())
1991                         return;
1992         
1993                 String guid = currentSelection.text(2);
1994                 currentSelection.setText(0,edit.getTag());
1995                 
1996                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1997                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1998                                 listManager.getTagIndex().get(i).setName(edit.getTag());
1999                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2000                                 updateListTagName(guid);
2001                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2002                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2003                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2004                                 return;
2005                         }
2006                 }
2007                 browserWindow.setTag(getTagNamesForNote(currentNote));
2008                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2009         }
2010         // Delete an existing tag
2011         @SuppressWarnings("unused")
2012         private void deleteTag() {
2013                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2014                 
2015                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2016                         QMessageBox.StandardButton.Yes, 
2017                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2018                                                         return;
2019                 }
2020                 
2021                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2022         for (int i=selections.size()-1; i>=0; i--) {
2023                 QTreeWidgetItem currentSelection;
2024                 currentSelection = selections.get(i);                   
2025                 removeTagItem(currentSelection.text(2));
2026         }
2027         tagIndexUpdated(true);
2028         tagTreeSelection();
2029         listManager.countTagResults(listManager.getNoteIndex());
2030 //              tagTree.updateCounts(listManager.getTagCounter());
2031         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2032         }
2033         // Remove a tag tree item.  Go recursively down & remove the children too
2034         private void removeTagItem(String guid) {
2035         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2036                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2037                 if (parent != null && parent.equals(guid)) {            
2038                         //Remove this tag's children
2039                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2040                 }
2041         }
2042         //Now, remove this tag
2043         removeListTagName(guid);
2044         conn.getTagTable().expungeTag(guid, true);                      
2045         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2046                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2047                         listManager.getTagIndex().remove(a);
2048                         return;
2049                 }
2050         }
2051         }
2052         // Setup the tree containing the user's tags
2053     private void initializeTagTree() {
2054         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2055 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2056 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2057         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2058         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2059         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2060     }
2061     // Listener when a tag is selected
2062         private void tagTreeSelection() {
2063         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2064                 
2065         clearTrashFilter();
2066         clearAttributeFilter();
2067         clearSavedSearchFilter();
2068         
2069                 menuBar.noteRestoreAction.setVisible(false);
2070                 
2071         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2072         QTreeWidgetItem currentSelection;
2073         selectedTagGUIDs.clear();
2074         for (int i=0; i<selections.size(); i++) {
2075                 currentSelection = selections.get(i);
2076                 selectedTagGUIDs.add(currentSelection.text(2));
2077         }
2078         if (selections.size() > 0) {
2079                 menuBar.tagEditAction.setEnabled(true);
2080                 menuBar.tagDeleteAction.setEnabled(true);
2081                 menuBar.tagIconAction.setEnabled(true);
2082         }
2083         else {
2084                 menuBar.tagEditAction.setEnabled(false);
2085                 menuBar.tagDeleteAction.setEnabled(false);
2086                 menuBar.tagIconAction.setEnabled(true);
2087         }
2088         listManager.setSelectedTags(selectedTagGUIDs);
2089         listManager.loadNotesIndex();
2090         noteIndexUpdated(false);
2091         listManager.refreshCounters = true;
2092         listManager.refreshCounters();
2093         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2094     }
2095     // trigger the tag index to be refreshed
2096     @SuppressWarnings("unused")
2097         private void tagIndexUpdated() {
2098         tagIndexUpdated(true);
2099     }
2100     private void tagIndexUpdated(boolean reload) {
2101         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2102                 if (selectedTagGUIDs == null)
2103                         selectedTagGUIDs = new ArrayList<String>();
2104                 if (reload)
2105                         listManager.reloadTagIndex();
2106
2107                 tagTree.blockSignals(true);
2108                 if (reload) {
2109                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2110                         tagTree.load(listManager.getTagIndex());
2111                 }
2112
2113         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2114                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2115                 if (!found)
2116                         selectedTagGUIDs.remove(i);
2117         }
2118         tagTree.blockSignals(false);
2119         
2120                 browserWindow.setTag(getTagNamesForNote(currentNote));
2121         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2122     }   
2123     // Show/Hide note information
2124         private void toggleTagWindow() {
2125                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2126         if (tagTree.isVisible())
2127                 tagTree.hide();
2128         else
2129                 tagTree.show();
2130         menuBar.hideTags.setChecked(tagTree.isVisible());
2131         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2132         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2133     }   
2134         // A note's tags have been updated
2135         @SuppressWarnings("unused")
2136         private void updateNoteTags(String guid, List<String> tags) {
2137                 // Save any new tags.  We'll need them later.
2138                 List<String> newTags = new ArrayList<String>();
2139                 for (int i=0; i<tags.size(); i++) {
2140                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2141                                 newTags.add(tags.get(i));
2142                 }
2143                 
2144                 listManager.saveNoteTags(guid, tags);
2145                 listManager.countTagResults(listManager.getNoteIndex());
2146                 StringBuffer names = new StringBuffer("");
2147                 for (int i=0; i<tags.size(); i++) {
2148                         names = names.append(tags.get(i));
2149                         if (i<tags.size()-1) {
2150                                 names.append(Global.tagDelimeter + " ");
2151                         }
2152                 }
2153                 browserWindow.setTag(names.toString());
2154                 noteDirty = true;
2155                 
2156                 // Now, we need to add any new tags to the tag tree
2157                 for (int i=0; i<newTags.size(); i++) 
2158                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2159         }
2160         // Get a string containing all tag names for a note
2161         private String getTagNamesForNote(Note n) {
2162                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2163                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2164                         return "";
2165                 StringBuffer buffer = new StringBuffer(100);
2166                 Vector<String> v = new Vector<String>();
2167                 List<String> guids = n.getTagGuids();
2168                 
2169                 if (guids == null) 
2170                         return "";
2171                 
2172                 for (int i=0; i<guids.size(); i++) {
2173                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2174                 }
2175                 Comparator<String> comparator = Collections.reverseOrder();
2176                 Collections.sort(v,comparator);
2177                 Collections.reverse(v);
2178                 
2179                 for (int i = 0; i<v.size(); i++) {
2180                         if (i>0) 
2181                                 buffer.append(", ");
2182                         buffer.append(v.get(i));
2183                 }
2184                 
2185                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2186                 return buffer.toString();
2187         }       
2188         // Tags were added via dropping notes from the note list
2189         @SuppressWarnings("unused")
2190         private void tagsAdded(String noteGuid, String tagGuid) {
2191                 String tagName = null;
2192                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2193                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2194                                 tagName = listManager.getTagIndex().get(i).getName();
2195                                 i=listManager.getTagIndex().size();
2196                         }
2197                 }
2198                 if (tagName == null)
2199                         return;
2200                 
2201                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2202                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2203                                 List<String> tagNames = new ArrayList<String>();
2204                                 tagNames.add(new String(tagName));
2205                                 Note n = listManager.getMasterNoteIndex().get(i);
2206                                 for (int j=0; j<n.getTagNames().size(); j++) {
2207                                         tagNames.add(new String(n.getTagNames().get(j)));
2208                                 }
2209                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2210                                 if (n.getGuid().equals(currentNoteGuid)) {
2211                                         Collections.sort(tagNames);
2212                                         String display = "";
2213                                         for (int j=0; j<tagNames.size(); j++) {
2214                                                 display = display+tagNames.get(j);
2215                                                 if (j+2<tagNames.size()) 
2216                                                         display = display+Global.tagDelimeter+" ";
2217                                         }
2218                                         browserWindow.setTag(display);
2219                                 }
2220                                 i=listManager.getMasterNoteIndex().size();
2221                         }
2222                 }
2223                 
2224                 
2225                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2226         }
2227         private void clearTagFilter() {
2228                 tagTree.blockSignals(true);
2229                 tagTree.clearSelection();
2230                 menuBar.noteRestoreAction.setVisible(false);
2231                 menuBar.tagEditAction.setEnabled(false);
2232                 menuBar.tagDeleteAction.setEnabled(false);
2233                 menuBar.tagIconAction.setEnabled(false);
2234                 selectedTagGUIDs.clear();
2235         listManager.setSelectedTags(selectedTagGUIDs);
2236         tagTree.blockSignals(false);
2237         }
2238         // Change the icon for a tag
2239         @SuppressWarnings("unused")
2240         private void setTagIcon() {
2241                 QTreeWidgetItem currentSelection;
2242                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2243                 if (selections.size() == 0)
2244                         return;
2245                 
2246                 currentSelection = selections.get(0);   
2247                 String guid = currentSelection.text(2);
2248
2249                 QIcon currentIcon = currentSelection.icon(0);
2250                 QIcon icon = conn.getTagTable().getIcon(guid);
2251                 SetIcon dialog;
2252                 if (icon == null) {
2253                         dialog = new SetIcon(currentIcon, saveLastPath);
2254                         dialog.setUseDefaultIcon(true);
2255                 } else {
2256                         dialog = new SetIcon(icon, saveLastPath);
2257                         dialog.setUseDefaultIcon(false);
2258                 }
2259                 dialog.exec();
2260                 if (dialog.okPressed()) {
2261                 saveLastPath = dialog.getPath();
2262                         QIcon newIcon = dialog.getIcon();
2263                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2264                         if (newIcon == null) 
2265                                 newIcon = new QIcon(iconPath+"tag.png");
2266                         currentSelection.setIcon(0, newIcon);
2267                 }
2268         
2269         }
2270
2271         
2272     //***************************************************************
2273     //***************************************************************
2274     //** These functions deal with Saved Search menu items
2275     //***************************************************************
2276     //***************************************************************
2277         // Add a new notebook
2278         @SuppressWarnings("unused")
2279         private void addSavedSearch() {
2280                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2281                 SavedSearchEdit edit = new SavedSearchEdit();
2282                 edit.setSearchList(listManager.getSavedSearchIndex());
2283                 edit.exec();
2284         
2285                 if (!edit.okPressed())
2286                         return;
2287         
2288                 Calendar currentTime = new GregorianCalendar();         
2289                 Long l = new Long(currentTime.getTimeInMillis());
2290                 String randint = new String(Long.toString(l));
2291         
2292                 SavedSearch search = new SavedSearch();
2293                 search.setUpdateSequenceNum(0);
2294                 search.setGuid(randint);
2295                 search.setName(edit.getName());
2296                 search.setQuery(edit.getQuery());
2297                 search.setFormat(QueryFormat.USER);
2298                 listManager.getSavedSearchIndex().add(search);
2299                 conn.getSavedSearchTable().addSavedSearch(search, true);
2300                 savedSearchIndexUpdated();
2301                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2302         }
2303         // Edit an existing tag
2304         @SuppressWarnings("unused")
2305         private void editSavedSearch() {
2306                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2307                 SavedSearchEdit edit = new SavedSearchEdit();
2308                 edit.setTitle(tr("Edit Search"));
2309                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2310                 QTreeWidgetItem currentSelection;
2311                 currentSelection = selections.get(0);
2312                 String guid = currentSelection.text(1);
2313                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2314                 edit.setName(currentSelection.text(0));
2315                 edit.setQuery(s.getQuery());
2316                 edit.setSearchList(listManager.getSavedSearchIndex());
2317                 edit.exec();
2318         
2319                 if (!edit.okPressed())
2320                         return;
2321         
2322                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2323                 SavedSearch search = null;
2324                 boolean found = false;
2325                 for (int i=0; i<list.size(); i++) {
2326                         search = list.get(i);
2327                         if (search.getGuid().equals(guid)) {
2328                                 i=list.size();
2329                                 found = true;
2330                         }
2331                 }
2332                 if (!found)
2333                         return;
2334                 search.setName(edit.getName());
2335                 search.setQuery(edit.getQuery());
2336                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2337                 savedSearchIndexUpdated();
2338                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2339         }
2340         // Delete an existing tag
2341         @SuppressWarnings("unused")
2342         private void deleteSavedSearch() {
2343                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2344                 
2345                 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2346                         QMessageBox.StandardButton.Yes, 
2347                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2348                                                         return;
2349                 }
2350                 
2351                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2352         for (int i=selections.size()-1; i>=0; i--) {
2353                 QTreeWidgetItem currentSelection;
2354                 currentSelection = selections.get(i);
2355                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2356                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2357                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2358                                 listManager.getSavedSearchIndex().remove(j);
2359                                 j=listManager.getSavedSearchIndex().size()+1;
2360                         }
2361                 }
2362                 selections.remove(i);
2363         }
2364         savedSearchIndexUpdated();
2365         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2366         }
2367     // Setup the tree containing the user's tags
2368     private void initializeSavedSearchTree() {
2369         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2370         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2371         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2372     }
2373     // Listener when a tag is selected
2374     @SuppressWarnings("unused")
2375         private void savedSearchTreeSelection() {
2376         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2377
2378         clearNotebookFilter();
2379         clearTagFilter();
2380         clearTrashFilter();
2381         clearAttributeFilter();
2382         
2383         String currentGuid = selectedSavedSearchGUID;
2384         menuBar.savedSearchEditAction.setEnabled(true);
2385         menuBar.savedSearchDeleteAction.setEnabled(true);
2386         menuBar.savedSearchIconAction.setEnabled(true);
2387         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2388         QTreeWidgetItem currentSelection;
2389         selectedSavedSearchGUID = "";
2390         for (int i=0; i<selections.size(); i++) {
2391                 currentSelection = selections.get(i);
2392                 if (currentSelection.text(1).equals(currentGuid)) {
2393                         currentSelection.setSelected(false);
2394                 } else {
2395                         selectedSavedSearchGUID = currentSelection.text(1);
2396                 }
2397 //              i = selections.size() +1;
2398         }
2399         
2400         // There is the potential for no notebooks to be selected if this 
2401         // happens then we make it look like all notebooks were selecetd.
2402         // If that happens, just select the "all notebooks"
2403         if (selections.size()==0) {
2404                 clearSavedSearchFilter();
2405         }
2406         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2407         
2408         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2409     }
2410     private void clearSavedSearchFilter() {
2411         menuBar.savedSearchEditAction.setEnabled(false);
2412         menuBar.savedSearchDeleteAction.setEnabled(false);
2413         menuBar.savedSearchIconAction.setEnabled(false);
2414         savedSearchTree.blockSignals(true);
2415         savedSearchTree.clearSelection();
2416         savedSearchTree.blockSignals(false);
2417         selectedSavedSearchGUID = "";
2418         searchField.setEditText("");
2419         searchPerformed = false;
2420         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2421     }
2422     // trigger the tag index to be refreshed
2423         private void savedSearchIndexUpdated() { 
2424                 if (selectedSavedSearchGUID == null)
2425                         selectedSavedSearchGUID = new String();
2426                 savedSearchTree.blockSignals(true);
2427                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2428         savedSearchTree.load(listManager.getSavedSearchIndex());
2429         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2430         savedSearchTree.blockSignals(false);
2431     }
2432     // trigger when the saved search selection changes
2433     @SuppressWarnings("unused")
2434         private void updateSavedSearchSelection() {
2435                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2436                 
2437         menuBar.savedSearchEditAction.setEnabled(true);
2438         menuBar.savedSearchDeleteAction.setEnabled(true);
2439         menuBar.savedSearchIconAction.setEnabled(true);
2440         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2441
2442         if (selections.size() > 0) {
2443                 menuBar.savedSearchEditAction.setEnabled(true);
2444                 menuBar.savedSearchDeleteAction.setEnabled(true);
2445                 menuBar.savedSearchIconAction.setEnabled(true);
2446                 selectedSavedSearchGUID = selections.get(0).text(1);
2447                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2448                 searchField.setEditText(s.getQuery());
2449         } else { 
2450                 menuBar.savedSearchEditAction.setEnabled(false);
2451                 menuBar.savedSearchDeleteAction.setEnabled(false);
2452                 menuBar.savedSearchIconAction.setEnabled(false);
2453                 selectedSavedSearchGUID = "";
2454                 searchField.setEditText("");
2455         }
2456         searchFieldChanged();
2457         
2458                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2459
2460         
2461     }
2462     // Show/Hide note information
2463         private void toggleSavedSearchWindow() {
2464                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2465         if (savedSearchTree.isVisible())
2466                 savedSearchTree.hide();
2467         else
2468                 savedSearchTree.show();
2469         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2470                                 
2471                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2472         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2473     }
2474         // Change the icon for a saved search
2475         @SuppressWarnings("unused")
2476         private void setSavedSearchIcon() {
2477                 QTreeWidgetItem currentSelection;
2478                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2479                 if (selections.size() == 0)
2480                         return;
2481                 
2482                 currentSelection = selections.get(0);   
2483                 String guid = currentSelection.text(1);
2484
2485                 QIcon currentIcon = currentSelection.icon(0);
2486                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2487                 SetIcon dialog;
2488                 if (icon == null) {
2489                         dialog = new SetIcon(currentIcon, saveLastPath);
2490                         dialog.setUseDefaultIcon(true);
2491                 } else {
2492                         dialog = new SetIcon(icon, saveLastPath);
2493                         dialog.setUseDefaultIcon(false);
2494                 }
2495                 dialog.exec();
2496                 if (dialog.okPressed()) {
2497                 saveLastPath = dialog.getPath();
2498                         QIcon newIcon = dialog.getIcon();
2499                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2500                         if (newIcon == null) 
2501                                 newIcon = new QIcon(iconPath+"search.png");
2502                         currentSelection.setIcon(0, newIcon);
2503                 }
2504         
2505         }
2506         
2507         
2508         
2509         
2510     //***************************************************************
2511     //***************************************************************
2512     //** These functions deal with Help menu & tool menu items
2513     //***************************************************************
2514     //***************************************************************
2515         // Show database status
2516         @SuppressWarnings("unused")
2517         private void databaseStatus() {
2518                 waitCursor(true);
2519                 indexRunner.interrupt = true;
2520                 int dirty = conn.getNoteTable().getDirtyCount();
2521                 int unindexed = conn.getNoteTable().getUnindexedCount();
2522                 DatabaseStatus status = new DatabaseStatus();
2523                 status.setUnsynchronized(dirty);
2524                 status.setUnindexed(unindexed);
2525                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2526                 status.setNotebookCount(listManager.getNotebookIndex().size());
2527                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2528                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2529                 status.setTagCount(listManager.getTagIndex().size());
2530                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2531                 status.setWordCount(conn.getWordsTable().getWordCount());
2532                 waitCursor(false);
2533                 status.exec();
2534         }
2535         // Compact the database
2536         @SuppressWarnings("unused")
2537         private void compactDatabase() {
2538         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2539                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2540                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2541                                 "and NeverNote will be unresponsive until it is complete.  Do you wish to continue?"),
2542                                 QMessageBox.StandardButton.Yes, 
2543                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2544                                                         return;
2545                 }
2546                 setMessage("Compacting database.");
2547                 waitCursor(true);
2548                 listManager.compactDatabase();
2549                 waitCursor(false);
2550                 setMessage("Database compact is complete.");            
2551         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2552     }
2553         @SuppressWarnings("unused")
2554         private void accountInformation() {
2555                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2556                 AccountDialog dialog = new AccountDialog();
2557                 dialog.show();
2558                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2559         }
2560         @SuppressWarnings("unused")
2561         private void releaseNotes() {
2562                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2563                 QDialog dialog = new QDialog(this);
2564                 QHBoxLayout layout = new QHBoxLayout();
2565                 QTextEdit textBox = new QTextEdit();
2566                 layout.addWidget(textBox);
2567                 textBox.setReadOnly(true);
2568                 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2569                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2570                 QIODevice.OpenModeFlag.Text)))
2571                         return;
2572                 textBox.setText(file.readAll().toString());
2573                 file.close();
2574                 dialog.setWindowTitle(tr("Release Notes"));
2575                 dialog.setLayout(layout);
2576                 dialog.show();
2577                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2578         }
2579         // Called when user picks Log from the help menu
2580         @SuppressWarnings("unused")
2581         private void logger() {
2582                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2583                 LogFileDialog dialog = new LogFileDialog(emitLog);
2584                 dialog.exec();
2585                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2586         }
2587         // Menu option "help/about" was selected
2588         @SuppressWarnings("unused")
2589         private void about() {
2590                 logger.log(logger.HIGH, "Entering NeverNote.about");
2591                 QMessageBox.about(this, 
2592                                                 tr("About NeverNote"),
2593                                                 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2594                                                 +Global.version
2595                                                 +tr("<hr></center>Evernote"
2596                                                                 +"An Open Source Evernote Client.<br><br>" 
2597                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2598                                                                 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2599                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2600                                                                 +"PDFRenderer is licened under the LGPL<br>"
2601                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2602                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2603                                                                 +"Jazzy is licened under the LGPL<br>"
2604                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));     
2605                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2606         }
2607         // Hide the entire left hand side
2608         @SuppressWarnings("unused")
2609         private void toggleLeftSide() {
2610                 boolean hidden;
2611                 
2612                 hidden = !menuBar.hideLeftSide.isChecked();
2613                 menuBar.hideLeftSide.setChecked(!hidden);
2614                 
2615                 if (!hidden) 
2616                         leftSplitter1.setHidden(true);
2617                 else
2618                         leftSplitter1.setHidden(false);
2619                 
2620                 Global.saveWindowVisible("leftPanel", hidden);
2621                 
2622         }
2623         public void checkForUpdates() {
2624                 // Send off thread to check for a new version
2625                 versionChecker = new QNetworkAccessManager(this);
2626                 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2627                 QNetworkRequest request = new QNetworkRequest();
2628                 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2629                 versionChecker.get(request);
2630         }
2631         @SuppressWarnings("unused")
2632         private void upgradeFileRead(QNetworkReply reply) {
2633                 if (!reply.isReadable())
2634                         return;
2635                 
2636                 String winVersion = Global.version;
2637                 String osxVersion = Global.version;
2638                 String linuxVersion = Global.version;
2639                 String linux64Version = Global.version;
2640                 String version = Global.version;
2641                 
2642                 // Determine the versions available
2643                 QByteArray data = reply.readLine();
2644                 while (data != null && !reply.atEnd()) {
2645                         String line = data.toString();
2646                         String lineVersion;
2647                         if (line.contains(":")) 
2648                                 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2649                         else
2650                                 lineVersion = "";
2651                         if (line.toLowerCase().contains("windows")) 
2652                                 winVersion = lineVersion;
2653                         else if (line.toLowerCase().contains("os-x")) 
2654                                 osxVersion = lineVersion;
2655                         else if (line.toLowerCase().contains("linux amd64")) 
2656                                 linux64Version = lineVersion;
2657                         else if (line.toLowerCase().contains("linux i386")) 
2658                                 linuxVersion = lineVersion;
2659                         else if (line.toLowerCase().contains("default")) 
2660                                 version = lineVersion;
2661                         
2662                         // Read the next line
2663                         data = reply.readLine();
2664                 }
2665                 
2666                 // Now we need to determine what system we are on.
2667                 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2668                         version = winVersion;
2669                 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2670                         version = osxVersion;
2671                 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2672                         if (System.getProperty("os.arch").contains("amd64") ||
2673                                 System.getProperty("os.arch").contains("x86_64"))
2674                                         version = linux64Version;
2675                         else
2676                                 version = linuxVersion;
2677                 }
2678                 
2679                 
2680                 for (String validVersion : Global.validVersions) {
2681                         if (version.equals(validVersion))
2682                                 return;
2683                 }
2684                 
2685                 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2686                 dialog.exec();
2687                 if (dialog.remindMe())
2688                         Global.setCheckVersionUpgrade(true);
2689                 else
2690                         Global.setCheckVersionUpgrade(false);
2691         }
2692                 
2693         
2694     //***************************************************************
2695     //***************************************************************
2696     //** These functions deal with the Toolbar
2697     //***************************************************************
2698     //*************************************************************** 
2699         @SuppressWarnings("unused")
2700         private void focusSearch() {
2701                 searchField.setFocus();
2702         }
2703
2704         // Text in the search bar has been cleared
2705         private void searchFieldCleared() {
2706                 saveNote();
2707                 
2708                 // This is done because we want to force a reload of
2709                 // images.  Some images we may want to highlight the text.
2710                 readOnlyCache.clear();
2711                 inkNoteCache.clear();
2712                 noteCache.clear();
2713                 QWebSettings.setMaximumPagesInCache(0);
2714                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2715         
2716                 searchField.setEditText("");
2717                 saveNoteColumnPositions();
2718                 saveNoteIndexWidth();
2719                 noteIndexUpdated(true);
2720                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2721                         currentNote = listManager.getNoteIndex().get(0);
2722                         currentNoteGuid = currentNote.getGuid();
2723                 }
2724                 if (currentNote != null)
2725                         loadNoteBrowserInformation(browserWindow);
2726         }
2727         // text in the search bar changed.  We only use this to tell if it was cleared, 
2728         // otherwise we trigger off searchFieldChanged.
2729         @SuppressWarnings("unused")
2730         private void searchFieldTextChanged(String text) {
2731                 QWebSettings.setMaximumPagesInCache(0);
2732                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2733
2734                 if (text.trim().equals("")) {
2735                         searchFieldCleared();
2736                         if (searchPerformed) {
2737
2738                                 // This is done because we want to force a reload of
2739                                 // images.  Some images we may want to highlight the text.
2740                                 noteCache.clear();
2741                                 readOnlyCache.clear();
2742                                 inkNoteCache.clear();
2743                                 
2744                                 listManager.setEnSearch("");
2745                                 listManager.loadNotesIndex();
2746                                 refreshEvernoteNote(true);
2747                                 noteIndexUpdated(false);
2748                         }
2749                         searchPerformed = false;
2750                 }
2751         }
2752     // Text in the toolbar has changed
2753     private void searchFieldChanged() {
2754         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2755         noteCache.clear();
2756         readOnlyCache.clear();
2757         inkNoteCache.clear();
2758         saveNoteColumnPositions();
2759         saveNoteIndexWidth();
2760         String text = searchField.currentText();
2761         listManager.setEnSearch(text.trim());
2762         listManager.loadNotesIndex();
2763         noteIndexUpdated(false);
2764         refreshEvernoteNote(true);
2765         searchPerformed = true;
2766         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2767     }
2768
2769     // Build the window tool bar
2770     private void setupToolBar() {
2771         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2772         toolBar = addToolBar(tr("Tool Bar"));   
2773         menuBar.setupToolBarVisible();
2774         if (!Global.isWindowVisible("toolBar"))
2775                 toolBar.setVisible(false);
2776         else
2777                 toolBar.setVisible(true);
2778
2779 //      toolBar.addWidget(menuBar);
2780 //      menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2781 //      toolBar.addSeparator();
2782         prevButton = toolBar.addAction("Previous");
2783         QIcon prevIcon = new QIcon(iconPath+"back.png");
2784         prevButton.setIcon(prevIcon);
2785         prevButton.triggered.connect(this, "previousViewedAction()");   
2786         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2787         
2788         nextButton = toolBar.addAction("Next");
2789         QIcon nextIcon = new QIcon(iconPath+"forward.png");
2790         nextButton.setIcon(nextIcon);
2791         nextButton.triggered.connect(this, "nextViewedAction()");       
2792         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2793         
2794         upButton = toolBar.addAction("Up");
2795         QIcon upIcon = new QIcon(iconPath+"up.png");
2796         upButton.setIcon(upIcon);
2797         upButton.triggered.connect(this, "upAction()");         
2798         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2799
2800         
2801         downButton = toolBar.addAction("Down");
2802         QIcon downIcon = new QIcon(iconPath+"down.png");
2803         downButton.setIcon(downIcon);
2804         downButton.triggered.connect(this, "downAction()");
2805         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2806         
2807         synchronizeButton = toolBar.addAction("Synchronize");
2808         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2809         synchronizeIconAngle = 0;
2810         synchronizeButton.triggered.connect(this, "evernoteSync()");
2811         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2812         
2813         printButton = toolBar.addAction("Print");
2814         QIcon printIcon = new QIcon(iconPath+"print.png");
2815         printButton.setIcon(printIcon);
2816         printButton.triggered.connect(this, "printNote()");
2817         togglePrintButton(Global.isToolbarButtonVisible("print"));
2818
2819         tagButton = toolBar.addAction("Tag"); 
2820         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2821         tagButton.setIcon(tagIcon);
2822         tagButton.triggered.connect(browserWindow, "modifyTags()");
2823         toggleTagButton(Global.isToolbarButtonVisible("tag"));
2824
2825         attributeButton = toolBar.addAction("Attributes"); 
2826         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2827         attributeButton.setIcon(attributeIcon);
2828         attributeButton.triggered.connect(this, "toggleNoteInformation()");
2829         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2830                 
2831         emailButton = toolBar.addAction("Email");
2832         QIcon emailIcon = new QIcon(iconPath+"email.png");
2833         emailButton.setIcon(emailIcon);
2834         emailButton.triggered.connect(this, "emailNote()");
2835         toggleEmailButton(Global.isToolbarButtonVisible("email"));
2836
2837         deleteButton = toolBar.addAction("Delete");     
2838         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2839         deleteButton.setIcon(deleteIcon);
2840         deleteButton.triggered.connect(this, "deleteNote()");
2841         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2842
2843         newButton = toolBar.addAction("New");
2844         QIcon newIcon = new QIcon(iconPath+"new.png");
2845         newButton.triggered.connect(this, "addNote()");
2846         newButton.setIcon(newIcon);
2847         toggleNewButton(Global.isToolbarButtonVisible("new"));
2848         
2849         allNotesButton = toolBar.addAction("All Notes");
2850         QIcon allIcon = new QIcon(iconPath+"books.png");
2851         allNotesButton.triggered.connect(this, "allNotes()");
2852         allNotesButton.setIcon(allIcon);
2853         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2854         
2855         //toolBar.addSeparator();
2856         //toolBar.addWidget(new QLabel(tr("Quota:")));
2857         //toolBar.addWidget(quotaBar);
2858         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2859         updateQuotaBar();
2860         //toolBar.addSeparator();
2861         
2862         //toolBar.addWidget(new QLabel(tr("Zoom")));
2863         //toolBar.addWidget(zoomSpinner);
2864         
2865         //toolBar.addWidget(new QLabel("                    "));
2866         //toolBar.addSeparator();
2867         //toolBar.addWidget(new QLabel(tr("  Search:")));
2868         //toolBar.addWidget(searchField);
2869         QSizePolicy sizePolicy = new QSizePolicy();
2870         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2871         QLabel spacer = new QLabel("");
2872         spacer.setSizePolicy(sizePolicy);
2873         toolBar.addWidget(spacer);
2874         //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2875
2876         //searchClearButton = toolBar.addAction("Search Clear");
2877         //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2878         //searchClearButton.setIcon(searchClearIcon);
2879         //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2880         //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2881
2882         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2883     }
2884     // Update the sychronize button picture
2885     @Override
2886         public QMenu createPopupMenu() {
2887         QMenu contextMenu = super.createPopupMenu();
2888         
2889         contextMenu.addSeparator();
2890         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2891         contextMenu.addAction(prevAction);
2892         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2893
2894         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2895         contextMenu.addAction(nextAction);
2896         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2897
2898         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2899         contextMenu.addAction(upAction);
2900         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2901
2902         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2903         contextMenu.addAction(downAction);
2904         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2905
2906         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2907         contextMenu.addAction(synchronizeAction);
2908         synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2909
2910         QAction printAction = addContextAction("print", tr("Print"));
2911         contextMenu.addAction(printAction);
2912         printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2913
2914         QAction tagAction = addContextAction("tag", tr("Tag"));
2915         contextMenu.addAction(tagAction);
2916         tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2917         
2918         QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2919         contextMenu.addAction(attributeAction);
2920         attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2921         
2922         QAction emailAction = addContextAction("email", tr("Email"));
2923         contextMenu.addAction(emailAction);
2924         emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2925
2926         QAction deleteAction = addContextAction("delete", tr("Delete"));
2927         contextMenu.addAction(deleteAction);
2928         deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2929
2930         QAction newAction = addContextAction("new", tr("Add"));
2931         contextMenu.addAction(newAction);
2932         newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2933
2934         QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2935         contextMenu.addAction(allNotesAction);
2936         allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2937         
2938         QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2939         contextMenu.addAction(searchClearAction);
2940         searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2941         
2942         return contextMenu;
2943         
2944     }
2945     private QAction addContextAction(String config, String name) {
2946         QAction newAction = new QAction(this);
2947                 newAction.setText(name);
2948                 newAction.setCheckable(true);
2949                 newAction.setChecked(Global.isToolbarButtonVisible(config));
2950                 return newAction;
2951     }
2952     private void togglePrevArrowButton(Boolean toggle) {
2953                 prevButton.setVisible(toggle);
2954                 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2955     }
2956     private void toggleNextArrowButton(Boolean toggle) {
2957                 nextButton.setVisible(toggle);
2958                 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2959     }
2960     private void toggleUpArrowButton(Boolean toggle) {
2961                 upButton.setVisible(toggle);
2962                 Global.saveToolbarButtonsVisible("upArrow", toggle);
2963     }
2964     private void toggleDownArrowButton(Boolean toggle) {
2965                 downButton.setVisible(toggle);
2966                 Global.saveToolbarButtonsVisible("downArrow", toggle);
2967     }
2968     private void toggleSynchronizeButton(Boolean toggle) {
2969                 synchronizeButton.setVisible(toggle);
2970                 Global.saveToolbarButtonsVisible("synchronize", toggle);
2971     }
2972     private void togglePrintButton(Boolean toggle) {
2973                 printButton.setVisible(toggle);
2974                 Global.saveToolbarButtonsVisible("print", toggle);
2975     }
2976     private void toggleTagButton(Boolean toggle) {
2977                 tagButton.setVisible(toggle);
2978                 Global.saveToolbarButtonsVisible("tag", toggle);
2979     }
2980     private void toggleAttributeButton(Boolean toggle) {
2981                 attributeButton.setVisible(toggle);
2982                 Global.saveToolbarButtonsVisible("attribute", toggle);
2983     }
2984     private void toggleEmailButton(Boolean toggle) {
2985                 emailButton.setVisible(toggle);
2986                 Global.saveToolbarButtonsVisible("email", toggle);
2987     }
2988     private void toggleDeleteButton(Boolean toggle) {
2989                 deleteButton.setVisible(toggle);
2990                 Global.saveToolbarButtonsVisible("delete", toggle);
2991     }
2992     private void toggleNewButton(Boolean toggle) {
2993                 newButton.setVisible(toggle);
2994                 Global.saveToolbarButtonsVisible("new", toggle);
2995     }
2996     private void toggleAllNotesButton(Boolean toggle) {
2997                 allNotesButton.setVisible(toggle);
2998                 Global.saveToolbarButtonsVisible("allNotes", toggle);
2999     }
3000     @SuppressWarnings("unused")
3001         private void toggleSearchClearButton(Boolean toggle) {
3002                 searchClearButton.setVisible(toggle);
3003                 Global.saveToolbarButtonsVisible("searchClear", toggle);
3004     }
3005
3006
3007
3008
3009
3010     @SuppressWarnings("unused")
3011         private void updateSyncButton() {
3012                 
3013         if (syncIcons == null) {
3014                 syncIcons = new ArrayList<QPixmap>();
3015                 double angle = 0.0;
3016                 synchronizeIconAngle = 0;
3017                 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3018                 syncIcons.add(pix);
3019                 for (int i=0; i<=360; i++) {
3020                         QPixmap rotatedPix = new QPixmap(pix.size());
3021                         QPainter p = new QPainter(rotatedPix);
3022                 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3023                 QSize size = pix.size();
3024                 p.translate(size.width()/2, size.height()/2);
3025                 angle = angle+1.0;
3026                 p.rotate(angle);
3027                 p.setBackgroundMode(BGMode.OpaqueMode);
3028                 p.translate(-size.width()/2, -size.height()/2);
3029                 p.drawPixmap(0,0, pix);
3030                 p.end();
3031                 syncIcons.add(rotatedPix);
3032                 }
3033         }
3034
3035         synchronizeIconAngle++;
3036         if (synchronizeIconAngle > 359)
3037                 synchronizeIconAngle=0;
3038         synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3039         
3040     }
3041     // Synchronize with Evernote
3042         @SuppressWarnings("unused")
3043         private void evernoteSync() {
3044         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3045         if (!Global.isConnected)
3046                 remoteConnect();
3047         if (Global.isConnected)
3048                 synchronizeAnimationTimer.start(5);
3049 //                      synchronizeAnimationTimer.start(200);
3050         syncTimer();
3051         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3052     }
3053     private void updateQuotaBar() {
3054         long limit = Global.getUploadLimit();
3055         long amount = Global.getUploadAmount();
3056         if (amount>0 && limit>0) {
3057                 int percent =(int)(amount*100/limit);
3058                 quotaBar.setValue(percent);
3059         } else 
3060                 quotaBar.setValue(0);
3061     }
3062         // Zoom changed
3063     @SuppressWarnings("unused")
3064       &n