OSDN Git Service

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