OSDN Git Service

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