OSDN Git Service

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