OSDN Git Service

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