OSDN Git Service

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