OSDN Git Service

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