OSDN Git Service

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