OSDN Git Service

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