OSDN Git Service

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