OSDN Git Service

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