OSDN Git Service

Add the ability to customize saved search 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.setIconAction(menuBar.tagIconAction);
509                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
510                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
511                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
512                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
513         
514                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
515                 notebookTree.setEditAction(menuBar.notebookEditAction);
516                 notebookTree.setAddAction(menuBar.notebookAddAction);
517                 notebookTree.setIconAction(menuBar.notebookIconAction);
518                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
519                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
520                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
521
522                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
523                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
524                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
525                 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
526                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
527                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
528                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
529                         
530                 noteTableView.setAddAction(menuBar.noteAdd);
531                 noteTableView.setDeleteAction(menuBar.noteDelete);
532                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
533                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
534                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
535                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
536                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
537                 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
538                 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
539                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
540                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
541                 
542                 quotaBar.setMouseClickAction(menuBar.accountAction);
543                 
544                 trashTree.load();
545         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
546                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
547                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
548                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
549                 trashTree.updateCounts(listManager.getTrashCount());
550                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
551                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
552
553                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
554                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
555                 
556                 if (!Global.isWindowVisible("editorButtonBar"))
557                         toggleEditorButtonBar();
558                 if (!Global.isWindowVisible("leftPanel"))
559                         menuBar.hideLeftSide.setChecked(true);
560                 if (Global.isWindowVisible("noteInformation"))
561                         toggleNoteInformation();
562                 
563                 setMenuBar(menuBar);
564                 setupToolBar();
565                 find = new FindDialog();
566                 find.getOkButton().clicked.connect(this, "doFindText()");
567                 
568                 // Setup the tray icon menu bar
569                 trayShowAction = new QAction("Show/Hide", this);
570                 trayExitAction = new QAction("Exit", this);
571                 trayAddNoteAction = new QAction("Add Note", this);
572                 
573                 trayExitAction.triggered.connect(this, "close()");
574                 trayAddNoteAction.triggered.connect(this, "addNote()");
575                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
576                 
577                 trayMenu = new QMenu(this);
578                 trayMenu.addAction(trayAddNoteAction);
579                 trayMenu.addAction(trayShowAction);
580                 trayMenu.addAction(trayExitAction);
581                 
582                 
583                 trayIcon = new QSystemTrayIcon(this);
584                 trayIcon.setToolTip("NeverNote");
585                 trayIcon.setContextMenu(trayMenu);
586                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
587
588                 currentNoteGuid="";
589                 currentNoteGuid = Global.getLastViewedNoteGuid();
590         historyGuids = new ArrayList<String>();
591         historyPosition = 0;
592         fromHistory = false;
593                 noteDirty = false;
594                 if (!currentNoteGuid.trim().equals("")) {
595                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
596                 }
597                 
598                 noteIndexUpdated(true);
599                 showColumns();
600                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
601                 if (menuBar.showEditorBar.isChecked())
602                 showEditorButtons(browserWindow);
603                 tagIndexUpdated(true);
604                 savedSearchIndexUpdated();
605                 notebookIndexUpdated();
606                 updateQuotaBar();
607         setupSyncSignalListeners();        
608         setupBrowserSignalListeners();
609         setupIndexListeners();
610               
611         
612         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
613         tagTree.showAllTags(true);
614
615                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
616         setWindowIcon(appIcon);
617         trayIcon.setIcon(appIcon);
618         if (Global.showTrayIcon())
619                 trayIcon.show();
620         else
621                 trayIcon.hide();
622         
623         scrollToGuid(currentNoteGuid);
624         if (Global.automaticLogin()) {
625                 remoteConnect();
626                 if (Global.isConnected)
627                         syncTimer();
628         }
629         setupFolderImports();
630         
631         loadStyleSheet();
632         restoreWindowState(true);
633         
634         if (Global.mimicEvernoteInterface) {
635                 notebookTree.selectGuid("");
636         }
637         
638         threadMonitorTimer = new QTimer();
639         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
640         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
641         
642         historyGuids.add(currentNoteGuid);
643         historyPosition = 1;
644         
645         if (Global.getListView() == Global.View_List_Narrow) { 
646                 menuBar.narrowListView.setChecked(true);
647 //              narrowListView();
648         }
649         else{ 
650                 menuBar.wideListView.setChecked(true);
651 //              wideListView();
652         }
653
654         if (Global.getListView() == Global.View_List_Wide) {
655                 browserIndexSplitter.addWidget(noteTableView);
656                 browserIndexSplitter.addWidget(browserWindow); 
657         } else {
658                 mainLeftRightSplitter.addWidget(noteTableView);
659                 mainLeftRightSplitter.addWidget(browserWindow); 
660         }
661         
662         int sortCol = Global.getSortColumn();
663                 int sortOrder = Global.getSortOrder();
664                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
665
666         }
667
668         
669         // Main entry point
670         public static void main(String[] args) {
671                 QApplication.initialize(args);
672                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
673                 QSplashScreen splash = new QSplashScreen(pixmap);
674                 boolean showSplash;
675                 
676                 DatabaseConnection dbConn;
677
678         try {
679             initializeGlobalSettings(args);
680
681             showSplash = Global.isWindowVisible("SplashScreen");
682             if (showSplash)
683                 splash.show();
684
685             dbConn = setupDatabaseConnection();
686
687             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
688             Global.getFileManager().purgeResDirectory();
689
690         } catch (InitializationException e) {
691             // Fatal
692             e.printStackTrace();
693             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
694             return;
695         }
696
697         NeverNote application = new NeverNote(dbConn);
698
699                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
700                 if (Global.startMinimized()) 
701                         application.showMinimized();
702                 else {
703                         if (Global.wasWindowMaximized())
704                                 application.showMaximized();
705                         else
706                                 application.show();
707                 }
708                 
709                 if (showSplash)
710                         splash.finish(application);
711                 QApplication.exec();
712                 System.out.println("Goodbye.");
713                 QApplication.exit();
714         }
715
716     /**
717      * Open the internal database, or create if not present
718      *
719      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
720      */
721     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
722         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
723         
724         File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
725                 boolean dbExists = f.exists(); 
726                 if (!dbExists)
727                         Global.setDatabaseUrl("");
728         
729         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
730             boolean goodCheck = false;
731             while (!goodCheck) {
732                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
733                 dialog.exec();
734                 if (!dialog.okPressed())
735                     System.exit(0);
736                 Global.cipherPassword = dialog.getPassword();
737                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
738                         Global.getDatabaseUserPassword(), Global.cipherPassword);
739             }
740         }
741         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
742        return dbConn;
743     }
744     
745     // Encrypt the database upon shutdown
746     private void encryptOnShutdown() {
747         String dbPath= Global.getFileManager().getDbDirPath("");
748         String dbName = "NeverNote";
749         try {
750                 Statement st = conn.getConnection().createStatement();  
751                 st.execute("shutdown");
752                 if (QMessageBox.question(this, "Are you sure", 
753                                 "Are you sure you wish to encrypt the database?",
754                                 QMessageBox.StandardButton.Yes, 
755                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
756                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
757                         Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
758                         QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
759                 }
760         } catch (SQLException e) {
761                         e.printStackTrace();
762                 }       
763     }
764     
765     // Decrypt the database upon shutdown
766     private void decryptOnShutdown() {
767         String dbPath= Global.getFileManager().getDbDirPath("");
768         String dbName = "NeverNote";
769         try {
770                 Statement st = conn.getConnection().createStatement();  
771                 st.execute("shutdown");
772                 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
773                         encryptCipher = "AES";
774                 else
775                         encryptCipher = "XTEA";
776                 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure", 
777                                 "Are you sure you wish to decrypt the database?"),
778                                 QMessageBox.StandardButton.Yes, 
779                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
780
781                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
782                         Global.setDatabaseUrl("");
783                         QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
784                 }
785                 } catch (SQLException e) {
786                         e.printStackTrace();
787                 }       
788     }
789     /**
790      * Encrypt/Decrypt the local database
791      **/
792     public void doDatabaseEncrypt() {
793         // The database is not currently encrypted
794         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
795                 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
796                                 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
797                                 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
798                                 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
799                                 "Do you wish to proceed?"),
800                                 QMessageBox.StandardButton.Yes, 
801                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
802                                 return;
803                 }
804                 DBEncryptDialog dialog = new DBEncryptDialog();
805                 dialog.exec();
806                 if (dialog.okPressed()) {
807                         Global.cipherPassword = dialog.getPassword();
808                         encryptOnShutdown  = true;
809                         encryptCipher = dialog.getEncryptionMethod();
810                 }
811         } else {
812             DBEncryptDialog dialog = new DBEncryptDialog();
813             dialog.setWindowTitle("Database Decryption");
814             dialog.hideEncryption();
815             dialog.exec();
816             if (dialog.okPressed()) {
817                 if (!dialog.getPassword().equals(Global.cipherPassword)) {
818                         QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
819                         return;
820                 }
821                 decryptOnShutdown  = true;
822                 encryptCipher = "";
823             }
824         }
825         return;
826     }
827
828         private static void initializeGlobalSettings(String[] args) throws InitializationException {
829                 StartupConfig   startupConfig = new StartupConfig();
830
831         for (String arg : args) {
832             String lower = arg.toLowerCase();
833             if (lower.startsWith("--name="))
834                startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
835             if (lower.startsWith("--home="))
836                startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
837             if (lower.startsWith("--disable-viewing"))
838                startupConfig.setDisableViewing(true);
839         }
840                 Global.setup(startupConfig);
841     }
842
843     // Exit point
844         @Override
845         public void closeEvent(QCloseEvent event) {     
846                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
847                 waitCursor(true);
848                 
849                 if (currentNote!= null & browserWindow!=null) {
850                         if (!currentNote.getTitle().equals(browserWindow.getTitle()))
851                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
852                 }
853                 saveNote();
854                 setMessage(tr("Beginning shutdown."));
855                 
856                 // Close down external windows
857                 Collection<ExternalBrowse> windows = externalWindows.values();
858                 Iterator<ExternalBrowse> iterator = windows.iterator();
859                 while (iterator.hasNext()) {
860                         ExternalBrowse browser = iterator.next();
861                         browser.windowClosing.disconnect();
862                         browser.close();
863                 }
864                 
865                 
866                 externalFileEditedSaver();
867                 if (Global.isConnected && Global.synchronizeOnClose()) {
868                         setMessage(tr("Performing synchronization before closing."));
869                         syncRunner.addWork("SYNC");
870                 }
871                 setMessage("Closing Program.");
872                 threadMonitorTimer.stop();
873
874                 syncRunner.addWork("STOP");
875                 syncRunner.keepRunning = false;
876                 thumbnailRunner.addWork("STOP");
877                 syncRunner.keepRunning = false;
878                 indexRunner.addWork("STOP");
879                 syncRunner.keepRunning = false;
880                 saveNote();
881                 listManager.stop();
882                 saveWindowState();
883
884                 if (tempFiles != null)
885                         tempFiles.clear();
886
887                 browserWindow.noteSignal.tagsChanged.disconnect();
888                 browserWindow.noteSignal.titleChanged.disconnect();
889                 browserWindow.noteSignal.noteChanged.disconnect();
890                 browserWindow.noteSignal.notebookChanged.disconnect();
891                 browserWindow.noteSignal.createdDateChanged.disconnect();
892                 browserWindow.noteSignal.alteredDateChanged.disconnect();
893                 syncRunner.searchSignal.listChanged.disconnect();
894                 syncRunner.tagSignal.listChanged.disconnect();
895         syncRunner.notebookSignal.listChanged.disconnect();
896         syncRunner.noteIndexSignal.listChanged.disconnect();
897
898                 if (isVisible())
899                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
900                 saveNoteColumnPositions();
901                 saveNoteIndexWidth();
902                 
903                 int width = notebookTree.columnWidth(0);
904                 Global.setColumnWidth("notebookTreeName", width);
905                 width = tagTree.columnWidth(0);
906                 Global.setColumnWidth("tagTreeName", width);
907                 
908                 Global.saveWindowMaximized(isMaximized());
909                 Global.saveCurrentNoteGuid(currentNoteGuid);
910                         
911                 int sortCol = noteTableView.proxyModel.sortColumn();
912                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
913                 Global.setSortColumn(sortCol);
914                 Global.setSortOrder(sortOrder);
915                 
916                 hide();
917                 trayIcon.hide();
918                 Global.keepRunning = false;
919                 try {
920                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
921                         indexRunner.thread().join(50);
922                         logger.log(logger.MEDIUM, "Index thread has stopped");
923                 } catch (InterruptedException e1) {
924                         e1.printStackTrace();
925                 }
926                 if (!syncRunner.isIdle()) {
927                         try {
928                                 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
929                                 syncThread.join();
930                                 logger.log(logger.MEDIUM, "Sync thread has stopped");
931                         } catch (InterruptedException e1) {
932                                 e1.printStackTrace();
933                         }
934                 }
935
936                 if (encryptOnShutdown) {
937                         encryptOnShutdown();
938                 }
939                 if (decryptOnShutdown) {
940                         decryptOnShutdown();
941                 }
942                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
943         }
944
945         public void setMessage(String s) {
946                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
947                 logger.log(logger.HIGH, "Message: " +s);
948                 statusBar.showMessage(s);
949                 emitLog.add(s);
950                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
951         }
952                 
953         private void waitCursor(boolean wait) {
954 //              if (wait)
955 //                      QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
956 //              else
957 //                      QApplication.restoreOverrideCursor();
958         }
959         
960         private void setupIndexListeners() {
961                 indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
962                 indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
963 //                      indexRunner.threadSignal.indexNeeded.connect(listManager, "setIndexNeeded(String, String, Boolean)");
964         }
965         private void setupSyncSignalListeners() {
966                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
967         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
968         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
969         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
970         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
971         
972                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
973                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
974                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
975                 
976                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
977                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
978                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
979                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
980                 
981                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
982         }
983         
984         private void setupBrowserSignalListeners() {
985                 setupBrowserWindowListeners(browserWindow, true);
986         }
987
988         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
989                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
990                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
991             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
992             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
993             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
994             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
995             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
996             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
997             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
998             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
999             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1000             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1001             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1002             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1003             if (master) browser.focusLost.connect(this, "saveNote()");
1004             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1005         }
1006
1007         //***************************************************************
1008         //***************************************************************
1009         //* Settings and look & feel
1010         //***************************************************************
1011         //***************************************************************
1012         @SuppressWarnings("unused")
1013         private void settings() {
1014                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1015                 saveNoteColumnPositions();
1016                 saveNoteIndexWidth();
1017                 showColumns();
1018         ConfigDialog settings = new ConfigDialog(this);
1019         String dateFormat = Global.getDateFormat();
1020         String timeFormat = Global.getTimeFormat();
1021         
1022                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1023                 indexTimer.start(indexTime);  // reset indexing timer
1024         
1025         settings.exec();
1026         if (Global.showTrayIcon())
1027                 trayIcon.show();
1028         else
1029                 trayIcon.hide();
1030         showColumns();
1031         if (menuBar.showEditorBar.isChecked())
1032                 showEditorButtons(browserWindow);
1033         
1034         // Reset the save timer
1035         if (Global.getAutoSaveInterval() > 0)
1036                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1037         else
1038                 saveTimer.stop();
1039         
1040         // This is a hack to force a reload of the index in case the date or time changed.
1041 //        if (!dateFormat.equals(Global.getDateFormat()) ||
1042 //                      !timeFormat.equals(Global.getTimeFormat())) {
1043                 noteCache.clear();
1044                 noteIndexUpdated(true);
1045 //        }
1046         
1047         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1048         }
1049         // Restore things to the way they were
1050         private void restoreWindowState(boolean mainWindow) {
1051                 // We need to name things or this doesn't work.
1052                 setObjectName("NeverNote");
1053                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1054                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1055                 leftSplitter1.setObjectName("leftSplitter1");   
1056                 
1057                 // Restore the actual positions.
1058                 if (mainWindow)
1059                         restoreGeometry(Global.restoreGeometry(objectName()));
1060         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1061         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1062         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1063        
1064         }
1065         // Save window positions for the next start
1066         private void saveWindowState() {
1067                 Global.saveGeometry(objectName(), saveGeometry());
1068                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1069                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1070                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1071         }    
1072         // Load the style sheet
1073         private void loadStyleSheet() {
1074                 String fileName = Global.getFileManager().getQssDirPath("default.qss");
1075                 QFile file = new QFile(fileName);
1076                 file.open(OpenModeFlag.ReadOnly);
1077                 String styleSheet = file.readAll().toString();
1078                 file.close();
1079                 setStyleSheet(styleSheet);
1080         }
1081         // Save column positions for the next time
1082         private void saveNoteColumnPositions() {
1083                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1084                 Global.setColumnPosition("noteTableCreationPosition", position);
1085                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1086                 Global.setColumnPosition("noteTableTagPosition", position);
1087                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1088                 Global.setColumnPosition("noteTableNotebookPosition", position);
1089                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1090                 Global.setColumnPosition("noteTableChangedPosition", position);
1091                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1092                 Global.setColumnPosition("noteTableAuthorPosition", position);
1093                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1094                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1095                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1096                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1097                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1098                 Global.setColumnPosition("noteTableTitlePosition", position);
1099                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1100                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1101                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1102                 Global.setColumnPosition("noteTableGuidPosition", position);
1103                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1104                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1105
1106         }
1107         // Save column widths for the next time
1108         private void saveNoteIndexWidth() {
1109                 int width;
1110         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1111         Global.setColumnWidth("noteTableCreationPosition", width);
1112                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1113                 Global.setColumnWidth("noteTableChangedPosition", width);
1114                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1115                 Global.setColumnWidth("noteTableGuidPosition", width);
1116                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1117                 Global.setColumnWidth("noteTableNotebookPosition", width);
1118                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1119                 Global.setColumnWidth("noteTableTagPosition", width);
1120                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1121                 Global.setColumnWidth("noteTableTitlePosition", width);
1122                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1123                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1124                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1125                 Global.setColumnWidth("noteTableAuthorPosition", width);
1126                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1127                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1128                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1129                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1130                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1131                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1132                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1133                 Global.setColumnWidth("noteTableGuidPosition", width);
1134         }
1135         
1136         
1137     //***************************************************************
1138     //***************************************************************
1139     //** These functions deal with Notebook menu items
1140     //***************************************************************
1141     //***************************************************************
1142     // Setup the tree containing the user's notebooks.
1143     private void initializeNotebookTree() {       
1144         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1145  //     notebookTree.itemSelectionChanged.connect(this, "notebookTreeSelection()");
1146         notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1147         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1148  //     notebookTree.resize(Global.getSize("notebookTree"));
1149         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1150     }   
1151     // Listener when a notebook is selected
1152         private void notebookTreeSelection() {
1153                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1154
1155                 clearTrashFilter();
1156                 clearAttributeFilter();
1157                 clearSavedSearchFilter();
1158                 if (Global.mimicEvernoteInterface) {
1159                         clearTagFilter();
1160                         searchField.clear();
1161                 }
1162                 menuBar.noteRestoreAction.setVisible(false);            
1163         menuBar.notebookEditAction.setEnabled(true);
1164         menuBar.notebookDeleteAction.setEnabled(true);
1165         menuBar.notebookIconAction.setEnabled(true);
1166         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1167         QTreeWidgetItem currentSelection;
1168         selectedNotebookGUIDs.clear();
1169         if (!Global.mimicEvernoteInterface) {
1170                 for (int i=0; i<selections.size(); i++) {
1171                         currentSelection = selections.get(i);
1172                         if (!currentSelection.text(2).equals("STACK"))
1173                                 selectedNotebookGUIDs.add(currentSelection.text(2));
1174                         else {
1175                                 String stackName = currentSelection.text(0);
1176                                 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1177                                         Notebook book = listManager.getNotebookIndex().get(j);
1178                                         if (book.getStack()!=null && book.getStack().equalsIgnoreCase(stackName))
1179                                                 selectedNotebookGUIDs.add(book.getGuid());
1180                                 }
1181                         }
1182                 }
1183         
1184                 
1185                 // There is the potential for no notebooks to be selected if this 
1186                 // happens then we make it look like all notebooks were selecetd.
1187                 // If that happens, just select the "all notebooks"
1188                 selections = notebookTree.selectedItems();
1189                 if (selections.size()==0) {
1190                         selectedNotebookGUIDs.clear();
1191                         menuBar.notebookEditAction.setEnabled(false);
1192                         menuBar.notebookDeleteAction.setEnabled(false);
1193                         menuBar.notebookIconAction.setEnabled(false);
1194                 }
1195                 if (selectedNotebookGUIDs.size() == 1 && selectedNotebookGUIDs.get(0).equals(previousSelectedNotebook)) {
1196                         previousSelectedNotebook = selectedNotebookGUIDs.get(0);
1197                         previousSelectedNotebook = "";
1198                         notebookTree.clearSelection();
1199                         notebookTreeSelection();
1200                         return;
1201                 }
1202                 if (selectedNotebookGUIDs.size() == 1)
1203                         previousSelectedNotebook = selectedNotebookGUIDs.get(0);
1204                 if (selectedNotebookGUIDs.size() > 1) 
1205                         previousSelectedNotebook = "";
1206         } else {
1207                 String guid = "";
1208                 String stackName = "";
1209                 if (selections.size() > 0) {
1210                         guid = (selections.get(0).text(2));
1211                         stackName = selections.get(0).text(0);
1212                 }
1213                 if (!guid.equals("") && !guid.equals("STACK")) {
1214                         selectedNotebookGUIDs.add(guid);
1215                         menuBar.notebookIconAction.setEnabled(true);
1216                 }
1217                 else {
1218                         menuBar.notebookIconAction.setEnabled(false);
1219                                 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1220                                         Notebook book = listManager.getNotebookIndex().get(j);
1221                                         if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1222                                                 selectedNotebookGUIDs.add(book.getGuid());
1223                                 }
1224                 }
1225         }
1226         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1227         listManager.loadNotesIndex();
1228         noteIndexUpdated(false);
1229                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1230
1231     }
1232     private void clearNotebookFilter() {
1233         notebookTree.blockSignals(true);
1234         notebookTree.clearSelection();
1235                 menuBar.noteRestoreAction.setVisible(false);
1236         menuBar.notebookEditAction.setEnabled(false);
1237         menuBar.notebookDeleteAction.setEnabled(false);
1238         selectedNotebookGUIDs.clear();
1239         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1240         notebookTree.blockSignals(false);
1241     }
1242         // Triggered when the notebook DB has been updated
1243         private void notebookIndexUpdated() {
1244                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1245         
1246                 // Get the possible icons
1247                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1248         notebookTree.setIcons(icons);
1249         
1250         if (selectedNotebookGUIDs == null)
1251                         selectedNotebookGUIDs = new ArrayList<String>();
1252                 List<Notebook> books = conn.getNotebookTable().getAll();
1253                 for (int i=books.size()-1; i>=0; i--) {
1254                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1255                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1256                                         books.remove(i);
1257                                         j=listManager.getArchiveNotebookIndex().size();
1258                                 }
1259                         }
1260                 }
1261                 
1262                 
1263                 listManager.countNotebookResults(listManager.getNoteIndex());
1264                 notebookTree.blockSignals(true);
1265         notebookTree.load(books, listManager.getLocalNotebooks());
1266         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1267                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1268                 if (!found)
1269                         selectedNotebookGUIDs.remove(i);
1270         }
1271         notebookTree.blockSignals(false);
1272         
1273                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1274     }
1275     // Show/Hide note information
1276         private void toggleNotebookWindow() {
1277                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1278         if (notebookTree.isVisible())
1279                 notebookTree.hide();
1280         else
1281                 notebookTree.show();
1282         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1283         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1284         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1285     }   
1286         // Add a new notebook
1287         @SuppressWarnings("unused")
1288         private void addNotebook() {
1289                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1290                 NotebookEdit edit = new NotebookEdit();
1291                 edit.setNotebooks(listManager.getNotebookIndex());
1292                 edit.exec();
1293         
1294                 if (!edit.okPressed())
1295                         return;
1296         
1297                 Calendar currentTime = new GregorianCalendar();
1298                 Long l = new Long(currentTime.getTimeInMillis());
1299                 String randint = new String(Long.toString(l));
1300         
1301                 Notebook newBook = new Notebook();
1302                 newBook.setUpdateSequenceNum(0);
1303                 newBook.setGuid(randint);
1304                 newBook.setName(edit.getNotebook());
1305                 newBook.setServiceCreated(new Date().getTime());
1306                 newBook.setServiceUpdated(new Date().getTime());
1307                 newBook.setDefaultNotebook(false);
1308                 newBook.setPublished(false);
1309                 
1310                 listManager.getNotebookIndex().add(newBook);
1311                 if (edit.isLocal())
1312                         listManager.getLocalNotebooks().add(newBook.getGuid());
1313                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1314                 notebookIndexUpdated();
1315                 listManager.countNotebookResults(listManager.getNoteIndex());
1316 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1317                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1318         }
1319         // Edit an existing notebook
1320         @SuppressWarnings("unused")
1321         private void editNotebook() {
1322                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1323                 NotebookEdit edit = new NotebookEdit();
1324                 edit.setTitle(tr("Edit Notebook"));
1325                 edit.setLocalCheckboxEnabled(false);
1326                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1327                 QTreeWidgetItem currentSelection;
1328                 currentSelection = selections.get(0);
1329                 edit.setNotebook(currentSelection.text(0));
1330                 edit.setNotebooks(listManager.getNotebookIndex());
1331
1332                 String guid = currentSelection.text(2);
1333                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1334                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1335                                 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1336                                 i=listManager.getNotebookIndex().size();
1337                         }
1338                 }
1339                 edit.exec();
1340         
1341                 if (!edit.okPressed())
1342                         return;
1343         
1344                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1345                 currentSelection.setText(0, edit.getNotebook());
1346                 
1347                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1348                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1349                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1350                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1351                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1352                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1353                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1354                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1355                                 }
1356                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1357                                 i=listManager.getNotebookIndex().size();
1358                         }
1359                 }
1360                 
1361                 // Build a list of non-closed notebooks
1362                 List<Notebook> nbooks = new ArrayList<Notebook>();
1363                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1364                         boolean found=false;
1365                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1366                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1367                                         found = true;
1368                         }
1369                         if (!found)
1370                                 nbooks.add(listManager.getNotebookIndex().get(i));
1371                 }
1372                 
1373                 browserWindow.setNotebookList(nbooks);
1374                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1375         }
1376         // Delete an existing notebook
1377         @SuppressWarnings("unused")
1378         private void deleteNotebook() {
1379                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1380                 boolean assigned = false;
1381                 // Check if any notes have this notebook
1382                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1383         for (int i=0; i<selections.size(); i++) {
1384                 QTreeWidgetItem currentSelection;
1385                 currentSelection = selections.get(i);
1386                 String guid = currentSelection.text(2);
1387                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1388                         String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1389                         if (noteGuid.equals(guid)) {
1390                                 assigned = true;
1391                                 j=listManager.getNoteIndex().size();
1392                                 i=selections.size();
1393                         }
1394                 }
1395         }
1396                 if (assigned) {
1397                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1398                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1399                         return;
1400                 }
1401                 
1402                 if (conn.getNotebookTable().getAll().size() == 1) {
1403                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1404                         return;
1405                 }
1406         
1407         // If all notebooks are clear, verify the delete
1408                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected notebooks?"),
1409                         QMessageBox.StandardButton.Yes, 
1410                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1411                         return;
1412                 }
1413                 
1414                 // If confirmed, delete the notebook
1415         for (int i=selections.size()-1; i>=0; i--) {
1416                 QTreeWidgetItem currentSelection;
1417                 currentSelection = selections.get(i);
1418                 String guid = currentSelection.text(2);
1419                 conn.getNotebookTable().expungeNotebook(guid, true);
1420                 listManager.deleteNotebook(guid);
1421         }
1422 //        for (int i=<dbRunner.getLocalNotebooks().size()-1; i>=0; i--) {
1423  //             if (dbRunner.getLocalNotebooks().get(i).equals(arg0))
1424  //       }
1425         notebookTreeSelection();
1426         notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1427         listManager.countNotebookResults(listManager.getNoteIndex());
1428 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1429         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1430         }
1431         // A note's notebook has been updated
1432         @SuppressWarnings("unused")
1433         private void updateNoteNotebook(String guid, String notebookGuid) {
1434                 
1435                 // Update the list manager
1436                 listManager.updateNoteNotebook(guid, notebookGuid);
1437                 listManager.countNotebookResults(listManager.getNoteIndex());
1438 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1439                 
1440                 // Find the name of the notebook
1441                 String notebookName = null;
1442                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1443                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1444                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1445                                 break;
1446                         }
1447                 }
1448                 
1449                 // If we found the name, update the browser window
1450                 if (notebookName != null) {
1451                         updateListNoteNotebook(guid, notebookName);
1452                         if (guid.equals(currentNoteGuid)) {
1453                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1454                                 if (pos >=0)
1455                                         browserWindow.notebookBox.setCurrentIndex(pos);
1456                         }
1457                 }
1458                 
1459                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1460                 if (guid.equals(currentNoteGuid)) {
1461                         if (currentNote != null) {
1462                                 currentNote.setNotebookGuid(notebookGuid);
1463                         }
1464                 }
1465         }
1466         // Open/close notebooks
1467         @SuppressWarnings("unused")
1468         private void closeNotebooks() {
1469                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1470                 na.exec();
1471                 if (!na.okClicked())
1472                         return;
1473                 
1474                 waitCursor(true);
1475                 listManager.getArchiveNotebookIndex().clear();
1476                 
1477                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1478                         String text = na.getClosedBookList().takeItem(i).text();
1479                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1480                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1481                                         Notebook n = listManager.getNotebookIndex().get(j);
1482                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1483                                         listManager.getArchiveNotebookIndex().add(n);
1484                                         j=listManager.getNotebookIndex().size();
1485                                 }
1486                         }
1487                 }
1488                 
1489                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1490                         String text = na.getOpenBookList().takeItem(i).text();
1491                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1492                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1493                                         Notebook n = listManager.getNotebookIndex().get(j);
1494                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1495                                         j=listManager.getNotebookIndex().size();
1496                                 }
1497                         }
1498                 }
1499                 notebookTreeSelection();
1500                 listManager.loadNotesIndex();
1501                 notebookIndexUpdated();
1502                 noteIndexUpdated(false);
1503 //              noteIndexUpdated(false);
1504                 
1505                 // Build a list of non-closed notebooks
1506                 List<Notebook> nbooks = new ArrayList<Notebook>();
1507                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1508                         boolean found=false;
1509                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1510                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1511                                         found = true;
1512                         }
1513                         if (!found)
1514                                 nbooks.add(listManager.getNotebookIndex().get(i));
1515                 }
1516                 waitCursor(false);
1517                 browserWindow.setNotebookList(nbooks);
1518         }
1519         // Change the notebook's icon
1520         private void setNotebookIcon() {
1521                 QTreeWidgetItem currentSelection;
1522                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1523                 if (selections.size() == 0)
1524                         return;
1525                 
1526                 currentSelection = selections.get(0);   
1527                 String guid = currentSelection.text(2);
1528                 if (guid.equalsIgnoreCase(""))
1529                         return;
1530
1531                 QIcon currentIcon = currentSelection.icon(0);
1532                 QIcon icon = conn.getNotebookTable().getIcon(guid);
1533                 SetIcon dialog;
1534                 if (icon == null) {
1535                         dialog = new SetIcon(currentIcon);
1536                         dialog.setUseDefaultIcon(true);
1537                 } else {
1538                         dialog = new SetIcon(icon);
1539                         dialog.setUseDefaultIcon(false);
1540                 }
1541                 dialog.exec();
1542                 if (dialog.okPressed()) {
1543                         QIcon newIcon = dialog.getIcon();
1544                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1545                         if (newIcon == null) {
1546                                 boolean isPublished = false;;
1547                                 boolean found = false;
1548                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1549                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1550                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1551                                                 found = true;
1552                                         }
1553                                 }
1554                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1555                         }
1556                         currentSelection.setIcon(0, newIcon);
1557                 }
1558         
1559         }
1560         
1561         
1562     //***************************************************************
1563     //***************************************************************
1564     //** These functions deal with Tag menu items
1565     //***************************************************************
1566     //***************************************************************
1567         // Add a new notebook
1568         @SuppressWarnings("unused")
1569         private void addTag() {
1570                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1571                 TagEdit edit = new TagEdit();
1572                 edit.setTagList(listManager.getTagIndex());
1573                 edit.exec();
1574         
1575                 if (!edit.okPressed())
1576                         return;
1577         
1578                 Calendar currentTime = new GregorianCalendar();
1579                 Long l = new Long(currentTime.getTimeInMillis());
1580                 String randint = new String(Long.toString(l));
1581         
1582                 Tag newTag = new Tag();
1583                 newTag.setUpdateSequenceNum(0);
1584                 newTag.setGuid(randint);
1585                 newTag.setName(edit.getTag());
1586                 conn.getTagTable().addTag(newTag, true);
1587                 listManager.getTagIndex().add(newTag);
1588                 reloadTagTree(true);
1589                 
1590                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1591         }
1592         private void reloadTagTree() {
1593                 reloadTagTree(false);
1594         }
1595         private void reloadTagTree(boolean reload) {
1596                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1597                 tagIndexUpdated(reload);
1598                 boolean filter = false;
1599                 listManager.countTagResults(listManager.getNoteIndex());
1600                 if (notebookTree.selectedItems().size() > 0 
1601                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1602                                                   filter = true;
1603                 if (tagTree.selectedItems().size() > 0)
1604                         filter = true;
1605                 tagTree.showAllTags(!filter);
1606                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1607         }
1608         // Edit an existing tag
1609         @SuppressWarnings("unused")
1610         private void editTag() {
1611                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1612                 TagEdit edit = new TagEdit();
1613                 edit.setTitle("Edit Tag");
1614                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1615                 QTreeWidgetItem currentSelection;
1616                 currentSelection = selections.get(0);
1617                 edit.setTag(currentSelection.text(0));
1618                 edit.setTagList(listManager.getTagIndex());
1619                 edit.exec();
1620         
1621                 if (!edit.okPressed())
1622                         return;
1623         
1624                 String guid = currentSelection.text(2);
1625                 currentSelection.setText(0,edit.getTag());
1626                 
1627                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1628                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1629                                 listManager.getTagIndex().get(i).setName(edit.getTag());
1630                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1631                                 updateListTagName(guid);
1632                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1633                                         browserWindow.setTag(getTagNamesForNote(currentNote));
1634                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1635                                 return;
1636                         }
1637                 }
1638                 browserWindow.setTag(getTagNamesForNote(currentNote));
1639                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1640         }
1641         // Delete an existing tag
1642         @SuppressWarnings("unused")
1643         private void deleteTag() {
1644                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1645                 
1646                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1647                         QMessageBox.StandardButton.Yes, 
1648                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1649                                                         return;
1650                 }
1651                 
1652                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1653         for (int i=selections.size()-1; i>=0; i--) {
1654                 QTreeWidgetItem currentSelection;
1655                 currentSelection = selections.get(i);                   
1656                 removeTagItem(currentSelection.text(2));
1657         }
1658         tagIndexUpdated(true);
1659         tagTreeSelection();
1660         listManager.countTagResults(listManager.getNoteIndex());
1661 //              tagTree.updateCounts(listManager.getTagCounter());
1662         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1663         }
1664         // Remove a tag tree item.  Go recursively down & remove the children too
1665         private void removeTagItem(String guid) {
1666         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
1667                 String parent = listManager.getTagIndex().get(j).getParentGuid();
1668                 if (parent != null && parent.equals(guid)) {            
1669                         //Remove this tag's children
1670                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
1671                 }
1672         }
1673         //Now, remove this tag
1674         removeListTagName(guid);
1675         conn.getTagTable().expungeTag(guid, true);                      
1676         for (int a=0; a<listManager.getTagIndex().size(); a++) {
1677                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1678                         listManager.getTagIndex().remove(a);
1679                         return;
1680                 }
1681         }
1682         }
1683         // Setup the tree containing the user's tags
1684     private void initializeTagTree() {
1685         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1686 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1687         tagTree.itemClicked.connect(this, "tagTreeSelection()");
1688         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1689         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1690     }
1691     // Listener when a tag is selected
1692         private void tagTreeSelection() {
1693         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1694                 
1695         clearTrashFilter();
1696         clearAttributeFilter();
1697         clearSavedSearchFilter();
1698         
1699                 menuBar.noteRestoreAction.setVisible(false);
1700                 
1701         List<QTreeWidgetItem> selections = tagTree.selectedItems();
1702         QTreeWidgetItem currentSelection;
1703         selectedTagGUIDs.clear();
1704         for (int i=0; i<selections.size(); i++) {
1705                 currentSelection = selections.get(i);
1706                 selectedTagGUIDs.add(currentSelection.text(2));
1707         }
1708         if (selections.size() > 0) {
1709                 menuBar.tagEditAction.setEnabled(true);
1710                 menuBar.tagDeleteAction.setEnabled(true);
1711                 menuBar.tagIconAction.setEnabled(true);
1712         }
1713         else {
1714                 menuBar.tagEditAction.setEnabled(false);
1715                 menuBar.tagDeleteAction.setEnabled(false);
1716                 menuBar.tagIconAction.setEnabled(true);
1717         }
1718         if (selectedTagGUIDs.size() == 1 && selectedTagGUIDs.get(0).equals(previousSelectedTag)) {
1719                 previousSelectedTag = selectedTagGUIDs.get(0);
1720                 previousSelectedTag = "";
1721                 tagTree.clearSelection();
1722                 tagTreeSelection();
1723                 return;
1724         }
1725         if (selectedTagGUIDs.size() == 1)
1726                 previousSelectedTag = selectedTagGUIDs.get(0);
1727         if (selectedTagGUIDs.size() > 1) 
1728                 previousSelectedTag = "";
1729         listManager.setSelectedTags(selectedTagGUIDs);
1730         listManager.loadNotesIndex();
1731         noteIndexUpdated(false);
1732         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1733     }
1734     // trigger the tag index to be refreshed
1735     @SuppressWarnings("unused")
1736         private void tagIndexUpdated() {
1737         tagIndexUpdated(true);
1738     }
1739     private void tagIndexUpdated(boolean reload) {
1740         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1741                 if (selectedTagGUIDs == null)
1742                         selectedTagGUIDs = new ArrayList<String>();
1743 //              selectedTagGUIDs.clear();  // clear out old entries
1744
1745                 tagTree.blockSignals(true);
1746                 if (reload) {
1747                         tagTree.setIcons(conn.getTagTable().getAllIcons());
1748                         tagTree.load(listManager.getTagIndex());
1749                 }
1750         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1751                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1752                 if (!found)
1753                         selectedTagGUIDs.remove(i);
1754         }
1755         tagTree.blockSignals(false);
1756         
1757                 browserWindow.setTag(getTagNamesForNote(currentNote));
1758         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1759     }   
1760     // Show/Hide note information
1761         private void toggleTagWindow() {
1762                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1763         if (tagTree.isVisible())
1764                 tagTree.hide();
1765         else
1766                 tagTree.show();
1767         menuBar.hideTags.setChecked(tagTree.isVisible());
1768         Global.saveWindowVisible("tagTree", tagTree.isVisible());
1769         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1770     }   
1771         // A note's tags have been updated
1772         @SuppressWarnings("unused")
1773         private void updateNoteTags(String guid, List<String> tags) {
1774                 // Save any new tags.  We'll need them later.
1775                 List<String> newTags = new ArrayList<String>();
1776                 for (int i=0; i<tags.size(); i++) {
1777                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
1778                                 newTags.add(tags.get(i));
1779                 }
1780                 
1781                 listManager.saveNoteTags(guid, tags);
1782                 listManager.countTagResults(listManager.getNoteIndex());
1783                 StringBuffer names = new StringBuffer("");
1784                 for (int i=0; i<tags.size(); i++) {
1785                         names = names.append(tags.get(i));
1786                         if (i<tags.size()-1) {
1787                                 names.append(Global.tagDelimeter + " ");
1788                         }
1789                 }
1790                 browserWindow.setTag(names.toString());
1791                 noteDirty = true;
1792                 
1793                 // Now, we need to add any new tags to the tag tree
1794                 for (int i=0; i<newTags.size(); i++) 
1795                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
1796         }
1797         // Get a string containing all tag names for a note
1798         private String getTagNamesForNote(Note n) {
1799                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
1800                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
1801                         return "";
1802                 StringBuffer buffer = new StringBuffer(100);
1803                 Vector<String> v = new Vector<String>();
1804                 List<String> guids = n.getTagGuids();
1805                 
1806                 if (guids == null) 
1807                         return "";
1808                 
1809                 for (int i=0; i<guids.size(); i++) {
1810                         v.add(listManager.getTagNameByGuid(guids.get(i)));
1811                 }
1812                 Comparator<String> comparator = Collections.reverseOrder();
1813                 Collections.sort(v,comparator);
1814                 Collections.reverse(v);
1815                 
1816                 for (int i = 0; i<v.size(); i++) {
1817                         if (i>0) 
1818                                 buffer.append(", ");
1819                         buffer.append(v.get(i));
1820                 }
1821                 
1822                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
1823                 return buffer.toString();
1824         }       
1825         // Tags were added via dropping notes from the note list
1826         @SuppressWarnings("unused")
1827         private void tagsAdded(String noteGuid, String tagGuid) {
1828                 String tagName = null;
1829                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1830                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
1831                                 tagName = listManager.getTagIndex().get(i).getName();
1832                                 i=listManager.getTagIndex().size();
1833                         }
1834                 }
1835                 if (tagName == null)
1836                         return;
1837                 
1838                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
1839                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
1840                                 List<String> tagNames = new ArrayList<String>();
1841                                 tagNames.add(new String(tagName));
1842                                 Note n = listManager.getMasterNoteIndex().get(i);
1843                                 for (int j=0; j<n.getTagNames().size(); j++) {
1844                                         tagNames.add(new String(n.getTagNames().get(j)));
1845                                 }
1846                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
1847                                 if (n.getGuid().equals(currentNoteGuid)) {
1848                                         Collections.sort(tagNames);
1849                                         String display = "";
1850                                         for (int j=0; j<tagNames.size(); j++) {
1851                                                 display = display+tagNames.get(j);
1852                                                 if (j+2<tagNames.size()) 
1853                                                         display = display+Global.tagDelimeter+" ";
1854                                         }
1855                                         browserWindow.setTag(display);
1856                                 }
1857                                 i=listManager.getMasterNoteIndex().size();
1858                         }
1859                 }
1860                 
1861                 
1862                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
1863         }
1864         private void clearTagFilter() {
1865                 tagTree.blockSignals(true);
1866                 tagTree.clearSelection();
1867                 menuBar.noteRestoreAction.setVisible(false);
1868                 menuBar.tagEditAction.setEnabled(false);
1869                 menuBar.tagDeleteAction.setEnabled(false);
1870                 menuBar.tagIconAction.setEnabled(false);
1871                 selectedTagGUIDs.clear();
1872         listManager.setSelectedTags(selectedTagGUIDs);
1873         tagTree.blockSignals(false);
1874         }
1875         // Change the icon for a tag
1876         private void setTagIcon() {
1877                 QTreeWidgetItem currentSelection;
1878                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1879                 if (selections.size() == 0)
1880                         return;
1881                 
1882                 currentSelection = selections.get(0);   
1883                 String guid = currentSelection.text(2);
1884
1885                 QIcon currentIcon = currentSelection.icon(0);
1886                 QIcon icon = conn.getTagTable().getIcon(guid);
1887                 SetIcon dialog;
1888                 if (icon == null) {
1889                         dialog = new SetIcon(currentIcon);
1890                         dialog.setUseDefaultIcon(true);
1891                 } else {
1892                         dialog = new SetIcon(icon);
1893                         dialog.setUseDefaultIcon(false);
1894                 }
1895                 dialog.exec();
1896                 if (dialog.okPressed()) {
1897                         QIcon newIcon = dialog.getIcon();
1898                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
1899                         if (newIcon == null) 
1900                                 newIcon = new QIcon(iconPath+"tag.png");
1901                         currentSelection.setIcon(0, newIcon);
1902                 }
1903         
1904         }
1905
1906         
1907     //***************************************************************
1908     //***************************************************************
1909     //** These functions deal with Saved Search menu items
1910     //***************************************************************
1911     //***************************************************************
1912         // Add a new notebook
1913         @SuppressWarnings("unused")
1914         private void addSavedSearch() {
1915                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
1916                 SavedSearchEdit edit = new SavedSearchEdit();
1917                 edit.setSearchList(listManager.getSavedSearchIndex());
1918                 edit.exec();
1919         
1920                 if (!edit.okPressed())
1921                         return;
1922         
1923                 Calendar currentTime = new GregorianCalendar();         
1924                 Long l = new Long(currentTime.getTimeInMillis());
1925                 String randint = new String(Long.toString(l));
1926         
1927                 SavedSearch search = new SavedSearch();
1928                 search.setUpdateSequenceNum(0);
1929                 search.setGuid(randint);
1930                 search.setName(edit.getName());
1931                 search.setQuery(edit.getQuery());
1932                 search.setFormat(QueryFormat.USER);
1933                 listManager.getSavedSearchIndex().add(search);
1934                 conn.getSavedSearchTable().addSavedSearch(search, true);
1935                 savedSearchIndexUpdated();
1936                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
1937         }
1938         // Edit an existing tag
1939         @SuppressWarnings("unused")
1940         private void editSavedSearch() {
1941                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
1942                 SavedSearchEdit edit = new SavedSearchEdit();
1943                 edit.setTitle(tr("Edit Search"));
1944                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1945                 QTreeWidgetItem currentSelection;
1946                 currentSelection = selections.get(0);
1947                 String guid = currentSelection.text(1);
1948                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
1949                 edit.setName(currentSelection.text(0));
1950                 edit.setQuery(s.getQuery());
1951                 edit.setSearchList(listManager.getSavedSearchIndex());
1952                 edit.exec();
1953         
1954                 if (!edit.okPressed())
1955                         return;
1956         
1957                 List<SavedSearch> list = listManager.getSavedSearchIndex();
1958                 SavedSearch search = null;
1959                 boolean found = false;
1960                 for (int i=0; i<list.size(); i++) {
1961                         search = list.get(i);
1962                         if (search.getGuid().equals(guid)) {
1963                                 i=list.size();
1964                                 found = true;
1965                         }
1966                 }
1967                 if (!found)
1968                         return;
1969                 search.setName(edit.getName());
1970                 search.setQuery(edit.getQuery());
1971                 conn.getSavedSearchTable().updateSavedSearch(search, true);
1972                 savedSearchIndexUpdated();
1973                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
1974         }
1975         // Delete an existing tag
1976         @SuppressWarnings("unused")
1977         private void deleteSavedSearch() {
1978                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
1979                 
1980                 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
1981                         QMessageBox.StandardButton.Yes, 
1982                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1983                                                         return;
1984                 }
1985                 
1986                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1987         for (int i=selections.size()-1; i>=0; i--) {
1988                 QTreeWidgetItem currentSelection;
1989                 currentSelection = selections.get(i);
1990                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
1991                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
1992                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
1993                                 listManager.getSavedSearchIndex().remove(j);
1994                                 j=listManager.getSavedSearchIndex().size()+1;
1995                         }
1996                 }
1997                 selections.remove(i);
1998         }
1999         savedSearchIndexUpdated();
2000         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2001         }
2002     // Setup the tree containing the user's tags
2003     private void initializeSavedSearchTree() {
2004         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2005         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2006         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2007     }
2008     // Listener when a tag is selected
2009     @SuppressWarnings("unused")
2010         private void savedSearchTreeSelection() {
2011         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2012
2013         clearNotebookFilter();
2014         clearTagFilter();
2015         clearTrashFilter();
2016         clearAttributeFilter();
2017         
2018         String currentGuid = selectedSavedSearchGUID;
2019         menuBar.savedSearchEditAction.setEnabled(true);
2020         menuBar.savedSearchDeleteAction.setEnabled(true);
2021         menuBar.savedSearchIconAction.setEnabled(true);
2022         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2023         QTreeWidgetItem currentSelection;
2024         selectedSavedSearchGUID = "";
2025         for (int i=0; i<selections.size(); i++) {
2026                 currentSelection = selections.get(i);
2027                 if (currentSelection.text(1).equals(currentGuid)) {
2028                         currentSelection.setSelected(false);
2029                 } else {
2030                         selectedSavedSearchGUID = currentSelection.text(1);
2031                 }
2032 //              i = selections.size() +1;
2033         }
2034         
2035         // There is the potential for no notebooks to be selected if this 
2036         // happens then we make it look like all notebooks were selecetd.
2037         // If that happens, just select the "all notebooks"
2038         if (selections.size()==0) {
2039                 clearSavedSearchFilter();
2040         }
2041         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2042         
2043         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2044     }
2045     private void clearSavedSearchFilter() {
2046         menuBar.savedSearchEditAction.setEnabled(false);
2047         menuBar.savedSearchDeleteAction.setEnabled(false);
2048         menuBar.savedSearchIconAction.setEnabled(false);
2049         savedSearchTree.blockSignals(true);
2050         savedSearchTree.clearSelection();
2051         savedSearchTree.blockSignals(false);
2052         selectedSavedSearchGUID = "";
2053         searchField.setEditText("");
2054         searchPerformed = false;
2055         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2056     }
2057     // trigger the tag index to be refreshed
2058         private void savedSearchIndexUpdated() { 
2059                 if (selectedSavedSearchGUID == null)
2060                         selectedSavedSearchGUID = new String();
2061                 savedSearchTree.blockSignals(true);
2062                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2063         savedSearchTree.load(listManager.getSavedSearchIndex());
2064         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2065         savedSearchTree.blockSignals(false);
2066     }
2067     // trigger when the saved search selection changes
2068     @SuppressWarnings("unused")
2069         private void updateSavedSearchSelection() {
2070                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2071                 
2072         menuBar.savedSearchEditAction.setEnabled(true);
2073         menuBar.savedSearchDeleteAction.setEnabled(true);
2074         menuBar.savedSearchIconAction.setEnabled(true);
2075         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2076
2077         if (selections.size() > 0) {
2078                 menuBar.savedSearchEditAction.setEnabled(true);
2079                 menuBar.savedSearchDeleteAction.setEnabled(true);
2080                 menuBar.savedSearchIconAction.setEnabled(true);
2081                 selectedSavedSearchGUID = selections.get(0).text(1);
2082                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2083                 searchField.setEditText(s.getQuery());
2084         } else { 
2085                 menuBar.savedSearchEditAction.setEnabled(false);
2086                 menuBar.savedSearchDeleteAction.setEnabled(false);
2087                 menuBar.savedSearchIconAction.setEnabled(false);
2088                 selectedSavedSearchGUID = "";
2089                 searchField.setEditText("");
2090         }
2091         searchFieldChanged();
2092         
2093                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2094
2095         
2096     }
2097     // Show/Hide note information
2098         private void toggleSavedSearchWindow() {
2099                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2100         if (savedSearchTree.isVisible())
2101                 savedSearchTree.hide();
2102         else
2103                 savedSearchTree.show();
2104         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2105                                 
2106                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2107         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2108     }
2109         // Change the icon for a saved search
2110         private void setSavedSearchIcon() {
2111                 QTreeWidgetItem currentSelection;
2112                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2113                 if (selections.size() == 0)
2114                         return;
2115                 
2116                 currentSelection = selections.get(0);   
2117                 String guid = currentSelection.text(1);
2118
2119                 QIcon currentIcon = currentSelection.icon(0);
2120                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2121                 SetIcon dialog;
2122                 if (icon == null) {
2123                         dialog = new SetIcon(currentIcon);
2124                         dialog.setUseDefaultIcon(true);
2125                 } else {
2126                         dialog = new SetIcon(icon);
2127                         dialog.setUseDefaultIcon(false);
2128                 }
2129                 dialog.exec();
2130                 if (dialog.okPressed()) {
2131                         QIcon newIcon = dialog.getIcon();
2132                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2133                         if (newIcon == null) 
2134                                 newIcon = new QIcon(iconPath+"search.png");
2135                         currentSelection.setIcon(0, newIcon);
2136                 }
2137         
2138         }
2139         
2140         
2141         
2142         
2143     //***************************************************************
2144     //***************************************************************
2145     //** These functions deal with Help menu & tool menu items
2146     //***************************************************************
2147     //***************************************************************
2148         // Show database status
2149         @SuppressWarnings("unused")
2150         private void databaseStatus() {
2151                 waitCursor(true);
2152                 int dirty = conn.getNoteTable().getDirtyCount();
2153                 int unindexed = conn.getNoteTable().getUnindexedCount();
2154                 DatabaseStatus status = new DatabaseStatus();
2155                 status.setUnsynchronized(dirty);
2156                 status.setUnindexed(unindexed);
2157                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2158                 status.setNotebookCount(listManager.getNotebookIndex().size());
2159                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2160                 status.setTagCount(listManager.getTagIndex().size());
2161                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2162                 status.setWordCount(conn.getWordsTable().getWordCount());
2163                 waitCursor(false);
2164                 status.exec();
2165         }
2166         // Compact the database
2167         @SuppressWarnings("unused")
2168         private void compactDatabase() {
2169         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2170                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2171                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2172                                 "and NeverNote will be unresponsive until it is complete.  Do you wish to continue?"),
2173                                 QMessageBox.StandardButton.Yes, 
2174                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2175                                                         return;
2176                 }
2177                 setMessage("Compacting database.");
2178                 waitCursor(true);
2179                 listManager.compactDatabase();
2180                 waitCursor(false);
2181                 setMessage("Database compact is complete.");            
2182         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2183     }
2184         @SuppressWarnings("unused")
2185         private void accountInformation() {
2186                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2187                 AccountDialog dialog = new AccountDialog();
2188                 dialog.show();
2189                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2190         }
2191         @SuppressWarnings("unused")
2192         private void releaseNotes() {
2193                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2194                 QDialog dialog = new QDialog(this);
2195                 QHBoxLayout layout = new QHBoxLayout();
2196                 QTextEdit textBox = new QTextEdit();
2197                 layout.addWidget(textBox);
2198                 textBox.setReadOnly(true);
2199                 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2200                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2201                 QIODevice.OpenModeFlag.Text)))
2202                         return;
2203                 textBox.setText(file.readAll().toString());
2204                 file.close();
2205                 dialog.setWindowTitle(tr("Release Notes"));
2206                 dialog.setLayout(layout);
2207                 dialog.show();
2208                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2209         }
2210         // Called when user picks Log from the help menu
2211         @SuppressWarnings("unused")
2212         private void logger() {
2213                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2214                 QDialog dialog = new QDialog(this);
2215                 QHBoxLayout layout = new QHBoxLayout();
2216                 QListWidget textBox = new QListWidget();
2217                 layout.addWidget(textBox);
2218                 textBox.addItems(emitLog);
2219                 
2220                 dialog.setLayout(layout);
2221                 dialog.setWindowTitle(tr("Mesasge Log"));
2222                 dialog.show();
2223                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2224         }
2225         // Menu option "help/about" was selected
2226         @SuppressWarnings("unused")
2227         private void about() {
2228                 logger.log(logger.HIGH, "Entering NeverNote.about");
2229                 QMessageBox.about(this, 
2230                                                 tr("About NeverNote"),
2231                                                 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2232                                                 +Global.version
2233                                                 +tr("<hr></center>Evernote"
2234                                                                 +"An Open Source Evernote Client.<br><br>" 
2235                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2236                                                                 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2237                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2238                                                                 +"PDFRenderer is licened under the LGPL<br>"
2239                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2240                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2241                                                                 +"Jazzy is licened under the LGPL<br>"
2242                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));     
2243                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2244         }
2245         // Hide the entire left hand side
2246         @SuppressWarnings("unused")
2247         private void toggleLeftSide() {
2248                 boolean hidden;
2249                 
2250                 hidden = !menuBar.hideLeftSide.isChecked();
2251                 menuBar.hideLeftSide.setChecked(!hidden);
2252                 
2253                 if (notebookTree.isVisible() != hidden)
2254                         toggleNotebookWindow();
2255                 if (savedSearchTree.isVisible() != hidden)
2256                         toggleSavedSearchWindow();
2257                 if (tagTree.isVisible() != hidden)
2258                         toggleTagWindow();
2259                 if (attributeTree.isVisible() != hidden)
2260                         toggleAttributesWindow();
2261                 if (trashTree.isVisible() != hidden)
2262                         toggleTrashWindow();
2263                 
2264                 Global.saveWindowVisible("leftPanel", hidden);
2265                 
2266         }
2267                         
2268         
2269     //***************************************************************
2270     //***************************************************************
2271     //** These functions deal with the Toolbar
2272     //***************************************************************
2273     //***************************************************************  
2274         // Text in the search bar has been cleared
2275         private void searchFieldCleared() {
2276                 searchField.setEditText("");
2277                 saveNoteColumnPositions();
2278                 saveNoteIndexWidth();
2279         }
2280         // text in the search bar changed.  We only use this to tell if it was cleared, 
2281         // otherwise we trigger off searchFieldChanged.
2282         @SuppressWarnings("unused")
2283         private void searchFieldTextChanged(String text) {
2284                 if (text.trim().equals("")) {
2285                         searchFieldCleared();
2286                         if (searchPerformed) {
2287                                 noteCache.clear();
2288                                 listManager.setEnSearch("");
2289 /////                           listManager.clearNoteIndexSearch();
2290                                 //noteIndexUpdated(true);
2291                                 listManager.loadNotesIndex();
2292                                 refreshEvernoteNote(true);
2293                                 noteIndexUpdated(false);
2294                         }
2295                         searchPerformed = false;
2296                 }
2297         }
2298     // Text in the toolbar has changed
2299     private void searchFieldChanged() {
2300         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2301         noteCache.clear();
2302         saveNoteColumnPositions();
2303         saveNoteIndexWidth();
2304         String text = searchField.currentText();
2305         listManager.setEnSearch(text.trim());
2306         listManager.loadNotesIndex();
2307 //--->>>        noteIndexUpdated(true);
2308         noteIndexUpdated(false);
2309         refreshEvernoteNote(true);
2310         searchPerformed = true;
2311         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2312     }
2313
2314     // Build the window tool bar
2315     private void setupToolBar() {
2316         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2317         toolBar = addToolBar(tr("Tool Bar"));   
2318         menuBar.setupToolBarVisible();
2319         if (!Global.isWindowVisible("toolBar"))
2320                 toolBar.setVisible(false);
2321         else
2322                 toolBar.setVisible(true);
2323
2324         prevButton = toolBar.addAction("Previous");
2325         QIcon prevIcon = new QIcon(iconPath+"back.png");
2326         prevButton.setIcon(prevIcon);
2327         prevButton.triggered.connect(this, "previousViewedAction()");   
2328         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2329         
2330         nextButton = toolBar.addAction("Next");
2331         QIcon nextIcon = new QIcon(iconPath+"forward.png");
2332         nextButton.setIcon(nextIcon);
2333         nextButton.triggered.connect(this, "nextViewedAction()");       
2334         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2335         
2336         upButton = toolBar.addAction("Up");
2337         QIcon upIcon = new QIcon(iconPath+"up.png");
2338         upButton.setIcon(upIcon);
2339         upButton.triggered.connect(this, "upAction()");         
2340         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2341
2342         
2343         downButton = toolBar.addAction("Down");
2344         QIcon downIcon = new QIcon(iconPath+"down.png");
2345         downButton.setIcon(downIcon);
2346         downButton.triggered.connect(this, "downAction()");
2347         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2348         
2349         synchronizeButton = toolBar.addAction("Synchronize");
2350         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2351         synchronizeIconAngle = 0;
2352         synchronizeButton.triggered.connect(this, "evernoteSync()");
2353         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2354         
2355         printButton = toolBar.addAction("Print");
2356         QIcon printIcon = new QIcon(iconPath+"print.png");
2357         printButton.setIcon(printIcon);
2358         printButton.triggered.connect(this, "printNote()");
2359         togglePrintButton(Global.isToolbarButtonVisible("print"));
2360
2361         tagButton = toolBar.addAction("Tag"); 
2362         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2363         tagButton.setIcon(tagIcon);
2364         tagButton.triggered.connect(browserWindow, "modifyTags()");
2365         toggleTagButton(Global.isToolbarButtonVisible("tag"));
2366
2367         attributeButton = toolBar.addAction("Attributes"); 
2368         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2369         attributeButton.setIcon(attributeIcon);
2370         attributeButton.triggered.connect(this, "toggleNoteInformation()");
2371         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2372                 
2373         emailButton = toolBar.addAction("Email");
2374         QIcon emailIcon = new QIcon(iconPath+"email.png");
2375         emailButton.setIcon(emailIcon);
2376         emailButton.triggered.connect(this, "emailNote()");
2377         toggleEmailButton(Global.isToolbarButtonVisible("email"));
2378
2379         deleteButton = toolBar.addAction("Delete");     
2380         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2381         deleteButton.setIcon(deleteIcon);
2382         deleteButton.triggered.connect(this, "deleteNote()");
2383         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2384
2385         newButton = toolBar.addAction("New");
2386         QIcon newIcon = new QIcon(iconPath+"new.png");
2387         newButton.triggered.connect(this, "addNote()");
2388         newButton.setIcon(newIcon);
2389         toggleNewButton(Global.isToolbarButtonVisible("new"));
2390         
2391         allNotesButton = toolBar.addAction("All Notes");
2392         QIcon allIcon = new QIcon(iconPath+"books.png");
2393         allNotesButton.triggered.connect(this, "allNotes()");
2394         allNotesButton.setIcon(allIcon);
2395         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2396         
2397         toolBar.addSeparator();
2398         toolBar.addWidget(new QLabel(tr("Quota:")));
2399         toolBar.addWidget(quotaBar);
2400         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2401         updateQuotaBar();
2402         toolBar.addSeparator();
2403         
2404         // Setup the zoom
2405         zoomSpinner = new QSpinBox();
2406         zoomSpinner.setMinimum(10);
2407         zoomSpinner.setMaximum(1000);
2408         zoomSpinner.setAccelerated(true);
2409         zoomSpinner.setSingleStep(10);
2410         zoomSpinner.setValue(100);
2411         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2412         toolBar.addWidget(new QLabel(tr("Zoom")));
2413         toolBar.addWidget(zoomSpinner);
2414         
2415         //toolBar.addWidget(new QLabel("                    "));
2416         toolBar.addSeparator();
2417         toolBar.addWidget(new QLabel(tr("  Search:")));
2418         toolBar.addWidget(searchField);
2419         QSizePolicy sizePolicy = new QSizePolicy();
2420         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2421         searchField.setSizePolicy(sizePolicy);
2422         searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2423
2424         searchClearButton = toolBar.addAction("Search Clear");
2425         QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2426         searchClearButton.setIcon(searchClearIcon);
2427         searchClearButton.triggered.connect(this, "searchFieldCleared()");
2428         toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2429
2430         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2431     }
2432     // Update the sychronize button picture
2433     @Override
2434         public QMenu createPopupMenu() {
2435         QMenu contextMenu = super.createPopupMenu();
2436         
2437         contextMenu.addSeparator();
2438         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2439         contextMenu.addAction(prevAction);
2440         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2441
2442         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2443         contextMenu.addAction(nextAction);
2444         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2445
2446         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2447         contextMenu.addAction(upAction);
2448         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2449
2450         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2451         contextMenu.addAction(downAction);
2452         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2453
2454         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2455         contextMenu.addAction(synchronizeAction);
2456         synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2457
2458         QAction printAction = addContextAction("print", tr("Print"));
2459         contextMenu.addAction(printAction);
2460         printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2461
2462         QAction tagAction = addContextAction("tag", tr("Tag"));
2463         contextMenu.addAction(tagAction);
2464         tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2465         
2466         QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2467         contextMenu.addAction(attributeAction);
2468         attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2469         
2470         QAction emailAction = addContextAction("email", tr("Email"));
2471         contextMenu.addAction(emailAction);
2472         emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2473
2474         QAction deleteAction = addContextAction("delete", tr("Delete"));
2475         contextMenu.addAction(deleteAction);
2476         deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2477
2478         QAction newAction = addContextAction("new", tr("Add"));
2479         contextMenu.addAction(newAction);
2480         newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2481
2482         QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2483         contextMenu.addAction(allNotesAction);
2484         allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2485         
2486         QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2487         contextMenu.addAction(searchClearAction);
2488         searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2489         
2490         return contextMenu;
2491         
2492     }
2493     private QAction addContextAction(String config, String name) {
2494         QAction newAction = new QAction(this);
2495                 newAction.setText(name);
2496                 newAction.setCheckable(true);
2497                 newAction.setChecked(Global.isToolbarButtonVisible(config));
2498                 return newAction;
2499     }
2500     private void togglePrevArrowButton(Boolean toggle) {
2501                 prevButton.setVisible(toggle);
2502                 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2503     }
2504     private void toggleNextArrowButton(Boolean toggle) {
2505                 nextButton.setVisible(toggle);
2506                 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2507     }
2508     private void toggleUpArrowButton(Boolean toggle) {
2509                 upButton.setVisible(toggle);
2510                 Global.saveToolbarButtonsVisible("upArrow", toggle);
2511     }
2512     private void toggleDownArrowButton(Boolean toggle) {
2513                 downButton.setVisible(toggle);
2514                 Global.saveToolbarButtonsVisible("downArrow", toggle);
2515     }
2516     private void toggleSynchronizeButton(Boolean toggle) {
2517                 synchronizeButton.setVisible(toggle);
2518                 Global.saveToolbarButtonsVisible("synchronize", toggle);
2519     }
2520     private void togglePrintButton(Boolean toggle) {
2521                 printButton.setVisible(toggle);
2522                 Global.saveToolbarButtonsVisible("print", toggle);
2523     }
2524     private void toggleTagButton(Boolean toggle) {
2525                 tagButton.setVisible(toggle);
2526                 Global.saveToolbarButtonsVisible("tag", toggle);
2527     }
2528     private void toggleAttributeButton(Boolean toggle) {
2529                 attributeButton.setVisible(toggle);
2530                 Global.saveToolbarButtonsVisible("attribute", toggle);
2531     }
2532     private void toggleEmailButton(Boolean toggle) {
2533                 emailButton.setVisible(toggle);
2534                 Global.saveToolbarButtonsVisible("email", toggle);
2535     }
2536     private void toggleDeleteButton(Boolean toggle) {
2537                 deleteButton.setVisible(toggle);
2538                 Global.saveToolbarButtonsVisible("delete", toggle);
2539     }
2540     private void toggleNewButton(Boolean toggle) {
2541                 newButton.setVisible(toggle);
2542                 Global.saveToolbarButtonsVisible("new", toggle);
2543     }
2544     private void toggleAllNotesButton(Boolean toggle) {
2545                 allNotesButton.setVisible(toggle);
2546                 Global.saveToolbarButtonsVisible("allNotes", toggle);
2547     }
2548     private void toggleSearchClearButton(Boolean toggle) {
2549                 searchClearButton.setVisible(toggle);
2550                 Global.saveToolbarButtonsVisible("searchClear", toggle);
2551     }
2552
2553
2554
2555
2556
2557     @SuppressWarnings("unused")
2558         private void updateSyncButton() {
2559  /*     synchronizeFrame++;
2560         if (synchronizeFrame == 4) 
2561                 synchronizeFrame = 0;
2562         synchronizeButton.setIcon(synchronizeAnimation.get(synchronizeFrame));
2563         */
2564 /*      
2565         QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2566         QMatrix matrix = new QMatrix();
2567         synchronizeIconAngle = synchronizeIconAngle + 1.0;
2568         if (synchronizeIconAngle >= 365.0)
2569                 synchronizeIconAngle = 0.0;
2570         matrix.translate(pix.size().width()/2, pix.size().height()/2);
2571                 matrix.rotate( synchronizeIconAngle );
2572         matrix.translate(-pix.size().width()/2, -pix.size().height()/2);
2573                 pix = pix.transformed(matrix, TransformationMode.SmoothTransformation);
2574         synchronizeButton.setIcon(pix);
2575 */
2576                 
2577         
2578         QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2579         QPixmap rotatedPix = new QPixmap(pix.size());
2580         QPainter p = new QPainter(rotatedPix);
2581
2582         rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2583         QSize size = pix.size();
2584         p.translate(size.width()/2, size.height()/2);
2585         synchronizeIconAngle = synchronizeIconAngle+1.0;
2586         if (synchronizeIconAngle >= 359.0)
2587                 synchronizeIconAngle = 0.0;
2588         p.rotate(synchronizeIconAngle);
2589         p.setBackgroundMode(BGMode.OpaqueMode);
2590         p.translate(-size.width()/2, -size.height()/2);
2591         p.drawPixmap(0,0, pix);
2592         p.end();
2593         synchronizeButton.setIcon(rotatedPix);
2594         
2595     }
2596     // Synchronize with Evernote
2597         @SuppressWarnings("unused")
2598         private void evernoteSync() {
2599         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2600         if (!Global.isConnected)
2601                 remoteConnect();
2602         if (Global.isConnected)
2603                 synchronizeAnimationTimer.start(10);
2604 //                      synchronizeAnimationTimer.start(200);
2605         syncTimer();
2606         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2607     }
2608     private void updateQuotaBar() {
2609         long limit = Global.getUploadLimit();
2610         long amount = Global.getUploadAmount();
2611         if (amount>0 && limit>0) {
2612                 int percent =(int)(amount*100/limit);
2613                 quotaBar.setValue(percent);
2614         } else 
2615                 quotaBar.setValue(0);
2616     }
2617         // Zoom changed
2618     @SuppressWarnings("unused")
2619         private void zoomChanged() {
2620         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2621     }
2622
2623     //****************************************************************
2624     //****************************************************************
2625     //* System Tray functions
2626     //****************************************************************
2627     //****************************************************************
2628         private void trayToggleVisible() {
2629         if (isVisible()) {
2630                 hide();
2631         } else {
2632                 show();
2633                 if (windowMaximized)
2634                         showMaximized();
2635                 else
2636                         showNormal();
2637                 raise();
2638         }
2639     }
2640     @SuppressWarnings("unused")
2641         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2642         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2643                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2644                 trayToggleVisible();
2645         }
2646     }
2647     
2648     
2649     //***************************************************************
2650     //***************************************************************
2651     //** These functions deal with the trash tree
2652     //***************************************************************
2653     //***************************************************************    
2654     // Setup the tree containing the trash.
2655     @SuppressWarnings("unused")
2656         private void trashTreeSelection() {     
2657         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2658         
2659         clearNotebookFilter();
2660         clearTagFilter();
2661         clearAttributeFilter();
2662         clearSavedSearchFilter();
2663         
2664         String tempGuid = currentNoteGuid;
2665         
2666 //      currentNoteGuid = "";
2667         currentNote = new Note();
2668         selectedNoteGUIDs.clear();
2669         listManager.getSelectedNotebooks().clear();
2670         listManager.getSelectedTags().clear();
2671         listManager.setSelectedSavedSearch("");
2672         browserWindow.clear();
2673     
2674         // toggle the add buttons
2675         newButton.setEnabled(!newButton.isEnabled());
2676         menuBar.noteAdd.setEnabled(newButton.isEnabled());
2677         menuBar.noteAdd.setVisible(true);
2678         
2679         List<QTreeWidgetItem> selections = trashTree.selectedItems();
2680         if (selections.size() == 0) {
2681                 currentNoteGuid = trashNoteGuid;
2682                         trashNoteGuid = tempGuid;
2683                 Global.showDeleted = false;
2684                 menuBar.noteRestoreAction.setEnabled(false);
2685                 menuBar.noteRestoreAction.setVisible(false);
2686         }
2687         else {
2688                 currentNoteGuid = trashNoteGuid;
2689                         trashNoteGuid = tempGuid;
2690                 menuBar.noteRestoreAction.setEnabled(true);
2691                 menuBar.noteRestoreAction.setVisible(true);
2692                 Global.showDeleted = true;
2693         }
2694         listManager.loadNotesIndex();
2695         noteIndexUpdated(false);
2696 ////            browserWindow.setEnabled(newButton.isEnabled());
2697         browserWindow.setReadOnly(!newButton.isEnabled());
2698         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2699     }
2700     // Empty the trash file
2701     @SuppressWarnings("unused")
2702         private void emptyTrash() {
2703 //      browserWindow.clear();
2704         listManager.emptyTrash();
2705         if (trashTree.selectedItems().size() > 0) {
2706                 listManager.getSelectedNotebooks().clear();
2707                 listManager.getSelectedTags().clear();
2708                 listManager.setSelectedSavedSearch("");
2709                 newButton.setEnabled(!newButton.isEnabled());
2710                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2711                 menuBar.noteAdd.setVisible(true);
2712                 browserWindow.clear();
2713                 
2714                 clearTagFilter();
2715                 clearNotebookFilter();
2716                 clearSavedSearchFilter();
2717                 clearAttributeFilter();
2718                         
2719                 Global.showDeleted = false;
2720                 menuBar.noteRestoreAction.setEnabled(false);
2721                 menuBar.noteRestoreAction.setVisible(false);
2722                 
2723                 listManager.loadNotesIndex();
2724 //--->>>                noteIndexUpdated(true);
2725                 noteIndexUpdated(false);
2726         }       
2727    }
2728     // Show/Hide trash window
2729         private void toggleTrashWindow() {
2730                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2731         if (trashTree.isVisible())
2732                 trashTree.hide();
2733         else
2734                 trashTree.show();
2735         menuBar.hideTrash.setChecked(trashTree.isVisible());
2736         
2737                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2738         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2739     }    
2740         private void clearTrashFilter() {
2741                 Global.showDeleted = false;
2742         newButton.setEnabled(true);
2743         menuBar.noteAdd.setEnabled(true);
2744         menuBar.noteAdd.setVisible(true);
2745                 trashTree.blockSignals(true);
2746                 trashTree.clearSelection();
2747                 trashTree.blockSignals(false);
2748                 
2749         }
2750     
2751    
2752     //***************************************************************
2753     //***************************************************************
2754     //** These functions deal with connection settings
2755     //***************************************************************
2756     //***************************************************************
2757         // SyncRunner had a problem and things are disconnected
2758         @SuppressWarnings("unused")
2759         private void remoteErrorDisconnect() {
2760                 menuBar.connectAction.setText(tr("Connect"));
2761                 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2762                 menuBar.synchronizeAction.setEnabled(false);
2763                 synchronizeAnimationTimer.stop();
2764                 return;
2765         }
2766         // Do a manual connect/disconnect
2767     private void remoteConnect() {
2768         logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2769
2770         if (Global.isConnected) {
2771                 Global.isConnected = false;
2772                 syncRunner.enDisconnect();
2773                 setupConnectMenuOptions();
2774                 setupOnlineMenu();
2775                 return;
2776         }
2777         
2778         AESEncrypter aes = new AESEncrypter();
2779         try {
2780                         aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
2781                 } catch (FileNotFoundException e) {
2782                         // File not found, so we'll just get empty strings anyway. 
2783                 }
2784                 String userid = aes.getUserid();
2785                 String password = aes.getPassword();
2786                 if (!userid.equals("") && !password.equals("")) {
2787                 Global.username = userid;
2788                 Global.password = password;
2789                 }               
2790
2791         // Show the login dialog box
2792                 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
2793                         LoginDialog login = new LoginDialog();
2794                         login.exec();
2795                 
2796                         if (!login.okPressed()) {
2797                                 return;
2798                         }
2799         
2800                         Global.username = login.getUserid();
2801                         Global.password = login.getPassword();
2802                 }
2803                 syncRunner.username = Global.username;
2804                 syncRunner.password = Global.password;
2805                 syncRunner.userStoreUrl = Global.userStoreUrl;
2806                 syncRunner.noteStoreUrl = Global.noteStoreUrl;
2807                 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
2808                 
2809             if (Global.getProxyValue("url").equals("")) {
2810                 System.setProperty("http.proxyHost","") ;
2811                 System.setProperty("http.proxyPort", "") ;
2812                 System.setProperty("https.proxyHost","") ;
2813                 System.setProperty("https.proxyPort", "") ;         
2814             } else {
2815                         // PROXY
2816                 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
2817                 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
2818                 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
2819                 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
2820          
2821                 if (Global.getProxyValue("userid").equals("")) {
2822                         Authenticator.setDefault(new Authenticator() {
2823                                 @Override
2824                                 protected PasswordAuthentication getPasswordAuthentication() {
2825                                         return new
2826                                         PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
2827                                         }});
2828                         }
2829                 }
2830                 
2831                 
2832                 syncRunner.enConnect();
2833                 Global.isConnected = syncRunner.isConnected;
2834                 setupOnlineMenu();
2835                 setupConnectMenuOptions();
2836                 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
2837     }
2838     private void setupConnectMenuOptions() {
2839         logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
2840                 if (!Global.isConnected) {
2841                         menuBar.connectAction.setText(tr("Connect"));
2842                         menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2843                         menuBar.synchronizeAction.setEnabled(false);
2844                 } else {
2845                         menuBar.connectAction.setText(tr("Disconnect"));
2846                         menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
2847                         menuBar.synchronizeAction.setEnabled(true);
2848                 }
2849                 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
2850     }
2851     
2852     
2853     
2854     //***************************************************************
2855     //***************************************************************
2856     //** These functions deal with the GUI Attribute tree
2857     //***************************************************************
2858     //***************************************************************    
2859     @SuppressWarnings("unused")
2860         private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
2861         
2862         clearTagFilter();
2863         clearNotebookFilter();
2864         clearTrashFilter();
2865         clearSavedSearchFilter();
2866
2867         if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
2868                 if (item.childCount() > 0) {
2869                         item.setSelected(false);
2870                 } else {
2871                 Global.createdBeforeFilter.reset();
2872                 Global.createdSinceFilter.reset();
2873                 Global.changedBeforeFilter.reset();
2874                 Global.changedSinceFilter.reset();
2875                 Global.containsFilter.reset();
2876                         attributeTreeSelected = item;
2877                         DateAttributeFilterTable f = null;
2878                         f = findDateAttributeFilterTable(item.parent());
2879                         if (f!=null)
2880                                 f.select(item.parent().indexOfChild(item));
2881                         else {
2882                                 Global.containsFilter.select(item.parent().indexOfChild(item));
2883                         }
2884                 }
2885                 listManager.loadNotesIndex();
2886                 noteIndexUpdated(false);
2887                 return;
2888         }
2889                 attributeTreeSelected = null;
2890                 item.setSelected(false);
2891         Global.createdBeforeFilter.reset();
2892         Global.createdSinceFilter.reset();
2893         Global.changedBeforeFilter.reset();
2894         Global.changedSinceFilter.reset();
2895         Global.containsFilter.reset();
2896         listManager.loadNotesIndex();
2897                 noteIndexUpdated(false); 
2898     }
2899     // This determines what attribute filter we need, depending upon the selection
2900     private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
2901                 if (w.parent() != null && w.childCount() > 0) {
2902                         QTreeWidgetItem parent = w.parent();
2903                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
2904                                 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2905                                         return Global.createdSinceFilter;
2906                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
2907                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2908                                         return Global.createdBeforeFilter;
2909                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
2910                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2911                                         return Global.changedSinceFilter;
2912                 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
2913                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2914                                                 return Global.changedBeforeFilter;
2915                 }
2916                 return null;
2917     }
2918
2919     // Show/Hide attribute search window
2920         private void toggleAttributesWindow() {
2921                 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
2922         if (attributeTree.isVisible())
2923                 attributeTree.hide();
2924         else
2925                 attributeTree.show();
2926         menuBar.hideAttributes.setChecked(attributeTree.isVisible());
2927         
2928                 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
2929         logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
2930     }    
2931         private void clearAttributeFilter() {
2932         Global.createdBeforeFilter.reset();
2933         Global.createdSinceFilter.reset();
2934         Global.changedBeforeFilter.reset();
2935         Global.changedSinceFilter.reset();
2936         Global.containsFilter.reset();
2937         attributeTreeSelected = null;
2938                 attributeTree.blockSignals(true);
2939                 attributeTree.clearSelection();
2940                 attributeTree.blockSignals(false);
2941         }
2942     
2943         
2944     //***************************************************************
2945     //***************************************************************
2946     //** These functions deal with the GUI Note index table
2947     //***************************************************************
2948     //***************************************************************    
2949     // Initialize the note list table
2950         private void initializeNoteTable() {
2951                 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
2952                 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
2953                 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
2954                 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
2955         }       
2956     // Show/Hide trash window
2957         @SuppressWarnings("unused")
2958         private void toggleNoteListWindow() {
2959                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
2960         if (noteTableView.isVisible())
2961                 noteTableView.hide();
2962         else
2963                 noteTableView.show();
2964         menuBar.hideNoteList.setChecked(noteTableView.isVisible());
2965         
2966                 Global.saveWindowVisible("noteList", noteTableView.isVisible());
2967         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
2968     }   
2969         // Handle the event that a user selects a note from the table
2970     @SuppressWarnings("unused")
2971         private void noteTableSelection() {
2972                 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
2973                 saveNote();
2974                 if (historyGuids.size() == 0) {
2975                         historyGuids.add(currentNoteGuid);
2976                         historyPosition = 1;
2977                 }
2978         noteTableView.showColumn(Global.noteTableGuidPosition);
2979         
2980         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2981         if (!Global.isColumnVisible("guid"))
2982                 noteTableView.hideColumn(Global.noteTableGuidPosition);
2983         
2984         if (selections.size() > 0) {
2985                 QModelIndex index;
2986                 menuBar.noteDuplicateAction.setEnabled(true);
2987                 menuBar.noteOnlineHistoryAction.setEnabled(true);
2988                 menuBar.noteMergeAction.setEnabled(true);
2989                 selectedNoteGUIDs.clear();
2990                 if (selections.size() != 1 || Global.showDeleted) {
2991                         menuBar.noteDuplicateAction.setEnabled(false);
2992                 }
2993                 if (selections.size() != 1 || !Global.isConnected) {
2994                         menuBar.noteOnlineHistoryAction.setEnabled(false);
2995                 }
2996                 if (selections.size() == 1) {
2997                         menuBar.noteMergeAction.setEnabled(false);
2998                 }
2999                 for (int i=0; i<selections.size(); i++) {
3000                         int row = selections.get(i).row();
3001                         if (row == 0) 
3002                                 upButton.setEnabled(false);
3003                         else
3004                                 upButton.setEnabled(true);
3005                         if (row < listManager.getNoteTableModel().rowCount()-1)
3006                                 downButton.setEnabled(true);
3007                         else
3008                                 downButton.setEnabled(false);
3009                         index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3010                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3011                         currentNoteGuid = (String)ix.values().toArray()[0];
3012                         selectedNoteGUIDs.add(currentNoteGuid);
3013                 }
3014         }
3015         
3016         nextButton.setEnabled(true);
3017                 prevButton.setEnabled(true);
3018         if (!fromHistory) {
3019                 int endPosition = historyGuids.size()-1;
3020                 for (int j=historyPosition; j<=endPosition; j++) {
3021                         historyGuids.remove(historyGuids.size()-1);
3022                 }
3023                 historyGuids.add(currentNoteGuid);
3024                 historyPosition = historyGuids.size();
3025         } 
3026         if (historyPosition <= 1)
3027                 prevButton.setEnabled(false);
3028         if (historyPosition == historyGuids.size())
3029                 nextButton.setEnabled(false);
3030                 
3031         fromHistory = false;
3032         scrollToGuid(currentNoteGuid);
3033         refreshEvernoteNote(true);
3034                 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3035     }    
3036         // Trigger a refresh when the note db has been updated
3037         private void noteIndexUpdated(boolean reload) {
3038                 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3039                 saveNote();
3040         refreshEvernoteNoteList();
3041         logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3042         noteTableView.load(reload);
3043         scrollToGuid(currentNoteGuid);
3044                 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3045     }
3046         // Called when the list of notes is updated
3047     private void refreshEvernoteNoteList() {
3048         logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3049         browserWindow.setDisabled(false);
3050                 if (selectedNoteGUIDs == null)
3051                         selectedNoteGUIDs = new ArrayList<String>();
3052                 selectedNoteGUIDs.clear();  // clear out old entries
3053                 
3054                 String saveCurrentNoteGuid = new String();
3055                 String tempNoteGuid = new String();
3056                                 
3057                 historyGuids.clear();
3058                 historyPosition = 0;
3059                 prevButton.setEnabled(false);
3060                 nextButton.setEnabled(false);
3061                 
3062                 if (currentNoteGuid == null) 
3063                         currentNoteGuid = new String();
3064                 
3065                 //determine current note guid
3066                 for (Note note : listManager.getNoteIndex()) {
3067                         tempNoteGuid = note.getGuid();
3068                         if (currentNoteGuid.equals(tempNoteGuid)) {
3069                                 saveCurrentNoteGuid = tempNoteGuid;
3070                         }
3071                 }
3072                 
3073                 if (listManager.getNoteIndex().size() == 0) {
3074                         currentNoteGuid = "";
3075                         currentNote = null;
3076                         browserWindow.clear();
3077                         browserWindow.setDisabled(true);
3078                 } 
3079                 
3080                 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() > 0) {
3081                         currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
3082                         currentNoteGuid = currentNote.getGuid();
3083                         refreshEvernoteNote(true);
3084                 } else {
3085                         //we can reload if note not dirty
3086                         refreshEvernoteNote(!noteDirty);
3087                 }
3088                 reloadTagTree(false);
3089
3090                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3091         } 
3092     // Called when the previous arrow button is clicked 
3093     @SuppressWarnings("unused")
3094         private void previousViewedAction() {
3095         if (!prevButton.isEnabled())
3096                 return;
3097         if (historyPosition == 0)
3098                 return;
3099                 historyPosition--;
3100         if (historyPosition <= 0)
3101                 return;
3102         String historyGuid = historyGuids.get(historyPosition-1);
3103         fromHistory = true;
3104         for (int i=0; i<noteTableView.model().rowCount(); i++) {
3105                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
3106                 if (modelIndex != null) {
3107                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3108                         String tableGuid =  (String)ix.values().toArray()[0];
3109                         if (tableGuid.equals(historyGuid)) {
3110                                 noteTableView.selectRow(i);