OSDN Git Service

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