OSDN Git Service

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