OSDN Git Service

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