OSDN Git Service

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