OSDN Git Service

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