OSDN Git Service

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