OSDN Git Service

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