OSDN Git Service

Merge branch 'development' of ssh://nevernote.git.sourceforge.net/gitroot/nevernote...
[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         historyGuids = new ArrayList<String>();
696         historyPosition = 0;
697         fromHistory = false;
698                 noteDirty = false;
699                 if (!currentNoteGuid.trim().equals("")) {
700                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
701                 }
702                 
703                 noteIndexUpdated(true);
704                 showColumns();
705                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
706                 if (menuBar.showEditorBar.isChecked())
707                 showEditorButtons(browserWindow);
708                 tagIndexUpdated(true);
709                 savedSearchIndexUpdated();
710                 notebookIndexUpdated();
711                 updateQuotaBar();
712         setupSyncSignalListeners();        
713         setupBrowserSignalListeners();
714         setupIndexListeners();
715               
716         
717         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
718         tagTree.showAllTags(true);
719
720                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
721                 if (QSystemTrayIcon.isSystemTrayAvailable()) {
722                         setWindowIcon(appIcon);
723                         trayIcon.setIcon(appIcon);
724                         if (Global.showTrayIcon() || Global.minimizeOnClose())
725                                 trayIcon.show();
726                         else
727                                 trayIcon.hide();
728                 }
729         
730         scrollToGuid(currentNoteGuid);
731         if (Global.automaticLogin()) {
732                 remoteConnect();
733                 if (Global.isConnected)
734                         syncTimer();
735         }
736         setupFolderImports();
737         
738         loadStyleSheet();
739         restoreWindowState(true);
740         
741         if (Global.mimicEvernoteInterface) {
742                 notebookTree.selectGuid("");
743         }
744         
745         threadMonitorTimer = new QTimer();
746         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
747         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
748         
749         historyGuids.add(currentNoteGuid);
750         historyPosition = 1;
751         
752         menuBar.blockSignals(true);
753         menuBar.narrowListView.blockSignals(true);
754         menuBar.wideListView.blockSignals(true);
755         if (Global.getListView() == Global.View_List_Narrow) { 
756                 menuBar.narrowListView.setChecked(true);
757         }
758         else{ 
759                 menuBar.wideListView.setChecked(true);
760         }
761         menuBar.blockSignals(false);
762         menuBar.narrowListView.blockSignals(false);
763         menuBar.wideListView.blockSignals(false);
764
765         if (Global.getListView() == Global.View_List_Wide) {
766                 browserIndexSplitter.addWidget(noteTableView);
767                 browserIndexSplitter.addWidget(browserWindow); 
768         } else {
769                 mainLeftRightSplitter.addWidget(noteTableView);
770                 mainLeftRightSplitter.addWidget(browserWindow); 
771         }
772         
773                 messageTimer = new QTimer();
774                 messageTimer.timeout.connect(this, "clearMessage()");
775                 messageTimer.setInterval(1000*15);
776                 clearMessage();
777         
778         int sortCol = Global.getSortColumn();
779                 int sortOrder = Global.getSortOrder();
780                 noteTableView.proxyModel.blocked = true;
781                 // We sort the table twice to fix a bug.  For some reaosn the table won't sort properly if it is in narrow
782                 // list view and sorted descending on the date  created.  By sorting it twice it forces the proper sort.  Ugly.
783                 if (sortCol == 0 && sortOrder == 1 && Global.getListView() == Global.View_List_Narrow) 
784                         noteTableView.sortByColumn(sortCol, SortOrder.resolve(0));   
785                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
786                 noteTableView.proxyModel.blocked = false;
787                 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
788                 
789                 // Set the startup notebook
790         String defaultNotebook = Global.getStartupNotebook();
791         if (!defaultNotebook.equals("AllNotebooks") && !defaultNotebook.equals("")) {
792                 for (int k=0; k<listManager.getNotebookIndex().size(); k++) {
793                         if (listManager.getNotebookIndex().get(k).isDefaultNotebook()) {
794                                 notebookTree.clearSelection();
795                                 notebookTree.selectGuid(listManager.getNotebookIndex().get(k).getGuid());
796                                 notebookTree.selectionSignal.emit();
797                         }
798                 }
799         }
800                 
801    
802                         
803                         
804                 if (Global.checkVersionUpgrade())
805                         checkForUpdates();
806         }
807         
808         
809         public void debugDirty() {
810                 List<Note> dirty = conn.getNoteTable().getDirty();
811                 logger.log(logger.LOW, "------ Dirty Notes List Begin ------");
812                 for (int i=0; i<dirty.size(); i++) {
813                         logger.log(logger.LOW, "GUID: " +dirty.get(i).getGuid() + " Title:" + dirty.get(i).getTitle());
814                 }
815                 logger.log(logger.LOW, "------ Dirty Notes List End ------");
816         }
817                 
818         // Main entry point
819         public static void main(String[] args) {
820                 log.setLevel(Level.FATAL);
821                 QApplication.initialize(args);
822                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
823                 QSplashScreen splash = new QSplashScreen(pixmap);
824                 boolean showSplash;
825                 
826                 DatabaseConnection dbConn;
827
828         try {
829             initializeGlobalSettings(args);
830
831             showSplash = Global.isWindowVisible("SplashScreen");
832             if (showSplash)
833                 splash.show();
834
835             dbConn = setupDatabaseConnection();
836
837             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
838             Global.getFileManager().purgeResDirectory(true);
839
840         } catch (InitializationException e) {
841             // Fatal
842             e.printStackTrace();
843             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
844             return;
845         }
846         
847                 // Setup proxy crap
848                 String proxyUrl = Global.getProxyValue("url");
849                 String proxyPort = Global.getProxyValue("port");
850                 String proxyUserid = Global.getProxyValue("userid");
851                 String proxyPassword = Global.getProxyValue("password");
852                 boolean proxySet = false;
853                 QNetworkProxy proxy = new QNetworkProxy();
854                 proxy.setType(ProxyType.HttpProxy);
855                 if (!proxyUrl.trim().equals("")) {
856                         System.out.println("Proxy URL found: " +proxyUrl);
857                         proxySet = true;
858                         proxy.setHostName(proxyUrl);
859                 }
860                 if (!proxyPort.trim().equals("")) {
861                         System.out.println("Proxy Port found: " +proxyPort);
862                         proxySet = true;
863                         proxy.setPort(Integer.parseInt(proxyPort));
864                 }
865                 if (!proxyUserid.trim().equals("")) {
866                         System.out.println("Proxy Userid found: " +proxyUserid);
867                         proxySet = true;
868                         proxy.setUser(proxyUserid);
869                 }
870                 if (!proxyPassword.trim().equals("")) {
871                         System.out.println("Proxy URL found: " +proxyPassword);
872                         proxySet = true;
873                         proxy.setPassword(proxyPassword);
874                 }
875                 if (proxySet) {
876                         QNetworkProxy.setApplicationProxy(proxy);
877                 }
878                         
879
880         NeverNote application = new NeverNote(dbConn);
881                 if (Global.syncOnly) {
882                         System.out.println("Performing synchronization only.");
883                         application.remoteConnect();
884                         if (Global.isConnected) {
885                                 application.syncRunner.syncNeeded = true;
886                                 application.syncRunner.addWork("SYNC");
887                                 application.syncRunner.addWork("STOP");
888                                 while(!application.syncRunner.isIdle());
889                                 application.closeNeverNote();
890                         }
891                         return;
892                 }
893
894                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
895                 if (Global.startMinimized()) 
896                         application.showMinimized();
897                 else {
898                         if (Global.wasWindowMaximized())
899                                 application.showMaximized();
900                         else
901                                 application.show();
902                 }
903                 
904                 if (showSplash)
905                         splash.finish(application);
906                 QApplication.exec();
907                 System.out.println("Goodbye.");
908                 QApplication.exit();
909         }
910
911     /**
912      * Open the internal database, or create if not present
913      *
914      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
915      */
916     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
917         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
918         
919         File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
920         File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
921         File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
922                 if (!f.exists())
923                         Global.setDatabaseUrl("");
924                 if (!fr.exists())
925                         Global.setResourceDatabaseUrl("");              
926                 if (!fi.exists())
927                         Global.setIndexDatabaseUrl(""); 
928         
929         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
930             boolean goodCheck = false;
931             while (!goodCheck) {
932                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
933                 dialog.exec();
934                 if (!dialog.okPressed())
935                     System.exit(0);
936                 Global.cipherPassword = dialog.getPassword();
937                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
938                         Global.getDatabaseUserPassword(), Global.cipherPassword);
939             }
940         }
941         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), 
942                         Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
943                         Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
944        return dbConn;
945     }
946     
947     // Encrypt the database upon shutdown
948     private void encryptOnShutdown() {
949         String dbPath= Global.getFileManager().getDbDirPath("");
950         try {
951                 
952                 Statement st = conn.getConnection().createStatement();  
953                 st.execute("shutdown");
954                 st = conn.getResourceConnection().createStatement();
955                 st.execute("shutdown");
956                 st = conn.getIndexConnection().createStatement();
957                 st.execute("shutdown");
958                 if (QMessageBox.question(this, tr("Are you sure"), 
959                                 tr("Are you sure you wish to encrypt the database?"),
960                                 QMessageBox.StandardButton.Yes, 
961                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
962                         ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
963                         ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
964                         ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
965                         Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
966                         Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
967                         Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
968
969                         QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
970                 }
971         } catch (SQLException e) {
972                         e.printStackTrace();
973                 }       
974     }
975     
976     // Decrypt the database upon shutdown
977     private void decryptOnShutdown() {
978         String dbPath= Global.getFileManager().getDbDirPath("");
979         String dbName = "NeverNote";
980         try {
981                 Statement st = conn.getConnection().createStatement();  
982                 st.execute("shutdown");
983                 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
984                         encryptCipher = "AES";
985                 else
986                         encryptCipher = "XTEA";
987                 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure", 
988                                 "Are you sure you wish to decrypt the database?"),
989                                 QMessageBox.StandardButton.Yes, 
990                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
991
992                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
993                         Global.setDatabaseUrl("");
994                         Global.setResourceDatabaseUrl("");
995                         Global.setIndexDatabaseUrl("");
996                         QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
997                 }
998                 } catch (SQLException e) {
999                         e.printStackTrace();
1000                 }       
1001     }
1002     /**
1003      * Encrypt/Decrypt the local database
1004      **/
1005     public void doDatabaseEncrypt() {
1006         // The database is not currently encrypted
1007         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
1008                 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
1009                                 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
1010                                 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
1011                                 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
1012                                 "Do you wish to proceed?"),
1013                                 QMessageBox.StandardButton.Yes, 
1014                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1015                                 return;
1016                 }
1017                 DBEncryptDialog dialog = new DBEncryptDialog();
1018                 dialog.exec();
1019                 if (dialog.okPressed()) {
1020                         Global.cipherPassword = dialog.getPassword();
1021                         encryptOnShutdown  = true;
1022                         encryptCipher = dialog.getEncryptionMethod();
1023                 }
1024         } else {
1025             DBEncryptDialog dialog = new DBEncryptDialog();
1026             dialog.setWindowTitle(tr("Database Decryption"));
1027             dialog.hideEncryption();
1028             dialog.exec();
1029             if (dialog.okPressed()) {
1030                 if (!dialog.getPassword().equals(Global.cipherPassword)) {
1031                         QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
1032                         return;
1033                 }
1034                 decryptOnShutdown  = true;
1035                 encryptCipher = "";
1036             }
1037         }
1038         return;
1039     }
1040
1041         private static void initializeGlobalSettings(String[] args) throws InitializationException {
1042                 StartupConfig   startupConfig = new StartupConfig();
1043
1044         for (String arg : args) {
1045             String lower = arg.toLowerCase();
1046             if (lower.startsWith("--name="))
1047                startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
1048             if (lower.startsWith("--home="))
1049                startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
1050             if (lower.startsWith("--disable-viewing"))
1051                startupConfig.setDisableViewing(true);
1052             if (lower.startsWith("--sync-only=true"))
1053                 startupConfig.setSyncOnly(true);
1054         }
1055         Global.setup(startupConfig);
1056         
1057     }
1058
1059     // Exit point
1060         @Override
1061         public void closeEvent(QCloseEvent event) {     
1062                 if (Global.minimizeOnClose() && !closeAction) {
1063                         event.ignore();
1064                         hide();
1065                         return;
1066                 }
1067                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
1068                 waitCursor(true);
1069                 
1070                 if (currentNote!= null & browserWindow!=null) {
1071                         if (currentNote.getTitle() != null && browserWindow != null 
1072                                         && !currentNote.getTitle().equals(browserWindow.getTitle()))
1073                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
1074                 }
1075                 saveNote();
1076                 setMessage(tr("Beginning shutdown."));
1077                 
1078                 // Close down external windows
1079                 Collection<ExternalBrowse> windows = externalWindows.values();
1080                 Iterator<ExternalBrowse> iterator = windows.iterator();
1081                 while (iterator.hasNext()) {
1082                         ExternalBrowse browser = iterator.next();
1083                         browser.windowClosing.disconnect();
1084                         browser.close();
1085                 }
1086                 
1087                 
1088                 externalFileEditedSaver();
1089                 if (Global.isConnected && Global.synchronizeOnClose()) {
1090                         setMessage(tr("Performing synchronization before closing."));
1091                         syncRunner.syncNeeded = true;
1092                         syncRunner.addWork("SYNC");
1093                 } else {
1094                         syncRunner.keepRunning = false;
1095                 }
1096                 syncRunner.addWork("STOP");
1097                 setMessage("Closing Program.");
1098                 threadMonitorTimer.stop();
1099
1100                 thumbnailRunner.addWork("STOP");
1101                 indexRunner.addWork("STOP");
1102                 saveNote();
1103                 listManager.stop();
1104                 saveWindowState();
1105
1106                 if (tempFiles != null)
1107                         tempFiles.clear();
1108
1109                 browserWindow.noteSignal.tagsChanged.disconnect();
1110                 browserWindow.noteSignal.titleChanged.disconnect();
1111                 browserWindow.noteSignal.noteChanged.disconnect();
1112                 browserWindow.noteSignal.notebookChanged.disconnect();
1113                 browserWindow.noteSignal.createdDateChanged.disconnect();
1114                 browserWindow.noteSignal.alteredDateChanged.disconnect();
1115                 syncRunner.searchSignal.listChanged.disconnect();
1116                 syncRunner.tagSignal.listChanged.disconnect();
1117         syncRunner.notebookSignal.listChanged.disconnect();
1118         syncRunner.noteIndexSignal.listChanged.disconnect();
1119
1120                 if (isVisible())
1121                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
1122                 saveNoteColumnPositions();
1123                 saveNoteIndexWidth();
1124                 
1125                 int width = notebookTree.columnWidth(0);
1126                 Global.setColumnWidth("notebookTreeName", width);
1127                 width = tagTree.columnWidth(0);
1128                 Global.setColumnWidth("tagTreeName", width);
1129                 
1130                 Global.saveWindowMaximized(isMaximized());
1131                 Global.saveCurrentNoteGuid(currentNoteGuid);
1132                         
1133                 int sortCol = noteTableView.proxyModel.sortColumn();
1134                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1135                 Global.setSortColumn(sortCol);
1136                 Global.setSortOrder(sortOrder);
1137                 
1138                 hide();
1139                 trayIcon.hide();
1140                 Global.keepRunning = false;
1141                 try {
1142                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1143                         if (indexRunner.thread().isAlive())
1144                                 indexRunner.thread().join(50);
1145                         if (!indexRunner.thread().isAlive())
1146                                 logger.log(logger.MEDIUM, "Index thread has stopped");
1147                         else {
1148                                 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1149                                 indexRunner.thread().interrupt();
1150                         }
1151                 } catch (InterruptedException e1) {
1152                         e1.printStackTrace();
1153                 }
1154                 
1155                 if (!syncRunner.thread().isAlive()) {
1156                         logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1157                         if (syncRunner.thread().isAlive()) {
1158                                 System.out.println(tr("Synchronizing.  Please be patient."));
1159                                 for(;syncRunner.thread().isAlive();) {
1160                                         try {
1161                                                 wait(10);
1162                                         } catch (InterruptedException e) {
1163                                                 e.printStackTrace();
1164                                         }
1165                                 }
1166                         }
1167                         logger.log(logger.MEDIUM, "Sync thread has stopped");
1168                 }
1169
1170                 if (encryptOnShutdown) {
1171                         encryptOnShutdown();
1172                 }
1173                 if (decryptOnShutdown) {
1174                         decryptOnShutdown();
1175                 }
1176                 try {
1177                         Global.getFileManager().purgeResDirectory(false);
1178                 } catch (InitializationException e) {
1179                         System.out.println(tr("Empty res directory purge failed"));
1180                         e.printStackTrace();
1181                 }
1182                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1183         }
1184
1185
1186         private void closeNeverNote() {
1187                 closeAction = true;
1188                 close();
1189         }
1190         public void setMessage(String s) {
1191                 if (logger != null) 
1192                         logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1193                 else
1194                         System.out.println("*** ERROR *** " +s);
1195                 
1196                 if (statusBar != null) {
1197                         statusBar.show();
1198                         if (logger != null) 
1199                                 logger.log(logger.HIGH, "Message: " +s);
1200                         statusBar.showMessage(s);
1201                         if (emitLog != null)
1202                                 emitLog.add(s);
1203                 
1204                         if (messageTimer != null) {
1205                                 messageTimer.stop();
1206                                 messageTimer.setSingleShot(true);
1207                                 messageTimer.start();
1208                         }
1209                 }
1210                         
1211                 if (logger != null) 
1212                         logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1213         }
1214         
1215         private void clearMessage() {
1216                 statusBar.clearMessage();
1217                 statusBar.hide();
1218         }
1219                 
1220         private void waitCursor(boolean wait) {
1221                 if (wait) {
1222                         if (QApplication.overrideCursor() == null)
1223                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1224                 }
1225                 else {
1226                         while (QApplication.overrideCursor() != null)
1227                                 QApplication.restoreOverrideCursor();
1228                 }
1229                 listManager.refreshCounters();
1230         }
1231         
1232         private void setupIndexListeners() {
1233 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1234 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1235                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1236                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1237         }
1238         private void setupSyncSignalListeners() {
1239                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1240         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1241         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1242         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1243         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1244         
1245                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1246                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1247                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1248                 
1249                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1250                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1251                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1252                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1253                 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1254                 
1255                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1256         }
1257         
1258         private void setupBrowserSignalListeners() {
1259                 setupBrowserWindowListeners(browserWindow, true);
1260         }
1261
1262         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1263                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1264                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1265             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1266             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1267             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1268             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1269             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1270             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1271             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1272             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1273             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1274             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1275             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1276             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1277         browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1278         browser.unblockApplication.connect(this, "unblockApplication()");
1279             if (master) browser.focusLost.connect(this, "saveNote()");
1280             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1281             browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1282         }
1283
1284         //**************************************************
1285         //* Setup shortcuts
1286         //**************************************************
1287         private void setupShortcut(QShortcut action, String text) {
1288                 if (!Global.shortcutKeys.containsAction(text))
1289                         return;
1290                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1291         }
1292         
1293         //***************************************************************
1294         //***************************************************************
1295         //* Settings and look & feel
1296         //***************************************************************
1297         //***************************************************************
1298         @SuppressWarnings("unused")
1299         private void settings() {
1300                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1301                 saveNoteColumnPositions();
1302                 saveNoteIndexWidth();
1303                 showColumns();
1304         ConfigDialog settings = new ConfigDialog(this);
1305         String dateFormat = Global.getDateFormat();
1306         String timeFormat = Global.getTimeFormat();
1307         
1308                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1309                 indexTimer.start(indexTime);  // reset indexing timer
1310         
1311         settings.exec();
1312         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1313         indexRunner.indexNoteBody = Global.indexNoteBody();
1314         indexRunner.indexNoteTitle = Global.indexNoteTitle();
1315         indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1316         indexRunner.indexImageRecognition = Global.indexImageRecognition();
1317         if (Global.showTrayIcon() || Global.minimizeOnClose())
1318                 trayIcon.show();
1319         else
1320                 trayIcon.hide();
1321         showColumns();
1322         if (menuBar.showEditorBar.isChecked())
1323                 showEditorButtons(browserWindow);
1324         
1325         // Reset the save timer
1326         if (Global.getAutoSaveInterval() > 0)
1327                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1328         else
1329                 saveTimer.stop();
1330         
1331         
1332         // Set special reloads
1333         if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1334                 conn.executeSql("Delete from LinkedNotebook");
1335                 conn.executeSql("delete from SharedNotebook");
1336                 conn.executeSql("Delete from Notebook where linked=true");
1337                 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1338                 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1339         }
1340
1341         // Reload user data
1342         noteCache.clear();
1343         readOnlyCache.clear();
1344         inkNoteCache.clear();
1345         noteIndexUpdated(true);
1346                 
1347         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1348         }
1349         // Restore things to the way they were
1350         private void restoreWindowState(boolean mainWindow) {
1351                 // We need to name things or this doesn't work.
1352                 setObjectName("NeverNote");
1353         restoreState(Global.restoreState(objectName()));
1354                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1355                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1356                 leftSplitter1.setObjectName("leftSplitter1");   
1357                 
1358                 // Restore the actual positions.
1359                 if (mainWindow)
1360                         restoreGeometry(Global.restoreGeometry(objectName()));
1361         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1362         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1363         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1364        
1365         }
1366         // Save window positions for the next start
1367         private void saveWindowState() {
1368                 Global.saveGeometry(objectName(), saveGeometry());
1369                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1370                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1371                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1372                 Global.saveState(objectName(), saveState());
1373         }    
1374         // Load the style sheet
1375         private void loadStyleSheet() {
1376                 String styleSheetName = "default.qss";
1377                 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1378                                 styleSheetName = "default-cleanlooks.qss";
1379                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1380                 QFile file = new QFile(fileName);
1381                 
1382                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1383                 if (!file.exists()) {
1384                         fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1385                         file = new QFile(fileName);
1386                 }
1387                 file.open(OpenModeFlag.ReadOnly);
1388                 String styleSheet = file.readAll().toString();
1389                 file.close();
1390                 setStyleSheet(styleSheet);
1391         }
1392         // Save column positions for the next time
1393         private void saveNoteColumnPositions() {
1394                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1395                 Global.setColumnPosition("noteTableCreationPosition", position);
1396                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1397                 Global.setColumnPosition("noteTableTagPosition", position);
1398                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1399                 Global.setColumnPosition("noteTableNotebookPosition", position);
1400                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1401                 Global.setColumnPosition("noteTableChangedPosition", position);
1402                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1403                 Global.setColumnPosition("noteTableAuthorPosition", position);
1404                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1405                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1406                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1407                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1408                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1409                 Global.setColumnPosition("noteTableTitlePosition", position);
1410                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1411                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1412                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1413                 Global.setColumnPosition("noteTableGuidPosition", position);
1414                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1415                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1416                 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1417                 Global.setColumnPosition("noteTablePinnedPosition", position);
1418
1419         }
1420         // Save column widths for the next time
1421         private void saveNoteIndexWidth() {
1422                 int width;
1423         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1424         Global.setColumnWidth("noteTableCreationPosition", width);
1425                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1426                 Global.setColumnWidth("noteTableChangedPosition", width);
1427                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1428                 Global.setColumnWidth("noteTableGuidPosition", width);
1429                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1430                 Global.setColumnWidth("noteTableNotebookPosition", width);
1431                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1432                 Global.setColumnWidth("noteTableTagPosition", width);
1433                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1434                 Global.setColumnWidth("noteTableTitlePosition", width);
1435                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1436                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1437                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1438                 Global.setColumnWidth("noteTableAuthorPosition", width);
1439                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1440                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1441                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1442                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1443                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1444                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1445                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1446                 Global.setColumnWidth("noteTableGuidPosition", width);
1447                 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1448                 Global.setColumnWidth("noteTablePinnedPosition", width);
1449         }
1450         
1451         @SuppressWarnings("unused")
1452         private void toggleSearchWindow() {
1453                 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1454         searchLayout.toggleSearchField();
1455         menuBar.hideSearch.setChecked(searchField.isVisible());
1456         Global.saveWindowVisible("searchField", searchField.isVisible());
1457         logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1458     }   
1459         @SuppressWarnings("unused")
1460         private void toggleQuotaWindow() {
1461                 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1462         searchLayout.toggleQuotaBar();
1463         menuBar.hideQuota.setChecked(quotaBar.isVisible());
1464         Global.saveWindowVisible("quota", quotaBar.isVisible());
1465         logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1466     }   
1467         @SuppressWarnings("unused")
1468         private void toggleZoomWindow() {
1469                 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1470         searchLayout.toggleZoom();
1471         menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1472         Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1473         logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1474     }   
1475         
1476         
1477         
1478     //***************************************************************
1479     //***************************************************************
1480     //** These functions deal with Notebook menu items
1481     //***************************************************************
1482     //***************************************************************
1483     // Setup the tree containing the user's notebooks.
1484     private void initializeNotebookTree() {       
1485         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1486 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1487         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1488         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1489         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1490     }   
1491     // Listener when a notebook is selected
1492         private void notebookTreeSelection() {
1493                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1494                 noteTableView.proxyModel.blocked = true;
1495                 
1496                 clearTrashFilter();
1497                 clearAttributeFilter();
1498                 clearSavedSearchFilter();
1499                 if (Global.mimicEvernoteInterface) {
1500                         clearTagFilter();
1501                         //searchField.clear();
1502                         searchField.clearEditText();
1503                 }
1504                 menuBar.noteRestoreAction.setVisible(false);            
1505         menuBar.notebookEditAction.setEnabled(true);
1506         menuBar.notebookDeleteAction.setEnabled(true);
1507         menuBar.notebookPublishAction.setEnabled(true);
1508         menuBar.notebookShareAction.setEnabled(true);
1509         menuBar.notebookIconAction.setEnabled(true);
1510         menuBar.notebookStackAction.setEnabled(true);
1511         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1512         selectedNotebookGUIDs.clear();
1513                 String guid = "";
1514                 String stackName = "";
1515                 if (selections.size() > 0) {
1516                 guid = (selections.get(0).text(2));
1517                 stackName = selections.get(0).text(0);
1518         }
1519                 if (!Global.mimicEvernoteInterface) {
1520                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1521                         if (selections.size()==0) {
1522                                 selectedNotebookGUIDs.clear();
1523                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1524                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1525                                 }
1526                                 menuBar.notebookEditAction.setEnabled(false);
1527                                 menuBar.notebookDeleteAction.setEnabled(false);
1528                                 menuBar.notebookStackAction.setEnabled(false);
1529                                 menuBar.notebookIconAction.setEnabled(false);
1530                         }
1531                 }
1532         if (!guid.equals("") && !guid.equals("STACK")) {
1533                 selectedNotebookGUIDs.add(guid);
1534                 menuBar.notebookIconAction.setEnabled(true);
1535         } else {
1536                 menuBar.notebookIconAction.setEnabled(true);
1537                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1538                                 Notebook book = listManager.getNotebookIndex().get(j);
1539                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1540                                         selectedNotebookGUIDs.add(book.getGuid());
1541                         }
1542         }
1543         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1544         listManager.loadNotesIndex();
1545         noteIndexUpdated(false);
1546         refreshEvernoteNote(true);
1547         listManager.refreshCounters = true;
1548         listManager.refreshCounters();
1549         if (selectedNotebookGUIDs.size() == 1) {
1550                 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1551                 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1552                 if (col != -1) {
1553                         noteTableView.proxyModel.blocked = true;
1554                         if (order == 1)
1555                                 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1556                         else
1557                                 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1558                 }
1559         }
1560         noteTableView.proxyModel.blocked = false;
1561                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1562
1563     }
1564     private void clearNotebookFilter() {
1565         notebookTree.blockSignals(true);
1566         notebookTree.clearSelection();
1567                 menuBar.noteRestoreAction.setVisible(false);
1568         menuBar.notebookEditAction.setEnabled(false);
1569         menuBar.notebookDeleteAction.setEnabled(false);
1570         selectedNotebookGUIDs.clear();
1571         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1572         notebookTree.blockSignals(false);
1573     }
1574         // Triggered when the notebook DB has been updated
1575         private void notebookIndexUpdated() {
1576                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1577         
1578                 // Get the possible icons
1579                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1580         notebookTree.setIcons(icons);
1581         
1582         if (selectedNotebookGUIDs == null)
1583                         selectedNotebookGUIDs = new ArrayList<String>();
1584                 List<Notebook> books = conn.getNotebookTable().getAll();
1585                 for (int i=books.size()-1; i>=0; i--) {
1586                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1587                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1588                                         books.remove(i);
1589                                         j=listManager.getArchiveNotebookIndex().size();
1590                                 }
1591                         }
1592                 }
1593                 
1594                 
1595                 listManager.countNotebookResults(listManager.getNoteIndex());
1596                 notebookTree.blockSignals(true);
1597         notebookTree.load(books, listManager.getLocalNotebooks());
1598         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1599                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1600                 if (!found)
1601                         selectedNotebookGUIDs.remove(i);
1602         }
1603         listManager.refreshCounters = true;
1604         listManager.refreshCounters();
1605         notebookTree.blockSignals(false);
1606         
1607                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1608     }
1609     // Show/Hide note information
1610         @SuppressWarnings("unused")
1611         private void toggleNotebookWindow() {
1612                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1613                 searchLayout.toggleNotebook();
1614         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1615         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1616         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1617     }   
1618         // Add a new notebook
1619         @SuppressWarnings("unused")
1620         private void addNotebook() {
1621                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1622                 NotebookEdit edit = new NotebookEdit();
1623                 edit.setNotebooks(listManager.getNotebookIndex());
1624                 edit.exec();
1625         
1626                 if (!edit.okPressed())
1627                         return;
1628         
1629                 Calendar currentTime = new GregorianCalendar();
1630                 Long l = new Long(currentTime.getTimeInMillis());
1631                 String randint = new String(Long.toString(l));
1632         
1633                 Notebook newBook = new Notebook();
1634                 newBook.setUpdateSequenceNum(0);
1635                 newBook.setGuid(randint);
1636                 newBook.setName(edit.getNotebook());
1637                 newBook.setServiceCreated(new Date().getTime());
1638                 newBook.setServiceUpdated(new Date().getTime());
1639                 newBook.setDefaultNotebook(false);
1640                 newBook.setPublished(false);
1641                 
1642                 listManager.getNotebookIndex().add(newBook);
1643                 if (edit.isLocal())
1644                         listManager.getLocalNotebooks().add(newBook.getGuid());
1645                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1646                 notebookIndexUpdated();
1647                 listManager.countNotebookResults(listManager.getNoteIndex());
1648 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1649                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1650         }
1651         // Edit an existing notebook
1652         @SuppressWarnings("unused")
1653         private void stackNotebook() {
1654                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1655                 StackNotebook edit = new StackNotebook();
1656                 
1657                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1658                 QTreeWidgetItem currentSelection;
1659                 for (int i=0; i<selections.size(); i++) {
1660                         currentSelection = selections.get(0);
1661                         String guid = currentSelection.text(2);
1662                         if (guid.equalsIgnoreCase("")) {
1663                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1664                                  return;
1665                         }
1666                         if (guid.equalsIgnoreCase("STACK")) {
1667                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1668                                  return;
1669                         }
1670                 }
1671
1672                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1673
1674                 
1675                 edit.exec();
1676         
1677                 if (!edit.okPressed())
1678                         return;
1679         
1680                 String stack = edit.getStackName();
1681                 
1682                 for (int i=0; i<selections.size(); i++) {
1683                         currentSelection = selections.get(i);
1684                         String guid = currentSelection.text(2);
1685                         listManager.updateNotebookStack(guid, stack);
1686                 }
1687                 notebookIndexUpdated();
1688                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1689         }
1690         // Edit an existing notebook
1691         @SuppressWarnings("unused")
1692         private void editNotebook() {
1693                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1694                 NotebookEdit edit = new NotebookEdit();
1695                 
1696                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1697                 QTreeWidgetItem currentSelection;
1698                 currentSelection = selections.get(0);
1699                 edit.setNotebook(currentSelection.text(0));
1700                 
1701                 String guid = currentSelection.text(2);
1702                 if (!guid.equalsIgnoreCase("STACK")) {
1703                         edit.setTitle(tr("Edit Notebook"));
1704                         edit.setNotebooks(listManager.getNotebookIndex());
1705                         edit.setLocalCheckboxEnabled(false);
1706                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1707                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1708                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1709                                         i=listManager.getNotebookIndex().size();
1710                                 }
1711                         }
1712                 } else {
1713                         edit.setTitle(tr("Edit Stack"));
1714                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1715                         edit.hideLocalCheckbox();
1716                         edit.hideDefaultCheckbox();
1717                 }
1718                 
1719                 edit.exec();
1720         
1721                 if (!edit.okPressed())
1722                         return;
1723         
1724                 
1725                 if (guid.equalsIgnoreCase("STACK")) {
1726                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1727                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1728                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1729                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1730                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1731                         }
1732                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1733                         currentSelection.setText(0, edit.getNotebook());
1734                         return;
1735                 }
1736                 
1737                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1738                 currentSelection.setText(0, edit.getNotebook());
1739                 
1740                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1741                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1742                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1743                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1744                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1745                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1746                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1747                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1748                                 }
1749                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1750                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1751                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1752                                         linkedNotebook.setShareName(edit.getNotebook());
1753                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1754                                 }
1755                                 i=listManager.getNotebookIndex().size();
1756                         }
1757                 }
1758                 
1759                 // Build a list of non-closed notebooks
1760                 List<Notebook> nbooks = new ArrayList<Notebook>();
1761                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1762                         boolean found=false;
1763                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1764                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1765                                         found = true;
1766                         }
1767                         if (!found)
1768                                 nbooks.add(listManager.getNotebookIndex().get(i));
1769                 }
1770                 
1771                 
1772                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1773                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1774                 browserWindow.setNotebookList(filteredBooks);
1775                 Iterator<String> set = externalWindows.keySet().iterator();
1776                 while(set.hasNext())
1777                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1778                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1779         }
1780         // Publish a notebook
1781         @SuppressWarnings("unused")
1782         private void publishNotebook() {
1783                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1784                 QTreeWidgetItem currentSelection;
1785                 currentSelection = selections.get(0);
1786                 String guid = currentSelection.text(2);
1787
1788                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1789                         return;
1790                 
1791                 Notebook n = null;
1792                 int position = 0;
1793                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1794                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1795                                 n = listManager.getNotebookIndex().get(i);
1796                                 position = i;
1797                                 i = listManager.getNotebookIndex().size();
1798                         }
1799                 }
1800                 if (n == null)
1801                         return;
1802                 
1803                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1804                 publish.exec();
1805                 
1806                 if (!publish.okClicked()) 
1807                         return;
1808                 
1809                 Publishing p = publish.getPublishing();
1810                 boolean isPublished = !publish.isStopPressed();
1811                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1812                 n.setPublished(isPublished);
1813                 n.setPublishing(p);
1814                 listManager.getNotebookIndex().set(position, n);
1815                 notebookIndexUpdated();
1816         }
1817         // Publish a notebook
1818         @SuppressWarnings("unused")
1819         private void shareNotebook() {
1820                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1821                 QTreeWidgetItem currentSelection;
1822                 currentSelection = selections.get(0);
1823                 String guid = currentSelection.text(2);
1824
1825                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1826                         return;
1827                 
1828                 Notebook n = null;;
1829                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1830                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1831                                 n = listManager.getNotebookIndex().get(i);
1832                                 i = listManager.getNotebookIndex().size();
1833                         }
1834                 }
1835                                 
1836                 String authToken = null;
1837                 if (syncRunner.isConnected)
1838                         authToken = syncRunner.authToken;
1839                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1840                 share.exec();
1841                 
1842         }
1843
1844         // Delete an existing notebook
1845         @SuppressWarnings("unused")
1846         private void deleteNotebook() {
1847                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1848                 boolean stacksFound = false;
1849                 boolean notebooksFound = false;
1850                 boolean assigned = false;
1851                 // Check if any notes have this notebook
1852                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1853         for (int i=0; i<selections.size(); i++) {
1854                 QTreeWidgetItem currentSelection;
1855                 currentSelection = selections.get(i);
1856                 String guid = currentSelection.text(2);
1857                 if (!guid.equalsIgnoreCase("STACK")) {
1858                         notebooksFound = true;
1859                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1860                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1861                                 if (noteGuid.equals(guid)) {
1862                                         assigned = true;
1863                                         j=listManager.getNoteIndex().size();
1864                                         i=selections.size();
1865                                 }
1866                         }
1867                 } else {
1868                         stacksFound = true;
1869                 }
1870         }
1871                 if (assigned) {
1872                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1873                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1874                         return;
1875                 }
1876                 
1877                 if (conn.getNotebookTable().getAll().size() == 1) {
1878                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1879                         return;
1880                 }
1881         
1882         // If all notebooks are clear, verify the delete
1883                 String msg1 = new String(tr("Delete selected notebooks?"));
1884                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1885                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1886                                 " not deleted unless selected?"));
1887                 String msg = "";
1888                 if (stacksFound && notebooksFound)
1889                         msg = msg3;
1890                 if (!stacksFound && notebooksFound)
1891                         msg = msg1;
1892                 if (stacksFound && !notebooksFound)
1893                         msg = msg2;
1894                 if (QMessageBox.question(this, tr("Confirmation"), msg,
1895                         QMessageBox.StandardButton.Yes, 
1896                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1897                         return;
1898                 }
1899                 
1900                 // If confirmed, delete the notebook
1901         for (int i=selections.size()-1; i>=0; i--) {
1902                 QTreeWidgetItem currentSelection;
1903                 currentSelection = selections.get(i);
1904                 String guid = currentSelection.text(2);
1905                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1906                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1907                         listManager.renameStack(currentSelection.text(0), "");
1908                 } else {
1909                         conn.getNotebookTable().expungeNotebook(guid, true);
1910                         listManager.deleteNotebook(guid);
1911                 }
1912         }
1913
1914                 notebookIndexUpdated();
1915 //        notebookTreeSelection();
1916 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1917 //        listManager.countNotebookResults(listManager.getNoteIndex());
1918         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1919         }
1920         // A note's notebook has been updated
1921         @SuppressWarnings("unused")
1922         private void updateNoteNotebook(String guid, String notebookGuid) {
1923                 
1924                 // Update the list manager
1925                 listManager.updateNoteNotebook(guid, notebookGuid);
1926                 listManager.countNotebookResults(listManager.getNoteIndex());
1927 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1928                 
1929                 // Find the name of the notebook
1930                 String notebookName = null;
1931                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1932                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1933                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1934                                 break;
1935                         }
1936                 }
1937                 
1938                 // If we found the name, update the browser window
1939                 if (notebookName != null) {
1940                         updateListNoteNotebook(guid, notebookName);
1941                         if (guid.equals(currentNoteGuid)) {
1942                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1943                                 if (pos >=0)
1944                                         browserWindow.notebookBox.setCurrentIndex(pos);
1945                         }
1946                 }
1947                 
1948                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1949                 if (guid.equals(currentNoteGuid)) {
1950                         if (currentNote != null) {
1951                                 currentNote.setNotebookGuid(notebookGuid);
1952                         }
1953                 }
1954         }
1955         // Open/close notebooks
1956         @SuppressWarnings("unused")
1957         private void closeNotebooks() {
1958                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1959                 na.exec();
1960                 if (!na.okClicked())
1961                         return;
1962                 
1963                 waitCursor(true);
1964                 listManager.getArchiveNotebookIndex().clear();
1965                 
1966                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1967                         String text = na.getClosedBookList().takeItem(i).text();
1968                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1969                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1970                                         Notebook n = listManager.getNotebookIndex().get(j);
1971                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1972                                         listManager.getArchiveNotebookIndex().add(n);
1973                                         j=listManager.getNotebookIndex().size();
1974                                 }
1975                         }
1976                 }
1977                 
1978                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1979                         String text = na.getOpenBookList().takeItem(i).text();
1980                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1981                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1982                                         Notebook n = listManager.getNotebookIndex().get(j);
1983                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1984                                         j=listManager.getNotebookIndex().size();
1985                                 }
1986                         }
1987                 }
1988                 notebookTreeSelection();
1989                 listManager.loadNotesIndex();
1990                 notebookIndexUpdated();
1991                 noteIndexUpdated(false);
1992                 reloadTagTree(true);
1993 //              noteIndexUpdated(false);
1994                 
1995                 // Build a list of non-closed notebooks
1996                 List<Notebook> nbooks = new ArrayList<Notebook>();
1997                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1998                         boolean found=false;
1999                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
2000                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
2001                                         found = true;
2002                         }
2003                         if (!found)
2004                                 nbooks.add(listManager.getNotebookIndex().get(i));
2005                 }
2006                 
2007                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
2008                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
2009                 browserWindow.setNotebookList(filteredBooks);
2010                 
2011                 // Update any external windows
2012                 Iterator<String> set = externalWindows.keySet().iterator();
2013                 while(set.hasNext())
2014                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
2015                 
2016                 waitCursor(false);
2017         }
2018         // Change the notebook's icon
2019         @SuppressWarnings("unused")
2020         private void setNotebookIcon() {
2021                 boolean stackSelected = false;
2022                 boolean allNotebookSelected = false;
2023                 
2024                 QTreeWidgetItem currentSelection;
2025                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
2026                 if (selections.size() == 0)
2027                         return;
2028                 
2029                 currentSelection = selections.get(0);   
2030                 String guid = currentSelection.text(2);
2031                 if (guid.equalsIgnoreCase(""))
2032                         allNotebookSelected = true;
2033                 if (guid.equalsIgnoreCase("STACK"))
2034                         stackSelected = true;
2035
2036                 QIcon currentIcon = currentSelection.icon(0);
2037                 QIcon icon;
2038                 SetIcon dialog;
2039                 
2040                 if (!stackSelected && !allNotebookSelected) {
2041                         icon = conn.getNotebookTable().getIcon(guid);
2042                         if (icon == null) {
2043                                 dialog = new SetIcon(currentIcon, saveLastPath);
2044                                 dialog.setUseDefaultIcon(true);
2045                         } else {
2046                                 dialog = new SetIcon(icon, saveLastPath);
2047                                 dialog.setUseDefaultIcon(false);
2048                         }
2049                 } else {
2050                         if (stackSelected) {
2051                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
2052                         } else {
2053                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
2054                         }
2055                         if (icon == null) {
2056                                 dialog = new SetIcon(currentIcon, saveLastPath);
2057                                 dialog.setUseDefaultIcon(true);
2058                         } else {
2059                                 dialog = new SetIcon(icon, saveLastPath);
2060                                 dialog.setUseDefaultIcon(false);
2061                         }
2062                 }
2063                 dialog.exec();
2064                 if (dialog.okPressed()) {
2065                 saveLastPath = dialog.getPath();
2066
2067                         QIcon newIcon = dialog.getIcon();
2068                         if (stackSelected) {
2069                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
2070                                 if (newIcon == null) {
2071                                         newIcon = new QIcon(iconPath+"books2.png");
2072                                 }
2073                                 currentSelection.setIcon(0,newIcon);
2074                                 return;
2075                         }
2076                         if (allNotebookSelected) {
2077                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
2078                                 if (newIcon == null) {
2079                                         newIcon = new QIcon(iconPath+"notebook-green.png");
2080                                 }
2081                                 currentSelection.setIcon(0,newIcon);
2082                                 return;
2083                         }
2084                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2085                         if (newIcon == null) {
2086                                 boolean isPublished = false;;
2087                                 boolean found = false;
2088                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2089                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2090                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2091                                                 found = true;
2092                                         }
2093                                 }
2094                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2095                         }
2096                         currentSelection.setIcon(0, newIcon);
2097                 }
2098         
2099         }
2100         
2101         
2102     //***************************************************************
2103     //***************************************************************
2104     //** These functions deal with Tag menu items
2105     //***************************************************************
2106     //***************************************************************
2107         // Add a new notebook
2108         @SuppressWarnings("unused")
2109         private void addTag() {
2110                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2111                 TagEdit edit = new TagEdit();
2112                 edit.setTagList(listManager.getTagIndex());
2113
2114                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2115                 QTreeWidgetItem currentSelection = null;
2116                 if (selections.size() > 0) {
2117                         currentSelection = selections.get(0);
2118                         edit.setParentTag(currentSelection.text(0));
2119                 }
2120
2121                 edit.exec();
2122         
2123                 if (!edit.okPressed())
2124                         return;
2125         
2126                 Calendar currentTime = new GregorianCalendar();
2127                 Long l = new Long(currentTime.getTimeInMillis());
2128                 String randint = new String(Long.toString(l));
2129         
2130                 Tag newTag = new Tag();
2131                 newTag.setUpdateSequenceNum(0);
2132                 newTag.setGuid(randint);
2133                 newTag.setName(edit.getTag());
2134                 if (edit.getParentTag().isChecked()) {
2135                         newTag.setParentGuid(currentSelection.text(2));
2136                         newTag.setParentGuidIsSet(true);
2137                         currentSelection.setExpanded(true);
2138                 }
2139                 conn.getTagTable().addTag(newTag, true);
2140                 listManager.getTagIndex().add(newTag);
2141                 reloadTagTree(true);
2142                 
2143                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2144         }
2145         @SuppressWarnings("unused")
2146         private void reloadTagTree() {
2147                 reloadTagTree(false);
2148         }
2149         private void reloadTagTree(boolean reload) {
2150                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2151                 tagIndexUpdated(reload);
2152                 boolean filter = false;
2153                 if (reload)
2154                         listManager.countTagResults(listManager.getNoteIndex());
2155                 if (notebookTree.selectedItems().size() > 0 
2156                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2157                                                   filter = true;
2158                 if (tagTree.selectedItems().size() > 0)
2159                         filter = true;
2160                 tagTree.showAllTags(!filter);
2161                 tagIndexUpdated(false);
2162                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2163         }
2164         // Edit an existing tag
2165         @SuppressWarnings("unused")
2166         private void editTag() {
2167                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2168                 TagEdit edit = new TagEdit();
2169                 edit.setTitle("Edit Tag");
2170                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2171                 QTreeWidgetItem currentSelection;
2172                 currentSelection = selections.get(0);
2173                 edit.setTag(currentSelection.text(0));
2174                 edit.setTagList(listManager.getTagIndex());
2175                 edit.exec();
2176         
2177                 if (!edit.okPressed())
2178                         return;
2179         
2180                 String guid = currentSelection.text(2);
2181                 currentSelection.setText(0,edit.getTag());
2182                 
2183                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2184                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2185                                 listManager.getTagIndex().get(i).setName(edit.getTag());
2186                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2187                                 updateListTagName(guid);
2188                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2189                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2190                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2191                                 //return;
2192                         }
2193                 }
2194                 listManager.reloadNoteTagNames(guid, edit.getTag());
2195                 noteIndexUpdated(true);
2196                 refreshEvernoteNote(true);
2197                 browserWindow.setTag(getTagNamesForNote(currentNote));
2198                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2199         }
2200         // Delete an existing tag
2201         @SuppressWarnings("unused")
2202         private void deleteTag() {
2203                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2204                 
2205                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2206                         QMessageBox.StandardButton.Yes, 
2207                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2208                                                         return;
2209                 }
2210                 
2211                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2212         for (int i=selections.size()-1; i>=0; i--) {
2213                 QTreeWidgetItem currentSelection;
2214                 currentSelection = selections.get(i);                   
2215                 removeTagItem(currentSelection.text(2));
2216         }
2217         tagIndexUpdated(true);
2218         tagTreeSelection();
2219         listManager.countTagResults(listManager.getNoteIndex());
2220 //              tagTree.updateCounts(listManager.getTagCounter());
2221         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2222         }
2223         // Remove a tag tree item.  Go recursively down & remove the children too
2224         private void removeTagItem(String guid) {
2225         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2226                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2227                 if (parent != null && parent.equals(guid)) {            
2228                         //Remove this tag's children
2229                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2230                 }
2231         }
2232         //Now, remove this tag
2233         removeListTagName(guid);
2234         conn.getTagTable().expungeTag(guid, true);                      
2235         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2236                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2237                         listManager.getTagIndex().remove(a);
2238                         return;
2239                 }
2240         }
2241         }
2242         // Setup the tree containing the user's tags
2243     private void initializeTagTree() {
2244         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2245 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2246 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2247         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2248         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2249         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2250     }
2251     // Listener when a tag is selected
2252         private void tagTreeSelection() {
2253         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2254                 
2255         clearTrashFilter();
2256         clearAttributeFilter();
2257         clearSavedSearchFilter();
2258         
2259                 menuBar.noteRestoreAction.setVisible(false);
2260                 
2261         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2262         QTreeWidgetItem currentSelection;
2263         selectedTagGUIDs.clear();
2264         for (int i=0; i<selections.size(); i++) {
2265                 currentSelection = selections.get(i);
2266                 selectedTagGUIDs.add(currentSelection.text(2));
2267         }
2268         if (selections.size() > 0) {
2269                 menuBar.tagEditAction.setEnabled(true);
2270                 menuBar.tagDeleteAction.setEnabled(true);
2271                 menuBar.tagIconAction.setEnabled(true);
2272         }
2273         else {
2274                 menuBar.tagEditAction.setEnabled(false);
2275                 menuBar.tagDeleteAction.setEnabled(false);
2276                 menuBar.tagIconAction.setEnabled(true);
2277         }
2278         if (selections.size() > 1)
2279                 menuBar.tagMergeAction.setEnabled(true);
2280         else
2281                 menuBar.tagMergeAction.setEnabled(false);
2282         listManager.setSelectedTags(selectedTagGUIDs);
2283         listManager.loadNotesIndex();
2284         noteIndexUpdated(false);
2285         refreshEvernoteNote(true);
2286         listManager.refreshCounters = true;
2287         listManager.refreshCounters();
2288         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2289     }
2290     // trigger the tag index to be refreshed
2291     @SuppressWarnings("unused")
2292         private void tagIndexUpdated() {
2293         tagIndexUpdated(true);
2294     }
2295     private void tagIndexUpdated(boolean reload) {
2296         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2297                 if (selectedTagGUIDs == null)
2298                         selectedTagGUIDs = new ArrayList<String>();
2299                 if (reload)
2300                         listManager.reloadTagIndex();
2301
2302                 tagTree.blockSignals(true);
2303                 if (reload) {
2304                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2305                         tagTree.load(listManager.getTagIndex());
2306                 }
2307
2308         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2309                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2310                 if (!found)
2311                         selectedTagGUIDs.remove(i);
2312         }
2313         tagTree.blockSignals(false);
2314         
2315                 browserWindow.setTag(getTagNamesForNote(currentNote));
2316         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2317     }   
2318     // Show/Hide note information
2319         @SuppressWarnings("unused")
2320         private void toggleTagWindow() {
2321                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2322         if (tagTree.isVisible())
2323                 tagTree.hide();
2324         else
2325                 tagTree.show();
2326         menuBar.hideTags.setChecked(tagTree.isVisible());
2327         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2328         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2329     }   
2330         // A note's tags have been updated
2331         @SuppressWarnings("unused")
2332         private void updateNoteTags(String guid, List<String> tags) {
2333                 // Save any new tags.  We'll need them later.
2334                 List<String> newTags = new ArrayList<String>();
2335                 for (int i=0; i<tags.size(); i++) {
2336                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2337                                 newTags.add(tags.get(i));
2338                 }
2339                 
2340                 listManager.saveNoteTags(guid, tags);
2341                 listManager.countTagResults(listManager.getNoteIndex());
2342                 StringBuffer names = new StringBuffer("");
2343                 for (int i=0; i<tags.size(); i++) {
2344                         names = names.append(tags.get(i));
2345                         if (i<tags.size()-1) {
2346                                 names.append(Global.tagDelimeter + " ");
2347                         }
2348                 }
2349                 browserWindow.setTag(names.toString());
2350                 noteDirty = true;
2351                 
2352                 // Now, we need to add any new tags to the tag tree
2353                 for (int i=0; i<newTags.size(); i++) 
2354                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2355         }
2356         // Get a string containing all tag names for a note
2357         private String getTagNamesForNote(Note n) {
2358                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2359                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2360                         return "";
2361                 StringBuffer buffer = new StringBuffer(100);
2362                 Vector<String> v = new Vector<String>();
2363                 List<String> guids = n.getTagGuids();
2364                 
2365                 if (guids == null) 
2366                         return "";
2367                 
2368                 for (int i=0; i<guids.size(); i++) {
2369                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2370                 }
2371                 Comparator<String> comparator = Collections.reverseOrder();
2372                 Collections.sort(v,comparator);
2373                 Collections.reverse(v);
2374                 
2375                 for (int i = 0; i<v.size(); i++) {
2376                         if (i>0) 
2377                                 buffer.append(", ");
2378                         buffer.append(v.get(i));
2379                 }
2380                 
2381                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2382                 return buffer.toString();
2383         }       
2384         // Tags were added via dropping notes from the note list
2385         @SuppressWarnings("unused")
2386         private void tagsAdded(String noteGuid, String tagGuid) {
2387                 String tagName = null;
2388                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2389                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2390                                 tagName = listManager.getTagIndex().get(i).getName();
2391                                 i=listManager.getTagIndex().size();
2392                         }
2393                 }
2394                 if (tagName == null)
2395                         return;
2396                 
2397                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2398                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2399                                 List<String> tagNames = new ArrayList<String>();
2400                                 tagNames.add(new String(tagName));
2401                                 Note n = listManager.getMasterNoteIndex().get(i);
2402                                 for (int j=0; j<n.getTagNames().size(); j++) {
2403                                         tagNames.add(new String(n.getTagNames().get(j)));
2404                                 }
2405                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2406                                 if (n.getGuid().equals(currentNoteGuid)) {
2407                                         Collections.sort(tagNames);
2408                                         String display = "";
2409                                         for (int j=0; j<tagNames.size(); j++) {
2410                                                 display = display+tagNames.get(j);
2411                                                 if (j+2<tagNames.size()) 
2412                                                         display = display+Global.tagDelimeter+" ";
2413                                         }
2414                                         browserWindow.setTag(display);
2415                                 }
2416                                 i=listManager.getMasterNoteIndex().size();
2417                         }
2418                 }
2419                 
2420                 
2421                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2422         }
2423         private void clearTagFilter() {
2424                 tagTree.blockSignals(true);
2425                 tagTree.clearSelection();
2426                 menuBar.noteRestoreAction.setVisible(false);
2427                 menuBar.tagEditAction.setEnabled(false);
2428                 menuBar.tagMergeAction.setEnabled(false);
2429                 menuBar.tagDeleteAction.setEnabled(false);
2430                 menuBar.tagIconAction.setEnabled(false);
2431                 selectedTagGUIDs.clear();
2432         listManager.setSelectedTags(selectedTagGUIDs);
2433         tagTree.blockSignals(false);
2434         }
2435         // Change the icon for a tag
2436         @SuppressWarnings("unused")
2437         private void setTagIcon() {
2438                 QTreeWidgetItem currentSelection;
2439                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2440                 if (selections.size() == 0)
2441                         return;
2442                 
2443                 currentSelection = selections.get(0);   
2444                 String guid = currentSelection.text(2);
2445
2446                 QIcon currentIcon = currentSelection.icon(0);
2447                 QIcon icon = conn.getTagTable().getIcon(guid);
2448                 SetIcon dialog;
2449                 if (icon == null) {
2450                         dialog = new SetIcon(currentIcon, saveLastPath);
2451                         dialog.setUseDefaultIcon(true);
2452                 } else {
2453                         dialog = new SetIcon(icon, saveLastPath);
2454                         dialog.setUseDefaultIcon(false);
2455                 }
2456                 dialog.exec();
2457                 if (dialog.okPressed()) {
2458                 saveLastPath = dialog.getPath();
2459                         QIcon newIcon = dialog.getIcon();
2460                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2461                         if (newIcon == null) 
2462                                 newIcon = new QIcon(iconPath+"tag.png");
2463                         currentSelection.setIcon(0, newIcon);
2464                 }
2465         
2466         }
2467         // Merge tags
2468         @SuppressWarnings("unused")
2469         private void mergeTags() {
2470                 List<Tag> tags = new ArrayList<Tag>();
2471                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2472                 for (int i=0; i<selections.size(); i++) {
2473                         Tag record = new Tag();
2474                         record.setGuid(selections.get(i).text(2));
2475                         record.setName(selections.get(i).text(0));
2476                         tags.add(record);
2477                 }
2478
2479                 TagMerge mergeDialog = new TagMerge(tags);
2480                 mergeDialog.exec();
2481                 if (!mergeDialog.okClicked())
2482                         return;
2483                 String newGuid = mergeDialog.getNewTagGuid();
2484                 
2485                 for (int i=0; i<tags.size(); i++) {
2486                         if (!tags.get(i).getGuid().equals(newGuid)) {
2487                                 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2488                                 for (int j=0; j<noteGuids.size(); j++) {
2489                                         String noteGuid = noteGuids.get(j);
2490                                         conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2491                                         if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2492                                                 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2493                                 }
2494                         }
2495                 }
2496                 listManager.reloadIndexes();
2497         }
2498         
2499     //***************************************************************
2500     //***************************************************************
2501     //** These functions deal with Saved Search menu items
2502     //***************************************************************
2503     //***************************************************************
2504         // Add a new notebook
2505         @SuppressWarnings("unused")
2506         private void addSavedSearch() {
2507                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2508                 SavedSearchEdit edit = new SavedSearchEdit();
2509                 edit.setSearchList(listManager.getSavedSearchIndex());
2510                 edit.exec();
2511         
2512                 if (!edit.okPressed())
2513                         return;
2514         
2515                 Calendar currentTime = new GregorianCalendar();         
2516                 Long l = new Long(currentTime.getTimeInMillis());
2517                 String randint = new String(Long.toString(l));
2518         
2519                 SavedSearch search = new SavedSearch();
2520                 search.setUpdateSequenceNum(0);
2521                 search.setGuid(randint);
2522                 search.setName(edit.getName());
2523                 search.setQuery(edit.getQuery());
2524                 search.setFormat(QueryFormat.USER);
2525                 listManager.getSavedSearchIndex().add(search);
2526                 conn.getSavedSearchTable().addSavedSearch(search, true);
2527                 savedSearchIndexUpdated();
2528                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2529         }
2530         // Edit an existing tag
2531         @SuppressWarnings("unused")
2532         private void editSavedSearch() {
2533                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2534                 SavedSearchEdit edit = new SavedSearchEdit();
2535                 edit.setTitle(tr("Edit Search"));
2536                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2537                 QTreeWidgetItem currentSelection;
2538                 currentSelection = selections.get(0);
2539                 String guid = currentSelection.text(1);
2540                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2541                 edit.setName(currentSelection.text(0));
2542                 edit.setQuery(s.getQuery());
2543                 edit.setSearchList(listManager.getSavedSearchIndex());
2544                 edit.exec();
2545         
2546                 if (!edit.okPressed())
2547                         return;
2548         
2549                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2550                 SavedSearch search = null;
2551                 boolean found = false;
2552                 for (int i=0; i<list.size(); i++) {
2553                         search = list.get(i);
2554                         if (search.getGuid().equals(guid)) {
2555                                 i=list.size();
2556                                 found = true;
2557                         }
2558                 }
2559                 if (!found)
2560                         return;
2561                 search.setName(edit.getName());
2562                 search.setQuery(edit.getQuery());
2563                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2564                 savedSearchIndexUpdated();
2565                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2566         }
2567         // Delete an existing tag
2568         @SuppressWarnings("unused")
2569         private void deleteSavedSearch() {
2570                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2571                 
2572                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2573                         QMessageBox.StandardButton.Yes, 
2574                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2575                                                         return;
2576                 }
2577                 
2578                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2579         for (int i=selections.size()-1; i>=0; i--) {
2580                 QTreeWidgetItem currentSelection;
2581                 currentSelection = selections.get(i);
2582                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2583                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2584                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2585                                 listManager.getSavedSearchIndex().remove(j);
2586                                 j=listManager.getSavedSearchIndex().size()+1;
2587                         }
2588                 }
2589                 selections.remove(i);
2590         }
2591         savedSearchIndexUpdated();
2592         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2593         }
2594     // Setup the tree containing the user's tags
2595     private void initializeSavedSearchTree() {
2596         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2597         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2598         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2599     }
2600     // Listener when a tag is selected
2601     @SuppressWarnings("unused")
2602         private void savedSearchTreeSelection() {
2603         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2604
2605         clearNotebookFilter();
2606         clearTagFilter();
2607         clearTrashFilter();
2608         clearAttributeFilter();
2609         
2610         String currentGuid = selectedSavedSearchGUID;
2611         menuBar.savedSearchEditAction.setEnabled(true);
2612         menuBar.savedSearchDeleteAction.setEnabled(true);
2613         menuBar.savedSearchIconAction.setEnabled(true);
2614         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2615         QTreeWidgetItem currentSelection;
2616         selectedSavedSearchGUID = "";
2617         for (int i=0; i<selections.size(); i++) {
2618                 currentSelection = selections.get(i);
2619                 if (currentSelection.text(1).equals(currentGuid)) {
2620                         currentSelection.setSelected(false);
2621                 } else {
2622                         selectedSavedSearchGUID = currentSelection.text(1);
2623                 }
2624 //              i = selections.size() +1;
2625         }
2626         
2627         // There is the potential for no notebooks to be selected if this 
2628         // happens then we make it look like all notebooks were selecetd.
2629         // If that happens, just select the "all notebooks"
2630         if (selections.size()==0) {
2631                 clearSavedSearchFilter();
2632         }
2633         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2634         
2635         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2636     }
2637     private void clearSavedSearchFilter() {
2638         menuBar.savedSearchEditAction.setEnabled(false);
2639         menuBar.savedSearchDeleteAction.setEnabled(false);
2640         menuBar.savedSearchIconAction.setEnabled(false);
2641         savedSearchTree.blockSignals(true);
2642         savedSearchTree.clearSelection();
2643         savedSearchTree.blockSignals(false);
2644         selectedSavedSearchGUID = "";
2645         searchField.setEditText("");
2646         searchPerformed = false;
2647         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2648     }
2649     // trigger the tag index to be refreshed
2650         private void savedSearchIndexUpdated() { 
2651                 if (selectedSavedSearchGUID == null)
2652                         selectedSavedSearchGUID = new String();
2653                 savedSearchTree.blockSignals(true);
2654                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2655         savedSearchTree.load(listManager.getSavedSearchIndex());
2656         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2657         savedSearchTree.blockSignals(false);
2658     }
2659     // trigger when the saved search selection changes
2660     @SuppressWarnings("unused")
2661         private void updateSavedSearchSelection() {
2662                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2663                 
2664         menuBar.savedSearchEditAction.setEnabled(true);
2665         menuBar.savedSearchDeleteAction.setEnabled(true);
2666         menuBar.savedSearchIconAction.setEnabled(true);
2667         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2668
2669         if (selections.size() > 0) {
2670                 menuBar.savedSearchEditAction.setEnabled(true);
2671                 menuBar.savedSearchDeleteAction.setEnabled(true);
2672                 menuBar.savedSearchIconAction.setEnabled(true);
2673                 selectedSavedSearchGUID = selections.get(0).text(1);
2674                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2675                 searchField.setEditText(s.getQuery());
2676         } else { 
2677                 menuBar.savedSearchEditAction.setEnabled(false);
2678                 menuBar.savedSearchDeleteAction.setEnabled(false);
2679                 menuBar.savedSearchIconAction.setEnabled(false);
2680                 selectedSavedSearchGUID = "";
2681                 searchField.setEditText("");
2682         }
2683         searchFieldChanged();
2684         
2685                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2686
2687         
2688     }
2689     // Show/Hide note information
2690         @SuppressWarnings("unused")
2691         private void toggleSavedSearchWindow() {
2692                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2693         if (savedSearchTree.isVisible())
2694                 savedSearchTree.hide();
2695         else
2696                 savedSearchTree.show();
2697         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2698                                 
2699                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2700         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2701     }
2702         // Change the icon for a saved search
2703         @SuppressWarnings("unused")
2704         private void setSavedSearchIcon() {
2705                 QTreeWidgetItem currentSelection;
2706                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2707                 if (selections.size() == 0)
2708                         return;
2709                 
2710                 currentSelection = selections.get(0);   
2711                 String guid = currentSelection.text(1);
2712
2713                 QIcon currentIcon = currentSelection.icon(0);
2714                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2715                 SetIcon dialog;
2716                 if (icon == null) {
2717                         dialog = new SetIcon(currentIcon, saveLastPath);
2718                         dialog.setUseDefaultIcon(true);
2719                 } else {
2720                         dialog = new SetIcon(icon, saveLastPath);
2721                         dialog.setUseDefaultIcon(false);
2722                 }
2723                 dialog.exec();
2724                 if (dialog.okPressed()) {
2725                 saveLastPath = dialog.getPath();
2726                         QIcon newIcon = dialog.getIcon();
2727                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2728                         if (newIcon == null) 
2729                                 newIcon = new QIcon(iconPath+"search.png");
2730                         currentSelection.setIcon(0, newIcon);
2731                 }
2732         
2733         }
2734         
2735         
2736         
2737         
2738     //***************************************************************
2739     //***************************************************************
2740     //** These functions deal with Help menu & tool menu items
2741     //***************************************************************
2742     //***************************************************************
2743         // Show database status
2744         @SuppressWarnings("unused")
2745         private void databaseStatus() {
2746                 waitCursor(true);
2747                 indexRunner.interrupt = true;
2748                 int dirty = conn.getNoteTable().getDirtyCount();
2749                 int unindexed = conn.getNoteTable().getUnindexedCount();
2750                 DatabaseStatus status = new DatabaseStatus();
2751                 status.setUnsynchronized(dirty);
2752                 status.setUnindexed(unindexed);
2753                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2754                 status.setNotebookCount(listManager.getNotebookIndex().size());
2755                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2756                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2757                 status.setTagCount(listManager.getTagIndex().size());
2758                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2759                 status.setWordCount(conn.getWordsTable().getWordCount());
2760                 waitCursor(false);
2761                 status.exec();
2762         }
2763         // Compact the database
2764         @SuppressWarnings("unused")
2765         private void compactDatabase() {
2766         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2767                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2768                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2769                                 "and NixNote will be unresponsive until it is complete.  Do you wish to continue?"),
2770                                 QMessageBox.StandardButton.Yes, 
2771                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2772                                                         return;
2773                 }
2774                 setMessage("Compacting database.");
2775                 waitCursor(true);
2776                 listManager.compactDatabase();
2777                 waitCursor(false);
2778                 setMessage("Database compact is complete.");            
2779         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2780     }
2781         @SuppressWarnings("unused")
2782         private void accountInformation() {
2783                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2784                 AccountDialog dialog = new AccountDialog();
2785                 dialog.show();
2786                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2787         }
2788         @SuppressWarnings("unused")
2789         private void releaseNotes() {
2790                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2791                 QDialog dialog = new QDialog(this);
2792                 QHBoxLayout layout = new QHBoxLayout();
2793                 QTextEdit textBox = new QTextEdit();
2794                 layout.addWidget(textBox);
2795                 textBox.setReadOnly(true);
2796                 QFile file = new QFile(Global.getFileManager().getProgramDirPath("release.txt"));
2797                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2798                 QIODevice.OpenModeFlag.Text)))
2799                         return;
2800                 textBox.setText(file.readAll().toString());
2801                 file.close();
2802                 dialog.setWindowTitle(tr("Release Notes"));
2803                 dialog.setLayout(layout);
2804                 dialog.show();
2805                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2806         }
2807         // Called when user picks Log from the help menu
2808         @SuppressWarnings("unused")
2809         private void logger() {
2810                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2811                 LogFileDialog dialog = new LogFileDialog(emitLog);
2812                 dialog.exec();
2813                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2814         }
2815         // Menu option "help/about" was selected
2816         @SuppressWarnings("unused")
2817         private void about() {
2818                 logger.log(logger.HIGH, "Entering NeverNote.about");
2819                 QMessageBox.about(this, 
2820                                                 tr("About NixNote"),
2821                                                 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2822                                                 +Global.version
2823                                                 //+"1.2.120724"
2824                                                 +tr("<hr>"
2825                                                                 +"Open Source Evernote Client.<br><br>" 
2826                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2827                                                                 +"</center>Evernote is copyright 2001-2012 by Evernote Corporation<br>"
2828                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2829                                                                 +"PDFRenderer is licened under the LGPL<br>"
2830                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2831                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2832                                                                 +"Jazzy is licened under the LGPL<br>"
2833                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2834                                                                 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2835                                                                 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2836                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2837         }
2838         // Hide the entire left hand side
2839         @SuppressWarnings("unused")
2840         private void toggleLeftSide() {
2841                 boolean hidden;
2842                 
2843                 hidden = !menuBar.hideLeftSide.isChecked();
2844                 menuBar.hideLeftSide.setChecked(!hidden);
2845                 
2846                 if (!hidden) 
2847                         leftSplitter1.setHidden(true);
2848                 else
2849                         leftSplitter1.setHidden(false);
2850                 
2851                 Global.saveWindowVisible("leftPanel", hidden);
2852                 
2853         }
2854         public void checkForUpdates() {
2855                 // Send off thread to check for a new version
2856                 versionChecker = new QNetworkAccessManager(this);
2857                 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2858                 QNetworkRequest request = new QNetworkRequest();
2859                 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2860                 versionChecker.get(request);
2861         }
2862         @SuppressWarnings("unused")
2863         private void upgradeFileRead(QNetworkReply reply) {
2864                 if (!reply.isReadable())
2865                         return;
2866                 
2867                 String winVersion = Global.version;
2868                 String osxVersion = Global.version;
2869                 String linuxVersion = Global.version;
2870                 String linux64Version = Global.version;
2871                 String version = Global.version;
2872                 
2873                 // Determine the versions available
2874                 QByteArray data = reply.readLine();
2875                 while (data != null && !reply.atEnd()) {
2876                         String line = data.toString();
2877                         String lineVersion;
2878                         if (line.contains(":")) 
2879                                 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2880                         else
2881                                 lineVersion = "";
2882                         if (line.toLowerCase().contains("windows")) 
2883                                 winVersion = lineVersion;
2884                         else if (line.toLowerCase().contains("os-x")) 
2885                                 osxVersion = lineVersion;
2886                         else if (line.toLowerCase().contains("linux amd64")) 
2887                                 linux64Version = lineVersion;
2888                         else if (line.toLowerCase().contains("linux i386")) 
2889                                 linuxVersion = lineVersion;
2890                         else if (line.toLowerCase().contains("default")) 
2891                                 version = lineVersion;
2892                         
2893                         // Read the next line
2894                         data = reply.readLine();
2895                 }
2896                 
2897                 // Now we need to determine what system we are on.
2898                 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2899                         version = winVersion;
2900                 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2901                         version = osxVersion;
2902                 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2903                         if (System.getProperty("os.arch").contains("amd64") ||
2904                                 System.getProperty("os.arch").contains("x86_64"))
2905                                         version = linux64Version;
2906                         else
2907                                 version = linuxVersion;
2908                 }
2909                 
2910                 
2911                 for (String validVersion : Global.validVersions) {
2912                         if (version.equals(validVersion))
2913                                 return;
2914                 }
2915                 
2916                 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2917                 dialog.exec();
2918                 if (dialog.remindMe())
2919                         Global.setCheckVersionUpgrade(true);
2920                 else
2921                         Global.setCheckVersionUpgrade(false);
2922         }
2923                 
2924         
2925     //***************************************************************
2926     //***************************************************************
2927     //** These functions deal with the Toolbar
2928     //***************************************************************
2929     //*************************************************************** 
2930         @SuppressWarnings("unused")
2931         private void focusSearch() {
2932                 searchField.setFocus();
2933         }
2934
2935         // Text in the search bar has been cleared
2936         private void searchFieldCleared() {
2937                 saveNote();
2938                 
2939                 // This is done because we want to force a reload of
2940                 // images.  Some images we may want to highlight the text.
2941                 readOnlyCache.clear();
2942                 inkNoteCache.clear();
2943                 noteCache.clear();
2944                 QWebSettings.setMaximumPagesInCache(0);
2945                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2946         
2947                 searchField.setEditText("");
2948                 saveNoteColumnPositions();
2949                 saveNoteIndexWidth();
2950                 noteIndexUpdated(true);
2951                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2952                         currentNote = listManager.getNoteIndex().get(0);
2953                         currentNoteGuid = currentNote.getGuid();
2954                 }
2955                 refreshEvernoteNote(true);
2956                 if (currentNote != null)
2957                         loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2958         }
2959         // text in the search bar changed.  We only use this to tell if it was cleared, 
2960         // otherwise we trigger off searchFieldChanged.
2961         @SuppressWarnings("unused")
2962         private void searchFieldTextChanged(String text) {
2963                 QWebSettings.setMaximumPagesInCache(0);
2964                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2965
2966                 if (text.trim().equals("")) {
2967                         searchFieldCleared();
2968                         if (searchPerformed) {
2969
2970                                 // This is done because we want to force a reload of
2971                                 // images.  Some images we may want to highlight the text.
2972                                 noteCache.clear();
2973                                 readOnlyCache.clear();
2974                                 inkNoteCache.clear();
2975                                 
2976                                 listManager.setEnSearch("");
2977                                 listManager.loadNotesIndex();
2978                                 refreshEvernoteNote(true);
2979                                 noteIndexUpdated(false);
2980                                 refreshEvernoteNote(true);
2981                         }
2982                         searchPerformed = false;
2983                 }
2984         }
2985     // Text in the toolbar has changed
2986     private void searchFieldChanged() {
2987         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2988         noteCache.clear();
2989         readOnlyCache.clear();
2990         inkNoteCache.clear();
2991         saveNoteColumnPositions();
2992         saveNoteIndexWidth();
2993         String text = searchField.currentText();
2994         listManager.setEnSearch(text.trim());
2995         listManager.loadNotesIndex();
2996         noteIndexUpdated(false);
2997
2998         refreshEvernoteNote(true);
2999         searchPerformed = true;
3000         waitCursor(false);
3001         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
3002     }
3003
3004     // Build the window tool bar
3005     private void setupToolBar() {
3006         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
3007         toolBar = addToolBar(tr("Tool Bar"));   
3008         toolBar.setObjectName("toolBar");
3009         menuBar.setupToolBarVisible();
3010         if (!Global.isWindowVisible("toolBar"))
3011                 toolBar.setVisible(false);
3012         else
3013                 toolBar.setVisible(true);
3014
3015 //      toolBar.addWidget(menuBar);
3016 //      menuBar.setSizePolicy(Policy.Minimum, Pol