OSDN Git Service

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