OSDN Git Service

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