OSDN Git Service

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