OSDN Git Service

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