OSDN Git Service

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