OSDN Git Service

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