OSDN Git Service

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