OSDN Git Service

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