OSDN Git Service

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