OSDN Git Service

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