OSDN Git Service

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