OSDN Git Service

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