OSDN Git Service

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