OSDN Git Service

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