OSDN Git Service

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