OSDN Git Service

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