OSDN Git Service

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