OSDN Git Service

Correct issues with importing notes that contain resources.
[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() != null && browserWindow != null 
984                                         && !currentNote.getTitle().equals(browserWindow.getTitle()))
985                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
986                 }
987                 saveNote();
988                 setMessage(tr("Beginning shutdown."));
989                 
990                 // Close down external windows
991                 Collection<ExternalBrowse> windows = externalWindows.values();
992                 Iterator<ExternalBrowse> iterator = windows.iterator();
993                 while (iterator.hasNext()) {
994                         ExternalBrowse browser = iterator.next();
995                         browser.windowClosing.disconnect();
996                         browser.close();
997                 }
998                 
999                 
1000                 externalFileEditedSaver();
1001                 if (Global.isConnected && Global.synchronizeOnClose()) {
1002                         setMessage(tr("Performing synchronization before closing."));
1003                         syncRunner.syncNeeded = true;
1004                         syncRunner.addWork("SYNC");
1005                 } else {
1006                         syncRunner.keepRunning = false;
1007                 }
1008                 syncRunner.addWork("STOP");
1009                 setMessage("Closing Program.");
1010                 threadMonitorTimer.stop();
1011
1012                 thumbnailRunner.addWork("STOP");
1013                 indexRunner.addWork("STOP");
1014                 saveNote();
1015                 listManager.stop();
1016                 saveWindowState();
1017
1018                 if (tempFiles != null)
1019                         tempFiles.clear();
1020
1021                 browserWindow.noteSignal.tagsChanged.disconnect();
1022                 browserWindow.noteSignal.titleChanged.disconnect();
1023                 browserWindow.noteSignal.noteChanged.disconnect();
1024                 browserWindow.noteSignal.notebookChanged.disconnect();
1025                 browserWindow.noteSignal.createdDateChanged.disconnect();
1026                 browserWindow.noteSignal.alteredDateChanged.disconnect();
1027                 syncRunner.searchSignal.listChanged.disconnect();
1028                 syncRunner.tagSignal.listChanged.disconnect();
1029         syncRunner.notebookSignal.listChanged.disconnect();
1030         syncRunner.noteIndexSignal.listChanged.disconnect();
1031
1032                 if (isVisible())
1033                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
1034                 saveNoteColumnPositions();
1035                 saveNoteIndexWidth();
1036                 
1037                 int width = notebookTree.columnWidth(0);
1038                 Global.setColumnWidth("notebookTreeName", width);
1039                 width = tagTree.columnWidth(0);
1040                 Global.setColumnWidth("tagTreeName", width);
1041                 
1042                 Global.saveWindowMaximized(isMaximized());
1043                 Global.saveCurrentNoteGuid(currentNoteGuid);
1044                         
1045                 int sortCol = noteTableView.proxyModel.sortColumn();
1046                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1047                 Global.setSortColumn(sortCol);
1048                 Global.setSortOrder(sortOrder);
1049                 
1050                 hide();
1051                 trayIcon.hide();
1052                 Global.keepRunning = false;
1053                 try {
1054                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1055                         if (indexRunner.thread().isAlive())
1056                                 indexRunner.thread().join(50);
1057                         if (!indexRunner.thread().isAlive())
1058                                 logger.log(logger.MEDIUM, "Index thread has stopped");
1059                         else {
1060                                 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1061                                 indexRunner.thread().interrupt();
1062                         }
1063                 } catch (InterruptedException e1) {
1064                         e1.printStackTrace();
1065                 }
1066                 
1067                 if (!syncRunner.thread().isAlive()) {
1068                         logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1069                         if (syncRunner.thread().isAlive()) {
1070                                 System.out.println(tr("Synchronizing.  Please be patient."));
1071                                 for(;syncRunner.thread().isAlive();) {
1072                                         try {
1073                                                 wait(10);
1074                                         } catch (InterruptedException e) {
1075                                                 e.printStackTrace();
1076                                         }
1077                                 }
1078                         }
1079                         logger.log(logger.MEDIUM, "Sync thread has stopped");
1080                 }
1081
1082                 if (encryptOnShutdown) {
1083                         encryptOnShutdown();
1084                 }
1085                 if (decryptOnShutdown) {
1086                         decryptOnShutdown();
1087                 }
1088                 try {
1089                         Global.getFileManager().purgeResDirectory(false);
1090                 } catch (InitializationException e) {
1091                         System.out.println(tr("Empty res directory purge failed"));
1092                         e.printStackTrace();
1093                 }
1094                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1095         }
1096
1097         @SuppressWarnings("unused")
1098         private void closeNeverNote() {
1099                 closeAction = true;
1100                 close();
1101         }
1102         public void setMessage(String s) {
1103                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1104                 
1105                 statusBar.show();
1106                 logger.log(logger.HIGH, "Message: " +s);
1107                 statusBar.showMessage(s);
1108                 emitLog.add(s);
1109                 
1110
1111                 messageTimer.stop();
1112                 messageTimer.setSingleShot(true);
1113                 messageTimer.start();
1114                 
1115                 
1116                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1117         }
1118         
1119         private void clearMessage() {
1120                 statusBar.clearMessage();
1121                 statusBar.hide();
1122         }
1123                 
1124         private void waitCursor(boolean wait) {
1125                 if (wait) {
1126                         if (QApplication.overrideCursor() == null)
1127                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1128                 }
1129                 else {
1130                         while (QApplication.overrideCursor() != null)
1131                                 QApplication.restoreOverrideCursor();
1132                 }
1133                 listManager.refreshCounters();
1134         }
1135         
1136         private void setupIndexListeners() {
1137 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1138 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1139                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1140                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1141         }
1142         private void setupSyncSignalListeners() {
1143                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1144         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1145         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1146         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1147         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1148         
1149                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1150                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1151                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1152                 
1153                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1154                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1155                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1156                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1157                 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1158                 
1159                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1160         }
1161         
1162         private void setupBrowserSignalListeners() {
1163                 setupBrowserWindowListeners(browserWindow, true);
1164         }
1165
1166         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1167                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1168                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1169             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1170             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1171             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1172             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1173             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1174             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1175             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1176             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1177             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1178             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1179             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1180             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1181         browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1182         browser.unblockApplication.connect(this, "unblockApplication()");
1183             if (master) browser.focusLost.connect(this, "saveNote()");
1184             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1185             browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1186         }
1187
1188         //**************************************************
1189         //* Setup shortcuts
1190         //**************************************************
1191         private void setupShortcut(QShortcut action, String text) {
1192                 if (!Global.shortcutKeys.containsAction(text))
1193                         return;
1194                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1195         }
1196         
1197         //***************************************************************
1198         //***************************************************************
1199         //* Settings and look & feel
1200         //***************************************************************
1201         //***************************************************************
1202         @SuppressWarnings("unused")
1203         private void settings() {
1204                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1205                 saveNoteColumnPositions();
1206                 saveNoteIndexWidth();
1207                 showColumns();
1208         ConfigDialog settings = new ConfigDialog(this);
1209         String dateFormat = Global.getDateFormat();
1210         String timeFormat = Global.getTimeFormat();
1211         
1212                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1213                 indexTimer.start(indexTime);  // reset indexing timer
1214         
1215         settings.exec();
1216         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1217         indexRunner.indexNoteBody = Global.indexNoteBody();
1218         indexRunner.indexNoteTitle = Global.indexNoteTitle();
1219         indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1220         indexRunner.indexImageRecognition = Global.indexImageRecognition();
1221         if (Global.showTrayIcon())
1222                 trayIcon.show();
1223         else
1224                 trayIcon.hide();
1225         showColumns();
1226         if (menuBar.showEditorBar.isChecked())
1227                 showEditorButtons(browserWindow);
1228         
1229         // Reset the save timer
1230         if (Global.getAutoSaveInterval() > 0)
1231                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1232         else
1233                 saveTimer.stop();
1234         
1235         
1236         // Set special reloads
1237         if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1238                 conn.executeSql("Delete from LinkedNotebook");
1239                 conn.executeSql("delete from SharedNotebook");
1240                 conn.executeSql("Delete from Notebook where linked=true");
1241                 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1242                 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1243         }
1244
1245         // Reload user data
1246         noteCache.clear();
1247         readOnlyCache.clear();
1248         inkNoteCache.clear();
1249         noteIndexUpdated(true);
1250                 
1251         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1252         }
1253         // Restore things to the way they were
1254         private void restoreWindowState(boolean mainWindow) {
1255                 // We need to name things or this doesn't work.
1256                 setObjectName("NeverNote");
1257         restoreState(Global.restoreState(objectName()));
1258                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1259                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1260                 leftSplitter1.setObjectName("leftSplitter1");   
1261                 
1262                 // Restore the actual positions.
1263                 if (mainWindow)
1264                         restoreGeometry(Global.restoreGeometry(objectName()));
1265         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1266         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1267         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1268        
1269         }
1270         // Save window positions for the next start
1271         private void saveWindowState() {
1272                 Global.saveGeometry(objectName(), saveGeometry());
1273                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1274                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1275                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1276                 Global.saveState(objectName(), saveState());
1277         }    
1278         // Load the style sheet
1279         private void loadStyleSheet() {
1280                 String styleSheetName = "default.qss";
1281                 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1282                                 styleSheetName = "default-cleanlooks.qss";
1283                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1284                 QFile file = new QFile(fileName);
1285                 
1286                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1287                 if (!file.exists()) {
1288                         fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1289                         file = new QFile(fileName);
1290                 }
1291                 file.open(OpenModeFlag.ReadOnly);
1292                 String styleSheet = file.readAll().toString();
1293                 file.close();
1294                 setStyleSheet(styleSheet);
1295         }
1296         // Save column positions for the next time
1297         private void saveNoteColumnPositions() {
1298                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1299                 Global.setColumnPosition("noteTableCreationPosition", position);
1300                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1301                 Global.setColumnPosition("noteTableTagPosition", position);
1302                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1303                 Global.setColumnPosition("noteTableNotebookPosition", position);
1304                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1305                 Global.setColumnPosition("noteTableChangedPosition", position);
1306                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1307                 Global.setColumnPosition("noteTableAuthorPosition", position);
1308                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1309                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1310                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1311                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1312                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1313                 Global.setColumnPosition("noteTableTitlePosition", position);
1314                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1315                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1316                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1317                 Global.setColumnPosition("noteTableGuidPosition", position);
1318                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1319                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1320                 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1321                 Global.setColumnPosition("noteTablePinnedPosition", position);
1322
1323         }
1324         // Save column widths for the next time
1325         private void saveNoteIndexWidth() {
1326                 int width;
1327         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1328         Global.setColumnWidth("noteTableCreationPosition", width);
1329                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1330                 Global.setColumnWidth("noteTableChangedPosition", width);
1331                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1332                 Global.setColumnWidth("noteTableGuidPosition", width);
1333                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1334                 Global.setColumnWidth("noteTableNotebookPosition", width);
1335                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1336                 Global.setColumnWidth("noteTableTagPosition", width);
1337                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1338                 Global.setColumnWidth("noteTableTitlePosition", width);
1339                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1340                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1341                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1342                 Global.setColumnWidth("noteTableAuthorPosition", width);
1343                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1344                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1345                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1346                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1347                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1348                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1349                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1350                 Global.setColumnWidth("noteTableGuidPosition", width);
1351                 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1352                 Global.setColumnWidth("noteTablePinnedPosition", width);
1353         }
1354         
1355         @SuppressWarnings("unused")
1356         private void toggleSearchWindow() {
1357                 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1358         searchLayout.toggleSearchField();
1359         menuBar.hideSearch.setChecked(searchField.isVisible());
1360         Global.saveWindowVisible("searchField", searchField.isVisible());
1361         logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1362     }   
1363         @SuppressWarnings("unused")
1364         private void toggleQuotaWindow() {
1365                 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1366         searchLayout.toggleQuotaBar();
1367         menuBar.hideQuota.setChecked(quotaBar.isVisible());
1368         Global.saveWindowVisible("quota", quotaBar.isVisible());
1369         logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1370     }   
1371         @SuppressWarnings("unused")
1372         private void toggleZoomWindow() {
1373                 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1374         searchLayout.toggleZoom();
1375         menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1376         Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1377         logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1378     }   
1379         
1380         
1381         
1382     //***************************************************************
1383     //***************************************************************
1384     //** These functions deal with Notebook menu items
1385     //***************************************************************
1386     //***************************************************************
1387     // Setup the tree containing the user's notebooks.
1388     private void initializeNotebookTree() {       
1389         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1390 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1391         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1392         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1393         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1394     }   
1395     // Listener when a notebook is selected
1396         private void notebookTreeSelection() {
1397                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1398                 noteTableView.proxyModel.blocked = true;
1399                 
1400                 clearTrashFilter();
1401                 clearAttributeFilter();
1402                 clearSavedSearchFilter();
1403                 if (Global.mimicEvernoteInterface) {
1404                         clearTagFilter();
1405                         searchField.clear();
1406                 }
1407                 menuBar.noteRestoreAction.setVisible(false);            
1408         menuBar.notebookEditAction.setEnabled(true);
1409         menuBar.notebookDeleteAction.setEnabled(true);
1410         menuBar.notebookPublishAction.setEnabled(true);
1411         menuBar.notebookShareAction.setEnabled(true);
1412         menuBar.notebookIconAction.setEnabled(true);
1413         menuBar.notebookStackAction.setEnabled(true);
1414         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1415         selectedNotebookGUIDs.clear();
1416                 String guid = "";
1417                 String stackName = "";
1418                 if (selections.size() > 0) {
1419                 guid = (selections.get(0).text(2));
1420                 stackName = selections.get(0).text(0);
1421         }
1422                 if (!Global.mimicEvernoteInterface) {
1423                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1424                         if (selections.size()==0) {
1425                                 selectedNotebookGUIDs.clear();
1426                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1427                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1428                                 }
1429                                 menuBar.notebookEditAction.setEnabled(false);
1430                                 menuBar.notebookDeleteAction.setEnabled(false);
1431                                 menuBar.notebookStackAction.setEnabled(false);
1432                                 menuBar.notebookIconAction.setEnabled(false);
1433                         }
1434                 }
1435         if (!guid.equals("") && !guid.equals("STACK")) {
1436                 selectedNotebookGUIDs.add(guid);
1437                 menuBar.notebookIconAction.setEnabled(true);
1438         } else {
1439                 menuBar.notebookIconAction.setEnabled(true);
1440                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1441                                 Notebook book = listManager.getNotebookIndex().get(j);
1442                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1443                                         selectedNotebookGUIDs.add(book.getGuid());
1444                         }
1445         }
1446         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1447         listManager.loadNotesIndex();
1448         noteIndexUpdated(false);
1449         refreshEvernoteNote(true);
1450         listManager.refreshCounters = true;
1451         listManager.refreshCounters();
1452         if (selectedNotebookGUIDs.size() == 1) {
1453                 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1454                 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1455                 if (col != -1) {
1456                         noteTableView.proxyModel.blocked = true;
1457                         if (order == 1)
1458                                 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1459                         else
1460                                 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1461                 }
1462         }
1463         noteTableView.proxyModel.blocked = false;
1464                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1465
1466     }
1467     private void clearNotebookFilter() {
1468         notebookTree.blockSignals(true);
1469         notebookTree.clearSelection();
1470                 menuBar.noteRestoreAction.setVisible(false);
1471         menuBar.notebookEditAction.setEnabled(false);
1472         menuBar.notebookDeleteAction.setEnabled(false);
1473         selectedNotebookGUIDs.clear();
1474         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1475         notebookTree.blockSignals(false);
1476     }
1477         // Triggered when the notebook DB has been updated
1478         private void notebookIndexUpdated() {
1479                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1480         
1481                 // Get the possible icons
1482                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1483         notebookTree.setIcons(icons);
1484         
1485         if (selectedNotebookGUIDs == null)
1486                         selectedNotebookGUIDs = new ArrayList<String>();
1487                 List<Notebook> books = conn.getNotebookTable().getAll();
1488                 for (int i=books.size()-1; i>=0; i--) {
1489                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1490                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1491                                         books.remove(i);
1492                                         j=listManager.getArchiveNotebookIndex().size();
1493                                 }
1494                         }
1495                 }
1496                 
1497                 
1498                 listManager.countNotebookResults(listManager.getNoteIndex());
1499                 notebookTree.blockSignals(true);
1500         notebookTree.load(books, listManager.getLocalNotebooks());
1501         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1502                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1503                 if (!found)
1504                         selectedNotebookGUIDs.remove(i);
1505         }
1506         listManager.refreshCounters = true;
1507         listManager.refreshCounters();
1508         notebookTree.blockSignals(false);
1509         
1510                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1511     }
1512     // Show/Hide note information
1513         @SuppressWarnings("unused")
1514         private void toggleNotebookWindow() {
1515                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1516                 searchLayout.toggleNotebook();
1517         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1518         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1519         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1520     }   
1521         // Add a new notebook
1522         @SuppressWarnings("unused")
1523         private void addNotebook() {
1524                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1525                 NotebookEdit edit = new NotebookEdit();
1526                 edit.setNotebooks(listManager.getNotebookIndex());
1527                 edit.exec();
1528         
1529                 if (!edit.okPressed())
1530                         return;
1531         
1532                 Calendar currentTime = new GregorianCalendar();
1533                 Long l = new Long(currentTime.getTimeInMillis());
1534                 String randint = new String(Long.toString(l));
1535         
1536                 Notebook newBook = new Notebook();
1537                 newBook.setUpdateSequenceNum(0);
1538                 newBook.setGuid(randint);
1539                 newBook.setName(edit.getNotebook());
1540                 newBook.setServiceCreated(new Date().getTime());
1541                 newBook.setServiceUpdated(new Date().getTime());
1542                 newBook.setDefaultNotebook(false);
1543                 newBook.setPublished(false);
1544                 
1545                 listManager.getNotebookIndex().add(newBook);
1546                 if (edit.isLocal())
1547                         listManager.getLocalNotebooks().add(newBook.getGuid());
1548                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1549                 notebookIndexUpdated();
1550                 listManager.countNotebookResults(listManager.getNoteIndex());
1551 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1552                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1553         }
1554         // Edit an existing notebook
1555         @SuppressWarnings("unused")
1556         private void stackNotebook() {
1557                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1558                 StackNotebook edit = new StackNotebook();
1559                 
1560                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1561                 QTreeWidgetItem currentSelection;
1562                 for (int i=0; i<selections.size(); i++) {
1563                         currentSelection = selections.get(0);
1564                         String guid = currentSelection.text(2);
1565                         if (guid.equalsIgnoreCase("")) {
1566                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1567                                  return;
1568                         }
1569                         if (guid.equalsIgnoreCase("STACK")) {
1570                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1571                                  return;
1572                         }
1573                 }
1574
1575                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1576
1577                 
1578                 edit.exec();
1579         
1580                 if (!edit.okPressed())
1581                         return;
1582         
1583                 String stack = edit.getStackName();
1584                 
1585                 for (int i=0; i<selections.size(); i++) {
1586                         currentSelection = selections.get(i);
1587                         String guid = currentSelection.text(2);
1588                         listManager.updateNotebookStack(guid, stack);
1589                 }
1590                 notebookIndexUpdated();
1591                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1592         }
1593         // Edit an existing notebook
1594         @SuppressWarnings("unused")
1595         private void editNotebook() {
1596                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1597                 NotebookEdit edit = new NotebookEdit();
1598                 
1599                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1600                 QTreeWidgetItem currentSelection;
1601                 currentSelection = selections.get(0);
1602                 edit.setNotebook(currentSelection.text(0));
1603                 
1604                 String guid = currentSelection.text(2);
1605                 if (!guid.equalsIgnoreCase("STACK")) {
1606                         edit.setTitle(tr("Edit Notebook"));
1607                         edit.setNotebooks(listManager.getNotebookIndex());
1608                         edit.setLocalCheckboxEnabled(false);
1609                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1610                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1611                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1612                                         i=listManager.getNotebookIndex().size();
1613                                 }
1614                         }
1615                 } else {
1616                         edit.setTitle(tr("Edit Stack"));
1617                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1618                         edit.hideLocalCheckbox();
1619                         edit.hideDefaultCheckbox();
1620                 }
1621                 
1622                 edit.exec();
1623         
1624                 if (!edit.okPressed())
1625                         return;
1626         
1627                 
1628                 if (guid.equalsIgnoreCase("STACK")) {
1629                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1630                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1631                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1632                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1633                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1634                         }
1635                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1636                         currentSelection.setText(0, edit.getNotebook());
1637                         return;
1638                 }
1639                 
1640                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1641                 currentSelection.setText(0, edit.getNotebook());
1642                 
1643                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1644                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1645                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1646                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1647                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1648                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1649                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1650                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1651                                 }
1652                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1653                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1654                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1655                                         linkedNotebook.setShareName(edit.getNotebook());
1656                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1657                                 }
1658                                 i=listManager.getNotebookIndex().size();
1659                         }
1660                 }
1661                 
1662                 // Build a list of non-closed notebooks
1663                 List<Notebook> nbooks = new ArrayList<Notebook>();
1664                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1665                         boolean found=false;
1666                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1667                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1668                                         found = true;
1669                         }
1670                         if (!found)
1671                                 nbooks.add(listManager.getNotebookIndex().get(i));
1672                 }
1673                 
1674                 
1675                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1676                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1677                 browserWindow.setNotebookList(filteredBooks);
1678                 Iterator<String> set = externalWindows.keySet().iterator();
1679                 while(set.hasNext())
1680                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1681                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1682         }
1683         // Publish a notebook
1684         @SuppressWarnings("unused")
1685         private void publishNotebook() {
1686                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1687                 QTreeWidgetItem currentSelection;
1688                 currentSelection = selections.get(0);
1689                 String guid = currentSelection.text(2);
1690
1691                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1692                         return;
1693                 
1694                 Notebook n = null;
1695                 int position = 0;
1696                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1697                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1698                                 n = listManager.getNotebookIndex().get(i);
1699                                 position = i;
1700                                 i = listManager.getNotebookIndex().size();
1701                         }
1702                 }
1703                 if (n == null)
1704                         return;
1705                 
1706                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1707                 publish.exec();
1708                 
1709                 if (!publish.okClicked()) 
1710                         return;
1711                 
1712                 Publishing p = publish.getPublishing();
1713                 boolean isPublished = !publish.isStopPressed();
1714                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1715                 n.setPublished(isPublished);
1716                 n.setPublishing(p);
1717                 listManager.getNotebookIndex().set(position, n);
1718                 notebookIndexUpdated();
1719         }
1720         // Publish a notebook
1721         @SuppressWarnings("unused")
1722         private void shareNotebook() {
1723                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1724                 QTreeWidgetItem currentSelection;
1725                 currentSelection = selections.get(0);
1726                 String guid = currentSelection.text(2);
1727
1728                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1729                         return;
1730                 
1731                 Notebook n = null;;
1732                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1733                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1734                                 n = listManager.getNotebookIndex().get(i);
1735                                 i = listManager.getNotebookIndex().size();
1736                         }
1737                 }
1738                                 
1739                 String authToken = null;
1740                 if (syncRunner.isConnected)
1741                         authToken = syncRunner.authToken;
1742                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1743                 share.exec();
1744                 
1745         }
1746
1747         // Delete an existing notebook
1748         @SuppressWarnings("unused")
1749         private void deleteNotebook() {
1750                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1751                 boolean stacksFound = false;
1752                 boolean notebooksFound = false;
1753                 boolean assigned = false;
1754                 // Check if any notes have this notebook
1755                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1756         for (int i=0; i<selections.size(); i++) {
1757                 QTreeWidgetItem currentSelection;
1758                 currentSelection = selections.get(i);
1759                 String guid = currentSelection.text(2);
1760                 if (!guid.equalsIgnoreCase("STACK")) {
1761                         notebooksFound = true;
1762                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1763                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1764                                 if (noteGuid.equals(guid)) {
1765                                         assigned = true;
1766                                         j=listManager.getNoteIndex().size();
1767                                         i=selections.size();
1768                                 }
1769                         }
1770                 } else {
1771                         stacksFound = true;
1772                 }
1773         }
1774                 if (assigned) {
1775                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1776                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1777                         return;
1778                 }
1779                 
1780                 if (conn.getNotebookTable().getAll().size() == 1) {
1781                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1782                         return;
1783                 }
1784         
1785         // If all notebooks are clear, verify the delete
1786                 String msg1 = new String(tr("Delete selected notebooks?"));
1787                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1788                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1789                                 " not deleted unless selected?"));
1790                 String msg = "";
1791                 if (stacksFound && notebooksFound)
1792                         msg = msg3;
1793                 if (!stacksFound && notebooksFound)
1794                         msg = msg1;
1795                 if (stacksFound && !notebooksFound)
1796                         msg = msg2;
1797                 if (QMessageBox.question(this, tr("Confirmation"), msg,
1798                         QMessageBox.StandardButton.Yes, 
1799                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1800                         return;
1801                 }
1802                 
1803                 // If confirmed, delete the notebook
1804         for (int i=selections.size()-1; i>=0; i--) {
1805                 QTreeWidgetItem currentSelection;
1806                 currentSelection = selections.get(i);
1807                 String guid = currentSelection.text(2);
1808                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1809                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1810                         listManager.renameStack(currentSelection.text(0), "");
1811                 } else {
1812                         conn.getNotebookTable().expungeNotebook(guid, true);
1813                         listManager.deleteNotebook(guid);
1814                 }
1815         }
1816
1817                 notebookIndexUpdated();
1818 //        notebookTreeSelection();
1819 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1820 //        listManager.countNotebookResults(listManager.getNoteIndex());
1821         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1822         }
1823         // A note's notebook has been updated
1824         @SuppressWarnings("unused")
1825         private void updateNoteNotebook(String guid, String notebookGuid) {
1826                 
1827                 // Update the list manager
1828                 listManager.updateNoteNotebook(guid, notebookGuid);
1829                 listManager.countNotebookResults(listManager.getNoteIndex());
1830 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1831                 
1832                 // Find the name of the notebook
1833                 String notebookName = null;
1834                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1835                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1836                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1837                                 break;
1838                         }
1839                 }
1840                 
1841                 // If we found the name, update the browser window
1842                 if (notebookName != null) {
1843                         updateListNoteNotebook(guid, notebookName);
1844                         if (guid.equals(currentNoteGuid)) {
1845                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1846                                 if (pos >=0)
1847                                         browserWindow.notebookBox.setCurrentIndex(pos);
1848                         }
1849                 }
1850                 
1851                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1852                 if (guid.equals(currentNoteGuid)) {
1853                         if (currentNote != null) {
1854                                 currentNote.setNotebookGuid(notebookGuid);
1855                         }
1856                 }
1857         }
1858         // Open/close notebooks
1859         @SuppressWarnings("unused")
1860         private void closeNotebooks() {
1861                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1862                 na.exec();
1863                 if (!na.okClicked())
1864                         return;
1865                 
1866                 waitCursor(true);
1867                 listManager.getArchiveNotebookIndex().clear();
1868                 
1869                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1870                         String text = na.getClosedBookList().takeItem(i).text();
1871                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1872                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1873                                         Notebook n = listManager.getNotebookIndex().get(j);
1874                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1875                                         listManager.getArchiveNotebookIndex().add(n);
1876                                         j=listManager.getNotebookIndex().size();
1877                                 }
1878                         }
1879                 }
1880                 
1881                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1882                         String text = na.getOpenBookList().takeItem(i).text();
1883                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1884                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1885                                         Notebook n = listManager.getNotebookIndex().get(j);
1886                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1887                                         j=listManager.getNotebookIndex().size();
1888                                 }
1889                         }
1890                 }
1891                 notebookTreeSelection();
1892                 listManager.loadNotesIndex();
1893                 notebookIndexUpdated();
1894                 noteIndexUpdated(false);
1895                 reloadTagTree(true);
1896 //              noteIndexUpdated(false);
1897                 
1898                 // Build a list of non-closed notebooks
1899                 List<Notebook> nbooks = new ArrayList<Notebook>();
1900                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1901                         boolean found=false;
1902                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1903                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1904                                         found = true;
1905                         }
1906                         if (!found)
1907                                 nbooks.add(listManager.getNotebookIndex().get(i));
1908                 }
1909                 
1910                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1911                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1912                 browserWindow.setNotebookList(filteredBooks);
1913                 
1914                 // Update any external windows
1915                 Iterator<String> set = externalWindows.keySet().iterator();
1916                 while(set.hasNext())
1917                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1918                 
1919                 waitCursor(false);
1920         }
1921         // Change the notebook's icon
1922         @SuppressWarnings("unused")
1923         private void setNotebookIcon() {
1924                 boolean stackSelected = false;
1925                 boolean allNotebookSelected = false;
1926                 
1927                 QTreeWidgetItem currentSelection;
1928                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1929                 if (selections.size() == 0)
1930                         return;
1931                 
1932                 currentSelection = selections.get(0);   
1933                 String guid = currentSelection.text(2);
1934                 if (guid.equalsIgnoreCase(""))
1935                         allNotebookSelected = true;
1936                 if (guid.equalsIgnoreCase("STACK"))
1937                         stackSelected = true;
1938
1939                 QIcon currentIcon = currentSelection.icon(0);
1940                 QIcon icon;
1941                 SetIcon dialog;
1942                 
1943                 if (!stackSelected && !allNotebookSelected) {
1944                         icon = conn.getNotebookTable().getIcon(guid);
1945                         if (icon == null) {
1946                                 dialog = new SetIcon(currentIcon, saveLastPath);
1947                                 dialog.setUseDefaultIcon(true);
1948                         } else {
1949                                 dialog = new SetIcon(icon, saveLastPath);
1950                                 dialog.setUseDefaultIcon(false);
1951                         }
1952                 } else {
1953                         if (stackSelected) {
1954                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1955                         } else {
1956                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
1957                         }
1958                         if (icon == null) {
1959                                 dialog = new SetIcon(currentIcon, saveLastPath);
1960                                 dialog.setUseDefaultIcon(true);
1961                         } else {
1962                                 dialog = new SetIcon(icon, saveLastPath);
1963                                 dialog.setUseDefaultIcon(false);
1964                         }
1965                 }
1966                 dialog.exec();
1967                 if (dialog.okPressed()) {
1968                 saveLastPath = dialog.getPath();
1969
1970                         QIcon newIcon = dialog.getIcon();
1971                         if (stackSelected) {
1972                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1973                                 if (newIcon == null) {
1974                                         newIcon = new QIcon(iconPath+"books2.png");
1975                                 }
1976                                 currentSelection.setIcon(0,newIcon);
1977                                 return;
1978                         }
1979                         if (allNotebookSelected) {
1980                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1981                                 if (newIcon == null) {
1982                                         newIcon = new QIcon(iconPath+"notebook-green.png");
1983                                 }
1984                                 currentSelection.setIcon(0,newIcon);
1985                                 return;
1986                         }
1987                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1988                         if (newIcon == null) {
1989                                 boolean isPublished = false;;
1990                                 boolean found = false;
1991                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1992                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1993                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1994                                                 found = true;
1995                                         }
1996                                 }
1997                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1998                         }
1999                         currentSelection.setIcon(0, newIcon);
2000                 }
2001         
2002         }
2003         
2004         
2005     //***************************************************************
2006     //***************************************************************
2007     //** These functions deal with Tag menu items
2008     //***************************************************************
2009     //***************************************************************
2010         // Add a new notebook
2011         @SuppressWarnings("unused")
2012         private void addTag() {
2013                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2014                 TagEdit edit = new TagEdit();
2015                 edit.setTagList(listManager.getTagIndex());
2016
2017                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2018                 QTreeWidgetItem currentSelection = null;
2019                 if (selections.size() > 0) {
2020                         currentSelection = selections.get(0);
2021                         edit.setParentTag(currentSelection.text(0));
2022                 }
2023
2024                 edit.exec();
2025         
2026                 if (!edit.okPressed())
2027                         return;
2028         
2029                 Calendar currentTime = new GregorianCalendar();
2030                 Long l = new Long(currentTime.getTimeInMillis());
2031                 String randint = new String(Long.toString(l));
2032         
2033                 Tag newTag = new Tag();
2034                 newTag.setUpdateSequenceNum(0);
2035                 newTag.setGuid(randint);
2036                 newTag.setName(edit.getTag());
2037                 if (edit.getParentTag().isChecked()) {
2038                         newTag.setParentGuid(currentSelection.text(2));
2039                         newTag.setParentGuidIsSet(true);
2040                         currentSelection.setExpanded(true);
2041                 }
2042                 conn.getTagTable().addTag(newTag, true);
2043                 listManager.getTagIndex().add(newTag);
2044                 reloadTagTree(true);
2045                 
2046                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2047         }
2048         @SuppressWarnings("unused")
2049         private void reloadTagTree() {
2050                 reloadTagTree(false);
2051         }
2052         private void reloadTagTree(boolean reload) {
2053                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2054                 tagIndexUpdated(reload);
2055                 boolean filter = false;
2056                 if (reload)
2057                         listManager.countTagResults(listManager.getNoteIndex());
2058                 if (notebookTree.selectedItems().size() > 0 
2059                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2060                                                   filter = true;
2061                 if (tagTree.selectedItems().size() > 0)
2062                         filter = true;
2063                 tagTree.showAllTags(!filter);
2064                 tagIndexUpdated(false);
2065                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2066         }
2067         // Edit an existing tag
2068         @SuppressWarnings("unused")
2069         private void editTag() {
2070                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2071                 TagEdit edit = new TagEdit();
2072                 edit.setTitle("Edit Tag");
2073                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2074                 QTreeWidgetItem currentSelection;
2075                 currentSelection = selections.get(0);
2076                 edit.setTag(currentSelection.text(0));
2077                 edit.setTagList(listManager.getTagIndex());
2078                 edit.exec();
2079         
2080                 if (!edit.okPressed())
2081                         return;
2082         
2083                 String guid = currentSelection.text(2);
2084                 currentSelection.setText(0,edit.getTag());
2085                 
2086                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2087                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2088                                 listManager.getTagIndex().get(i).setName(edit.getTag());
2089                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2090                                 updateListTagName(guid);
2091                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2092                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2093                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2094                                 return;
2095                         }
2096                 }
2097                 browserWindow.setTag(getTagNamesForNote(currentNote));
2098                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2099         }
2100         // Delete an existing tag
2101         @SuppressWarnings("unused")
2102         private void deleteTag() {
2103                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2104                 
2105                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2106                         QMessageBox.StandardButton.Yes, 
2107                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2108                                                         return;
2109                 }
2110                 
2111                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2112         for (int i=selections.size()-1; i>=0; i--) {
2113                 QTreeWidgetItem currentSelection;
2114                 currentSelection = selections.get(i);                   
2115                 removeTagItem(currentSelection.text(2));
2116         }
2117         tagIndexUpdated(true);
2118         tagTreeSelection();
2119         listManager.countTagResults(listManager.getNoteIndex());
2120 //              tagTree.updateCounts(listManager.getTagCounter());
2121         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2122         }
2123         // Remove a tag tree item.  Go recursively down & remove the children too
2124         private void removeTagItem(String guid) {
2125         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2126                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2127                 if (parent != null && parent.equals(guid)) {            
2128                         //Remove this tag's children
2129                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2130                 }
2131         }
2132         //Now, remove this tag
2133         removeListTagName(guid);
2134         conn.getTagTable().expungeTag(guid, true);                      
2135         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2136                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2137                         listManager.getTagIndex().remove(a);
2138                         return;
2139                 }
2140         }
2141         }
2142         // Setup the tree containing the user's tags
2143     private void initializeTagTree() {
2144         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2145 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2146 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2147         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2148         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2149         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2150     }
2151     // Listener when a tag is selected
2152         private void tagTreeSelection() {
2153         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2154                 
2155         clearTrashFilter();
2156         clearAttributeFilter();
2157         clearSavedSearchFilter();
2158         
2159                 menuBar.noteRestoreAction.setVisible(false);
2160                 
2161         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2162         QTreeWidgetItem currentSelection;
2163         selectedTagGUIDs.clear();
2164         for (int i=0; i<selections.size(); i++) {
2165                 currentSelection = selections.get(i);
2166                 selectedTagGUIDs.add(currentSelection.text(2));
2167         }
2168         if (selections.size() > 0) {
2169                 menuBar.tagEditAction.setEnabled(true);
2170                 menuBar.tagDeleteAction.setEnabled(true);
2171                 menuBar.tagIconAction.setEnabled(true);
2172         }
2173         else {
2174                 menuBar.tagEditAction.setEnabled(false);
2175                 menuBar.tagDeleteAction.setEnabled(false);
2176                 menuBar.tagIconAction.setEnabled(true);
2177         }
2178         if (selections.size() > 1)
2179                 menuBar.tagMergeAction.setEnabled(true);
2180         else
2181                 menuBar.tagMergeAction.setEnabled(false);
2182         listManager.setSelectedTags(selectedTagGUIDs);
2183         listManager.loadNotesIndex();
2184         noteIndexUpdated(false);
2185         refreshEvernoteNote(true);
2186         listManager.refreshCounters = true;
2187         listManager.refreshCounters();
2188         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2189     }
2190     // trigger the tag index to be refreshed
2191     @SuppressWarnings("unused")
2192         private void tagIndexUpdated() {
2193         tagIndexUpdated(true);
2194     }
2195     private void tagIndexUpdated(boolean reload) {
2196         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2197                 if (selectedTagGUIDs == null)
2198                         selectedTagGUIDs = new ArrayList<String>();
2199                 if (reload)
2200                         listManager.reloadTagIndex();
2201
2202                 tagTree.blockSignals(true);
2203                 if (reload) {
2204                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2205                         tagTree.load(listManager.getTagIndex());
2206                 }
2207
2208         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2209                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2210                 if (!found)
2211                         selectedTagGUIDs.remove(i);
2212         }
2213         tagTree.blockSignals(false);
2214         
2215                 browserWindow.setTag(getTagNamesForNote(currentNote));
2216         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2217     }   
2218     // Show/Hide note information
2219         @SuppressWarnings("unused")
2220         private void toggleTagWindow() {
2221                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2222         if (tagTree.isVisible())
2223                 tagTree.hide();
2224         else
2225                 tagTree.show();
2226         menuBar.hideTags.setChecked(tagTree.isVisible());
2227         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2228         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2229     }   
2230         // A note's tags have been updated
2231         @SuppressWarnings("unused")
2232         private void updateNoteTags(String guid, List<String> tags) {
2233                 // Save any new tags.  We'll need them later.
2234                 List<String> newTags = new ArrayList<String>();
2235                 for (int i=0; i<tags.size(); i++) {
2236                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2237                                 newTags.add(tags.get(i));
2238                 }
2239                 
2240                 listManager.saveNoteTags(guid, tags);
2241                 listManager.countTagResults(listManager.getNoteIndex());
2242                 StringBuffer names = new StringBuffer("");
2243                 for (int i=0; i<tags.size(); i++) {
2244                         names = names.append(tags.get(i));
2245                         if (i<tags.size()-1) {
2246                                 names.append(Global.tagDelimeter + " ");
2247                         }
2248                 }
2249                 browserWindow.setTag(names.toString());
2250                 noteDirty = true;
2251                 
2252                 // Now, we need to add any new tags to the tag tree
2253                 for (int i=0; i<newTags.size(); i++) 
2254                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2255         }
2256         // Get a string containing all tag names for a note
2257         private String getTagNamesForNote(Note n) {
2258                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2259                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2260                         return "";
2261                 StringBuffer buffer = new StringBuffer(100);
2262                 Vector<String> v = new Vector<String>();
2263                 List<String> guids = n.getTagGuids();
2264                 
2265                 if (guids == null) 
2266                         return "";
2267                 
2268                 for (int i=0; i<guids.size(); i++) {
2269                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2270                 }
2271                 Comparator<String> comparator = Collections.reverseOrder();
2272                 Collections.sort(v,comparator);
2273                 Collections.reverse(v);
2274                 
2275                 for (int i = 0; i<v.size(); i++) {
2276                         if (i>0) 
2277                                 buffer.append(", ");
2278                         buffer.append(v.get(i));
2279                 }
2280                 
2281                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2282                 return buffer.toString();
2283         }       
2284         // Tags were added via dropping notes from the note list
2285         @SuppressWarnings("unused")
2286         private void tagsAdded(String noteGuid, String tagGuid) {
2287                 String tagName = null;
2288                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2289                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2290                                 tagName = listManager.getTagIndex().get(i).getName();
2291                                 i=listManager.getTagIndex().size();
2292                         }
2293                 }
2294                 if (tagName == null)
2295                         return;
2296                 
2297                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2298                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2299                                 List<String> tagNames = new ArrayList<String>();
2300                                 tagNames.add(new String(tagName));
2301                                 Note n = listManager.getMasterNoteIndex().get(i);
2302                                 for (int j=0; j<n.getTagNames().size(); j++) {
2303                                         tagNames.add(new String(n.getTagNames().get(j)));
2304                                 }
2305                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2306                                 if (n.getGuid().equals(currentNoteGuid)) {
2307                                         Collections.sort(tagNames);
2308                                         String display = "";
2309                                         for (int j=0; j<tagNames.size(); j++) {
2310                                                 display = display+tagNames.get(j);
2311                                                 if (j+2<tagNames.size()) 
2312                                                         display = display+Global.tagDelimeter+" ";
2313                                         }
2314                                         browserWindow.setTag(display);
2315                                 }
2316                                 i=listManager.getMasterNoteIndex().size();
2317                         }
2318                 }
2319                 
2320                 
2321                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2322         }
2323         private void clearTagFilter() {
2324                 tagTree.blockSignals(true);
2325                 tagTree.clearSelection();
2326                 menuBar.noteRestoreAction.setVisible(false);
2327                 menuBar.tagEditAction.setEnabled(false);
2328                 menuBar.tagMergeAction.setEnabled(false);
2329                 menuBar.tagDeleteAction.setEnabled(false);
2330                 menuBar.tagIconAction.setEnabled(false);
2331                 selectedTagGUIDs.clear();
2332         listManager.setSelectedTags(selectedTagGUIDs);
2333         tagTree.blockSignals(false);
2334         }
2335         // Change the icon for a tag
2336         @SuppressWarnings("unused")
2337         private void setTagIcon() {
2338                 QTreeWidgetItem currentSelection;
2339                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2340                 if (selections.size() == 0)
2341                         return;
2342                 
2343                 currentSelection = selections.get(0);   
2344                 String guid = currentSelection.text(2);
2345
2346                 QIcon currentIcon = currentSelection.icon(0);
2347                 QIcon icon = conn.getTagTable().getIcon(guid);
2348                 SetIcon dialog;
2349                 if (icon == null) {
2350                         dialog = new SetIcon(currentIcon, saveLastPath);
2351                         dialog.setUseDefaultIcon(true);
2352                 } else {
2353                         dialog = new SetIcon(icon, saveLastPath);
2354                         dialog.setUseDefaultIcon(false);
2355                 }
2356                 dialog.exec();
2357                 if (dialog.okPressed()) {
2358                 saveLastPath = dialog.getPath();
2359                         QIcon newIcon = dialog.getIcon();
2360                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2361                         if (newIcon == null) 
2362                                 newIcon = new QIcon(iconPath+"tag.png");
2363                         currentSelection.setIcon(0, newIcon);
2364                 }
2365         
2366         }
2367         // Merge tags
2368         @SuppressWarnings("unused")
2369         private void mergeTags() {
2370                 List<Tag> tags = new ArrayList<Tag>();
2371                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2372                 for (int i=0; i<selections.size(); i++) {
2373                         Tag record = new Tag();
2374                         record.setGuid(selections.get(i).text(2));
2375                         record.setName(selections.get(i).text(0));
2376                         tags.add(record);
2377                 }
2378
2379                 TagMerge mergeDialog = new TagMerge(tags);
2380                 mergeDialog.exec();
2381                 if (!mergeDialog.okClicked())
2382                         return;
2383                 String newGuid = mergeDialog.getNewTagGuid();
2384                 
2385                 for (int i=0; i<tags.size(); i++) {
2386                         if (!tags.get(i).getGuid().equals(newGuid)) {
2387                                 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2388                                 for (int j=0; j<noteGuids.size(); j++) {
2389                                         String noteGuid = noteGuids.get(j);
2390                                         conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2391                                         if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2392                                                 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2393                                 }
2394                         }
2395                 }
2396                 listManager.reloadIndexes();
2397         }
2398         
2399     //***************************************************************
2400     //***************************************************************
2401     //** These functions deal with Saved Search menu items
2402     //***************************************************************
2403     //***************************************************************
2404         // Add a new notebook
2405         @SuppressWarnings("unused")
2406         private void addSavedSearch() {
2407                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2408                 SavedSearchEdit edit = new SavedSearchEdit();
2409                 edit.setSearchList(listManager.getSavedSearchIndex());
2410                 edit.exec();
2411         
2412                 if (!edit.okPressed())
2413                         return;
2414         
2415                 Calendar currentTime = new GregorianCalendar();         
2416                 Long l = new Long(currentTime.getTimeInMillis());
2417                 String randint = new String(Long.toString(l));
2418         
2419                 SavedSearch search = new SavedSearch();
2420                 search.setUpdateSequenceNum(0);
2421                 search.setGuid(randint);
2422                 search.setName(edit.getName());
2423                 search.setQuery(edit.getQuery());
2424                 search.setFormat(QueryFormat.USER);
2425                 listManager.getSavedSearchIndex().add(search);
2426                 conn.getSavedSearchTable().addSavedSearch(search, true);
2427                 savedSearchIndexUpdated();
2428                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2429         }
2430         // Edit an existing tag
2431         @SuppressWarnings("unused")
2432         private void editSavedSearch() {
2433                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2434                 SavedSearchEdit edit = new SavedSearchEdit();
2435                 edit.setTitle(tr("Edit Search"));
2436                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2437                 QTreeWidgetItem currentSelection;
2438                 currentSelection = selections.get(0);
2439                 String guid = currentSelection.text(1);
2440                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2441                 edit.setName(currentSelection.text(0));
2442                 edit.setQuery(s.getQuery());
2443                 edit.setSearchList(listManager.getSavedSearchIndex());
2444                 edit.exec();
2445         
2446                 if (!edit.okPressed())
2447                         return;
2448         
2449                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2450                 SavedSearch search = null;
2451                 boolean found = false;
2452                 for (int i=0; i<list.size(); i++) {
2453                         search = list.get(i);
2454                         if (search.getGuid().equals(guid)) {
2455                                 i=list.size();
2456                                 found = true;
2457                         }
2458                 }
2459                 if (!found)
2460                         return;
2461                 search.setName(edit.getName());
2462                 search.setQuery(edit.getQuery());
2463                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2464                 savedSearchIndexUpdated();
2465                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2466         }
2467         // Delete an existing tag
2468         @SuppressWarnings("unused")
2469         private void deleteSavedSearch() {
2470                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2471                 
2472                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2473                         QMessageBox.StandardButton.Yes, 
2474                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2475                                                         return;
2476                 }
2477                 
2478                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2479         for (int i=selections.size()-1; i>=0; i--) {
2480                 QTreeWidgetItem currentSelection;
2481                 currentSelection = selections.get(i);
2482                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2483                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2484                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2485                                 listManager.getSavedSearchIndex().remove(j);
2486                                 j=listManager.getSavedSearchIndex().size()+1;
2487                         }
2488                 }
2489                 selections.remove(i);
2490         }
2491         savedSearchIndexUpdated();
2492         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2493         }
2494     // Setup the tree containing the user's tags
2495     private void initializeSavedSearchTree() {
2496         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2497         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2498         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2499     }
2500     // Listener when a tag is selected
2501     @SuppressWarnings("unused")
2502         private void savedSearchTreeSelection() {
2503         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2504
2505         clearNotebookFilter();
2506         clearTagFilter();
2507         clearTrashFilter();
2508         clearAttributeFilter();
2509         
2510         String currentGuid = selectedSavedSearchGUID;
2511         menuBar.savedSearchEditAction.setEnabled(true);
2512         menuBar.savedSearchDeleteAction.setEnabled(true);
2513         menuBar.savedSearchIconAction.setEnabled(true);
2514         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2515         QTreeWidgetItem currentSelection;
2516         selectedSavedSearchGUID = "";
2517         for (int i=0; i<selections.size(); i++) {
2518                 currentSelection = selections.get(i);
2519                 if (currentSelection.text(1).equals(currentGuid)) {
2520                         currentSelection.setSelected(false);
2521                 } else {
2522                         selectedSavedSearchGUID = currentSelection.text(1);
2523                 }
2524 //              i = selections.size() +1;
2525         }
2526         
2527         // There is the potential for no notebooks to be selected if this 
2528         // happens then we make it look like all notebooks were selecetd.
2529         // If that happens, just select the "all notebooks"
2530         if (selections.size()==0) {
2531                 clearSavedSearchFilter();
2532         }
2533         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2534         
2535         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2536     }
2537     private void clearSavedSearchFilter() {
2538         menuBar.savedSearchEditAction.setEnabled(false);
2539         menuBar.savedSearchDeleteAction.setEnabled(false);
2540         menuBar.savedSearchIconAction.setEnabled(false);
2541         savedSearchTree.blockSignals(true);
2542         savedSearchTree.clearSelection();
2543         savedSearchTree.blockSignals(false);
2544         selectedSavedSearchGUID = "";
2545         searchField.setEditText("");
2546         searchPerformed = false;
2547         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2548     }
2549     // trigger the tag index to be refreshed
2550         private void savedSearchIndexUpdated() { 
2551                 if (selectedSavedSearchGUID == null)
2552                         selectedSavedSearchGUID = new String();
2553                 savedSearchTree.blockSignals(true);
2554                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2555         savedSearchTree.load(listManager.getSavedSearchIndex());
2556         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2557         savedSearchTree.blockSignals(false);
2558     }
2559     // trigger when the saved search selection changes
2560     @SuppressWarnings("unused")
2561         private void updateSavedSearchSelection() {
2562                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2563                 
2564         menuBar.savedSearchEditAction.setEnabled(true);
2565         menuBar.savedSearchDeleteAction.setEnabled(true);
2566         menuBar.savedSearchIconAction.setEnabled(true);
2567         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2568
2569         if (selections.size() > 0) {
2570                 menuBar.savedSearchEditAction.setEnabled(true);
2571                 menuBar.savedSearchDeleteAction.setEnabled(true);
2572                 menuBar.savedSearchIconAction.setEnabled(true);
2573                 selectedSavedSearchGUID = selections.get(0).text(1);
2574                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2575                 searchField.setEditText(s.getQuery());
2576         } else { 
2577                 menuBar.savedSearchEditAction.setEnabled(false);
2578                 menuBar.savedSearchDeleteAction.setEnabled(false);
2579                 menuBar.savedSearchIconAction.setEnabled(false);
2580                 selectedSavedSearchGUID = "";
2581                 searchField.setEditText("");
2582         }
2583         searchFieldChanged();
2584         
2585                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2586
2587         
2588     }
2589     // Show/Hide note information
2590         @SuppressWarnings("unused")
2591         private void toggleSavedSearchWindow() {
2592                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2593         if (savedSearchTree.isVisible())
2594                 savedSearchTree.hide();
2595         else
2596                 savedSearchTree.show();
2597         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2598                                 
2599                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2600         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2601     }
2602         // Change the icon for a saved search
2603         @SuppressWarnings("unused")
2604         private void setSavedSearchIcon() {
2605                 QTreeWidgetItem currentSelection;
2606                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2607                 if (selections.size() == 0)
2608                         return;
2609                 
2610                 currentSelection = selections.get(0);   
2611                 String guid = currentSelection.text(1);
2612
2613                 QIcon currentIcon = currentSelection.icon(0);
2614                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2615                 SetIcon dialog;
2616                 if (icon == null) {
2617                         dialog = new SetIcon(currentIcon, saveLastPath);
2618                         dialog.setUseDefaultIcon(true);
2619                 } else {
2620                         dialog = new SetIcon(icon, saveLastPath);
2621                         dialog.setUseDefaultIcon(false);
2622                 }
2623                 dialog.exec();
2624                 if (dialog.okPressed()) {
2625                 saveLastPath = dialog.getPath();
2626                         QIcon newIcon = dialog.getIcon();
2627                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2628                         if (newIcon == null) 
2629                                 newIcon = new QIcon(iconPath+"search.png");
2630                         currentSelection.setIcon(0, newIcon);
2631                 }
2632         
2633         }
2634         
2635         
2636         
2637         
2638     //***************************************************************
2639     //***************************************************************
2640     //** These functions deal with Help menu & tool menu items
2641     //***************************************************************
2642     //***************************************************************
2643         // Show database status
2644         @SuppressWarnings("unused")
2645         private void databaseStatus() {
2646                 waitCursor(true);
2647                 indexRunner.interrupt = true;
2648                 int dirty = conn.getNoteTable().getDirtyCount();
2649                 int unindexed = conn.getNoteTable().getUnindexedCount();
2650                 DatabaseStatus status = new DatabaseStatus();
2651                 status.setUnsynchronized(dirty);
2652                 status.setUnindexed(unindexed);
2653                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2654                 status.setNotebookCount(listManager.getNotebookIndex().size());
2655                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2656                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2657                 status.setTagCount(listManager.getTagIndex().size());
2658                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2659                 status.setWordCount(conn.getWordsTable().getWordCount());
2660                 waitCursor(false);
2661                 status.exec();
2662         }
2663         // Compact the database
2664         @SuppressWarnings("unused")
2665         private void compactDatabase() {
2666         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2667                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2668                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2669                                 "and NixNote will be unresponsive until it is complete.  Do you wish to continue?"),
2670                                 QMessageBox.StandardButton.Yes, 
2671                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2672                                                         return;
2673                 }
2674                 setMessage("Compacting database.");
2675                 waitCursor(true);
2676                 listManager.compactDatabase();
2677                 waitCursor(false);
2678                 setMessage("Database compact is complete.");            
2679         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2680     }
2681         @SuppressWarnings("unused")
2682         private void accountInformation() {
2683                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2684                 AccountDialog dialog = new AccountDialog();
2685                 dialog.show();
2686                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2687         }
2688         @SuppressWarnings("unused")
2689         private void releaseNotes() {
2690                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2691                 QDialog dialog = new QDialog(this);
2692                 QHBoxLayout layout = new QHBoxLayout();
2693                 QTextEdit textBox = new QTextEdit();
2694                 layout.addWidget(textBox);
2695                 textBox.setReadOnly(true);
2696                 QFile file = new QFile(Global.getFileManager().getProgramDirPath("release.txt"));
2697                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2698                 QIODevice.OpenModeFlag.Text)))
2699                         return;
2700                 textBox.setText(file.readAll().toString());
2701                 file.close();
2702                 dialog.setWindowTitle(tr("Release Notes"));
2703                 dialog.setLayout(layout);
2704                 dialog.show();
2705                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2706         }
2707         // Called when user picks Log from the help menu
2708         @SuppressWarnings("unused")
2709         private void logger() {
2710                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2711                 LogFileDialog dialog = new LogFileDialog(emitLog);
2712                 dialog.exec();
2713                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2714         }
2715         // Menu option "help/about" was selected
2716         @SuppressWarnings("unused")
2717         private void about() {
2718                 logger.log(logger.HIGH, "Entering NeverNote.about");
2719                 QMessageBox.about(this, 
2720                                                 tr("About NixNote"),
2721                                                 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2722                                                 +Global.version
2723                                                 +tr("<hr>"
2724                                                                 +"Open Source Evernote Client.<br><br>" 
2725                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2726                                                                 +"</center>Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2727                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2728                                                                 +"PDFRenderer is licened under the LGPL<br>"
2729                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2730                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2731                                                                 +"Jazzy is licened under the LGPL<br>"
2732                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2733                                                                 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2734                                                                 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2735                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2736         }
2737         // Hide the entire left hand side
2738         @SuppressWarnings("unused")
2739         private void toggleLeftSide() {
2740                 boolean hidden;
2741                 
2742                 hidden = !menuBar.hideLeftSide.isChecked();
2743                 menuBar.hideLeftSide.setChecked(!hidden);
2744                 
2745                 if (!hidden) 
2746                         leftSplitter1.setHidden(true);
2747                 else
2748                         leftSplitter1.setHidden(false);
2749                 
2750                 Global.saveWindowVisible("leftPanel", hidden);
2751                 
2752         }
2753         public void checkForUpdates() {
2754                 // Send off thread to check for a new version
2755                 versionChecker = new QNetworkAccessManager(this);
2756                 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2757                 QNetworkRequest request = new QNetworkRequest();
2758                 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2759                 versionChecker.get(request);
2760         }
2761         @SuppressWarnings("unused")
2762         private void upgradeFileRead(QNetworkReply reply) {
2763                 if (!reply.isReadable())
2764                         return;
2765                 
2766                 String winVersion = Global.version;
2767                 String osxVersion = Global.version;
2768                 String linuxVersion = Global.version;
2769                 String linux64Version = Global.version;
2770                 String version = Global.version;
2771                 
2772                 // Determine the versions available
2773                 QByteArray data = reply.readLine();
2774                 while (data != null && !reply.atEnd()) {
2775                         String line = data.toString();
2776                         String lineVersion;
2777                         if (line.contains(":")) 
2778                                 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2779                         else
2780                                 lineVersion = "";
2781                         if (line.toLowerCase().contains("windows")) 
2782                                 winVersion = lineVersion;
2783                         else if (line.toLowerCase().contains("os-x")) 
2784                                 osxVersion = lineVersion;
2785                         else if (line.toLowerCase().contains("linux amd64")) 
2786                                 linux64Version = lineVersion;
2787                         else if (line.toLowerCase().contains("linux i386")) 
2788                                 linuxVersion = lineVersion;
2789                         else if (line.toLowerCase().contains("default")) 
2790                                 version = lineVersion;
2791                         
2792                         // Read the next line
2793                         data = reply.readLine();
2794                 }
2795                 
2796                 // Now we need to determine what system we are on.
2797                 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2798                         version = winVersion;
2799                 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2800                         version = osxVersion;
2801                 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2802                         if (System.getProperty("os.arch").contains("amd64") ||
2803                                 System.getProperty("os.arch").contains("x86_64"))
2804                                         version = linux64Version;
2805                         else
2806                                 version = linuxVersion;
2807                 }
2808                 
2809                 
2810                 for (String validVersion : Global.validVersions) {
2811                         if (version.equals(validVersion))
2812                                 return;
2813                 }
2814                 
2815                 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2816                 dialog.exec();
2817                 if (dialog.remindMe())
2818                         Global.setCheckVersionUpgrade(true);
2819                 else
2820                         Global.setCheckVersionUpgrade(false);
2821         }
2822                 
2823         
2824     //***************************************************************
2825     //***************************************************************
2826     //** These functions deal with the Toolbar
2827     //***************************************************************
2828     //*************************************************************** 
2829         @SuppressWarnings("unused")
2830         private void focusSearch() {
2831                 searchField.setFocus();
2832         }
2833
2834         // Text in the search bar has been cleared
2835         private void searchFieldCleared() {
2836                 saveNote();
2837                 
2838                 // This is done because we want to force a reload of
2839                 // images.  Some images we may want to highlight the text.
2840                 readOnlyCache.clear();
2841                 inkNoteCache.clear();
2842                 noteCache.clear();
2843                 QWebSettings.setMaximumPagesInCache(0);
2844                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2845         
2846                 searchField.setEditText("");
2847                 saveNoteColumnPositions();
2848                 saveNoteIndexWidth();
2849                 noteIndexUpdated(true);
2850                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2851                         currentNote = listManager.getNoteIndex().get(0);
2852                         currentNoteGuid = currentNote.getGuid();
2853                 }
2854                 refreshEvernoteNote(true);
2855                 if (currentNote != null)
2856                         loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2857         }
2858         // text in the search bar changed.  We only use this to tell if it was cleared, 
2859         // otherwise we trigger off searchFieldChanged.
2860         @SuppressWarnings("unused")
2861         private void searchFieldTextChanged(String text) {
2862                 QWebSettings.setMaximumPagesInCache(0);
2863                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2864
2865                 if (text.trim().equals("")) {
2866                         searchFieldCleared();
2867                         if (searchPerformed) {
2868
2869                                 // This is done because we want to force a reload of
2870                                 // images.  Some images we may want to highlight the text.
2871                                 noteCache.clear();
2872                                 readOnlyCache.clear();
2873                                 inkNoteCache.clear();
2874                                 
2875                                 listManager.setEnSearch("");
2876                                 listManager.loadNotesIndex();
2877                                 refreshEvernoteNote(true);
2878                                 noteIndexUpdated(false);
2879                                 refreshEvernoteNote(true);
2880                         }
2881                         searchPerformed = false;
2882                 }
2883         }
2884     // Text in the toolbar has changed
2885     private void searchFieldChanged() {
2886         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2887         noteCache.clear();
2888         readOnlyCache.clear();
2889         inkNoteCache.clear();
2890         saveNoteColumnPositions();
2891         saveNoteIndexWidth();
2892         String text = searchField.currentText();
2893         listManager.setEnSearch(text.trim());
2894         listManager.loadNotesIndex();
2895         noteIndexUpdated(false);
2896
2897         refreshEvernoteNote(true);
2898         searchPerformed = true;
2899         waitCursor(false);
2900         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2901     }
2902
2903     // Build the window tool bar
2904     private void setupToolBar() {
2905         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2906         toolBar = addToolBar(tr("Tool Bar"));   
2907         toolBar.setObjectName("toolBar");
2908         menuBar.setupToolBarVisible();
2909         if (!Global.isWindowVisible("toolBar"))
2910                 toolBar.setVisible(false);
2911         else
2912                 toolBar.setVisible(true);
2913
2914 //      toolBar.addWidget(menuBar);
2915 //      menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2916 //      toolBar.addSeparator();
2917         prevButton = toolBar.addAction(tr("Previous"));
2918         QIcon prevIcon = new QIcon(iconPath+"back.png");
2919         prevButton.setIcon(prevIcon);
2920         prevButton.triggered.connect(this, "previousViewedAction()");   
2921         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2922         
2923         nextButton = toolBar.addAction(tr("Next"));
2924         QIcon nextIcon = new QIcon(iconPath+"forward.png");
2925         nextButton.setIcon(nextIcon);
2926         nextButton.triggered.connect(this, "nextViewedAction()");       
2927         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2928         
2929         upButton = toolBar.addAction(tr("Up"));
2930         QIcon upIcon = new QIcon(iconPath+"up.png");
2931         upButton.setIcon(upIcon);
2932         upButton.triggered.connect(this, "upAction()");         
2933         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2934
2935         
2936         downButton = toolBar.addAction(tr("Down"));
2937         QIcon downIcon = new QIcon(iconPath+"down.png");
2938         downButton.setIcon(downIcon);
2939         downButton.triggered.connect(this, "downAction()");
2940         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2941         
2942         synchronizeButton = toolBar.addAction(tr("Synchronize"));
2943         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2944         synchronizeIconAngle = 0;
2945         synchronizeButton.triggered.connect(this, "evernoteSync()");
2946         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2947         
2948         printButton = toolBar.addAction(tr("Print"));
2949         QIcon printIcon = new QIcon(iconPath+"print.png");
2950         printButton.setIcon(printIcon);
2951         printButton.triggered.connect(this, "printNote()");
2952         togglePrintButton(Global.isToolbarButtonVisible("print"));
2953
2954         tagButton = toolBar.addAction(tr("Tag")); 
2955         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2956         tagButton.setIcon(tagIcon);
2957         tagButton.triggered.connect(browserWindow, "modifyTags()");
2958         toggleTagButton(Global.isToolbarButtonVisible("tag"));
2959
2960         attributeButton = toolBar.addAction(tr("Attributes")); 
2961         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2962         attributeButton.setIcon(attributeIcon);
2963         attributeButton.triggered.connect(this, "toggleNoteInformation()");
2964         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2965                 
2966         emailButton = toolBar.addAction(tr("Email"));
2967         QIcon emailIcon = new QIcon(iconPath+"email.png");
2968         emailButton.setIcon(emailIcon);
2969         emailButton.triggered.connect(this, "emailNote()");
2970         toggleEmailButton(Global.isToolbarButtonVisible("email"));
2971
2972         deleteButton = toolBar.addAction(tr("Delete"));         
2973         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2974         deleteButton.setIcon(deleteIcon);
2975         deleteButton.triggered.connect(this, "deleteNote()");
2976         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2977
2978         newButton = toolBar.addAction(tr("New"));
2979         QIcon newIcon = new QIcon(iconPath+"new.png");
2980         newButton.triggered.connect(this, "addNote()");
2981         newButton.setIcon(newIcon);
2982         toggleNewButton(Global.isToolbarButtonVisible("new"));
2983         
2984         allNotesButton = toolBar.addAction(tr("All Notes"));
2985         QIcon allIcon = new QIcon(iconPath+"books.png");
2986         allNotesButton.triggered.connect(this, "allNotes()");
2987         allNotesButton.setIcon(allIcon);
2988         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2989         
2990         //toolBar.addSeparator();
2991         //toolBar.addWidget(new QLabel(tr("Quota:")));
2992         //toolBar.addWidget(quotaBar);
2993         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2994         updateQuotaBar();
2995         //toolBar.addSeparator();
2996         
2997         //toolBar.addWidget(new QLabel(tr("Zoom")));
2998         //toolBar.addWidget(zoomSpinner);
2999         
3000         //toolBar.addWidget(new QLabel("                    "));
3001         //toolBar.addSeparator();
3002         //toolBar.addWidget(new QLabel(tr("  Search:")));
3003         //toolBar.addWidget(searchField);
3004         QSizePolicy sizePolicy = new QSizePolicy();
3005         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3006         QLabel spacer = new QLabel("");
3007         spacer.setSizePolicy(sizePolicy);
3008         toolBar.addWidget(spacer);
3009         //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3010
3011         //searchClearButton = toolBar.addAction("Search Clear");
3012         //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3013         //searchClearButton.setIcon(searchClearIcon);
3014         //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3015         //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3016
3017         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3018     }
3019     // Update the sychronize button picture
3020     @Override
3021         public QMenu createPopupMenu() {
3022         QMenu contextMenu = super.createPopupMenu();
3023         
3024         contextMenu.addSeparator();
3025         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3026         contextMenu.addAction(prevAction);
3027         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3028
3029         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3030         contextMenu.addAction(nextAction);
3031         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3032
3033         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3034         contextMenu.addAction(upAction);
3035         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3036
3037         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3038         contextMenu.addAction(downAction);
3039         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3040
3041         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));