OSDN Git Service

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