OSDN Git Service

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