OSDN Git Service

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