OSDN Git Service

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