OSDN Git Service

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