OSDN Git Service

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