OSDN Git Service

5842a5c2a22da1460d9c95cd18b567686275e2ef
[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 - bypassing");
968                 } catch (InterruptedException e1) {
969                         e1.printStackTrace();
970                 }
971                 if (!syncRunner.isIdle()) {
972                         try {
973                                 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
974                                 syncThread.join();
975                                 logger.log(logger.MEDIUM, "Sync thread has stopped");
976                         } catch (InterruptedException e1) {
977                                 e1.printStackTrace();
978                         }
979                 }
980
981                 if (encryptOnShutdown) {
982                         encryptOnShutdown();
983                 }
984                 if (decryptOnShutdown) {
985                         decryptOnShutdown();
986                 }
987                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
988         }
989
990         @SuppressWarnings("unused")
991         private void closeNeverNote() {
992                 closeAction = true;
993                 close();
994         }
995         public void setMessage(String s) {
996                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
997                 logger.log(logger.HIGH, "Message: " +s);
998                 statusBar.showMessage(s);
999                 emitLog.add(s);
1000                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1001         }
1002                 
1003         private void waitCursor(boolean wait) {
1004                 if (wait) {
1005                         if (QApplication.overrideCursor() == null)
1006                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1007                 }
1008                 else {
1009                         while (QApplication.overrideCursor() != null)
1010                                 QApplication.restoreOverrideCursor();
1011                 }
1012         }
1013         
1014         private void setupIndexListeners() {
1015 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1016 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1017                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1018                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1019         }
1020         private void setupSyncSignalListeners() {
1021                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1022         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1023         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1024         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1025         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1026         
1027                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1028                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1029                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1030                 
1031                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1032                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1033                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1034                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1035                 
1036                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1037         }
1038         
1039         private void setupBrowserSignalListeners() {
1040                 setupBrowserWindowListeners(browserWindow, true);
1041         }
1042
1043         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1044                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1045                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1046             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1047             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1048             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1049             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1050             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1051             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1052             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1053             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1054             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1055             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1056             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1057             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1058             if (master) browser.focusLost.connect(this, "saveNote()");
1059             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1060         }
1061
1062         //***************************************************************
1063         //***************************************************************
1064         //* Settings and look & feel
1065         //***************************************************************
1066         //***************************************************************
1067         @SuppressWarnings("unused")
1068         private void settings() {
1069                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1070                 saveNoteColumnPositions();
1071                 saveNoteIndexWidth();
1072                 showColumns();
1073         ConfigDialog settings = new ConfigDialog(this);
1074         String dateFormat = Global.getDateFormat();
1075         String timeFormat = Global.getTimeFormat();
1076         
1077                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1078                 indexTimer.start(indexTime);  // reset indexing timer
1079         
1080         settings.exec();
1081         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1082         if (Global.showTrayIcon())
1083                 trayIcon.show();
1084         else
1085                 trayIcon.hide();
1086         showColumns();
1087         if (menuBar.showEditorBar.isChecked())
1088                 showEditorButtons(browserWindow);
1089         
1090         // Reset the save timer
1091         if (Global.getAutoSaveInterval() > 0)
1092                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1093         else
1094                 saveTimer.stop();
1095         
1096         // This is a hack to force a reload of the index in case the date or time changed.
1097 //        if (!dateFormat.equals(Global.getDateFormat()) ||
1098 //                      !timeFormat.equals(Global.getTimeFormat())) {
1099                 noteCache.clear();
1100                 readOnlyCache.clear();
1101                 inkNoteCache.clear();
1102                 noteIndexUpdated(true);
1103 //        }
1104         
1105         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1106         }
1107         // Restore things to the way they were
1108         private void restoreWindowState(boolean mainWindow) {
1109                 // We need to name things or this doesn't work.
1110                 setObjectName("NeverNote");
1111                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1112                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1113                 leftSplitter1.setObjectName("leftSplitter1");   
1114                 
1115                 // Restore the actual positions.
1116                 if (mainWindow)
1117                         restoreGeometry(Global.restoreGeometry(objectName()));
1118         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1119         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1120         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1121        
1122         }
1123         // Save window positions for the next start
1124         private void saveWindowState() {
1125                 Global.saveGeometry(objectName(), saveGeometry());
1126                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1127                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1128                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1129         }    
1130         // Load the style sheet
1131         private void loadStyleSheet() {
1132                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1133                 fileName = Global.getFileManager().getQssDirPath("default.qss");
1134                 QFile file = new QFile(fileName);
1135                 
1136                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1137                 if (!file.exists()) {
1138                         fileName = Global.getFileManager().getQssDirPath("default.qss");
1139                         file = new QFile(fileName);
1140                 }
1141                 file.open(OpenModeFlag.ReadOnly);
1142                 String styleSheet = file.readAll().toString();
1143                 file.close();
1144                 setStyleSheet(styleSheet);
1145         }
1146         // Save column positions for the next time
1147         private void saveNoteColumnPositions() {
1148                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1149                 Global.setColumnPosition("noteTableCreationPosition", position);
1150                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1151                 Global.setColumnPosition("noteTableTagPosition", position);
1152                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1153                 Global.setColumnPosition("noteTableNotebookPosition", position);
1154                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1155                 Global.setColumnPosition("noteTableChangedPosition", position);
1156                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1157                 Global.setColumnPosition("noteTableAuthorPosition", position);
1158                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1159                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1160                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1161                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1162                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1163                 Global.setColumnPosition("noteTableTitlePosition", position);
1164                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1165                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1166                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1167                 Global.setColumnPosition("noteTableGuidPosition", position);
1168                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1169                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1170
1171         }
1172         // Save column widths for the next time
1173         private void saveNoteIndexWidth() {
1174                 int width;
1175         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1176         Global.setColumnWidth("noteTableCreationPosition", width);
1177                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1178                 Global.setColumnWidth("noteTableChangedPosition", width);
1179                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1180                 Global.setColumnWidth("noteTableGuidPosition", width);
1181                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1182                 Global.setColumnWidth("noteTableNotebookPosition", width);
1183                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1184                 Global.setColumnWidth("noteTableTagPosition", width);
1185                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1186                 Global.setColumnWidth("noteTableTitlePosition", width);
1187                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1188                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1189                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1190                 Global.setColumnWidth("noteTableAuthorPosition", width);
1191                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1192                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1193                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1194                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1195                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1196                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1197                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1198                 Global.setColumnWidth("noteTableGuidPosition", width);
1199         }
1200         
1201         
1202     //***************************************************************
1203     //***************************************************************
1204     //** These functions deal with Notebook menu items
1205     //***************************************************************
1206     //***************************************************************
1207     // Setup the tree containing the user's notebooks.
1208     private void initializeNotebookTree() {       
1209         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1210 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1211         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1212         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1213         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1214     }   
1215     // Listener when a notebook is selected
1216         private void notebookTreeSelection() {
1217                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1218
1219                 clearTrashFilter();
1220                 clearAttributeFilter();
1221                 clearSavedSearchFilter();
1222                 if (Global.mimicEvernoteInterface) {
1223                         clearTagFilter();
1224                         searchField.clear();
1225                 }
1226                 menuBar.noteRestoreAction.setVisible(false);            
1227         menuBar.notebookEditAction.setEnabled(true);
1228         menuBar.notebookDeleteAction.setEnabled(true);
1229         menuBar.notebookPublishAction.setEnabled(true);
1230         menuBar.notebookShareAction.setEnabled(true);
1231         menuBar.notebookIconAction.setEnabled(true);
1232         menuBar.notebookStackAction.setEnabled(true);
1233         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1234         selectedNotebookGUIDs.clear();
1235                 String guid = "";
1236                 String stackName = "";
1237                 if (selections.size() > 0) {
1238                 guid = (selections.get(0).text(2));
1239                 stackName = selections.get(0).text(0);
1240         }
1241                 if (!Global.mimicEvernoteInterface) {
1242                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1243                         if (selections.size()==0) {
1244                                 selectedNotebookGUIDs.clear();
1245                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1246                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1247                                 }
1248                                 menuBar.notebookEditAction.setEnabled(false);
1249                                 menuBar.notebookDeleteAction.setEnabled(false);
1250                                 menuBar.notebookStackAction.setEnabled(false);
1251                                 menuBar.notebookIconAction.setEnabled(false);
1252                         }
1253                 }
1254         if (!guid.equals("") && !guid.equals("STACK")) {
1255                 selectedNotebookGUIDs.add(guid);
1256                 menuBar.notebookIconAction.setEnabled(true);
1257         } else {
1258                 menuBar.notebookIconAction.setEnabled(true);
1259                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1260                                 Notebook book = listManager.getNotebookIndex().get(j);
1261                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1262                                         selectedNotebookGUIDs.add(book.getGuid());
1263                         }
1264         }
1265         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1266         listManager.loadNotesIndex();
1267         noteIndexUpdated(false);
1268                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1269
1270     }
1271     private void clearNotebookFilter() {
1272         notebookTree.blockSignals(true);
1273         notebookTree.clearSelection();
1274                 menuBar.noteRestoreAction.setVisible(false);
1275         menuBar.notebookEditAction.setEnabled(false);
1276         menuBar.notebookDeleteAction.setEnabled(false);
1277         selectedNotebookGUIDs.clear();
1278         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1279         notebookTree.blockSignals(false);
1280     }
1281         // Triggered when the notebook DB has been updated
1282         private void notebookIndexUpdated() {
1283                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1284         
1285                 // Get the possible icons
1286                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1287         notebookTree.setIcons(icons);
1288         
1289         if (selectedNotebookGUIDs == null)
1290                         selectedNotebookGUIDs = new ArrayList<String>();
1291                 List<Notebook> books = conn.getNotebookTable().getAll();
1292                 for (int i=books.size()-1; i>=0; i--) {
1293                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1294                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1295                                         books.remove(i);
1296                                         j=listManager.getArchiveNotebookIndex().size();
1297                                 }
1298                         }
1299                 }
1300                 
1301                 
1302                 listManager.countNotebookResults(listManager.getNoteIndex());
1303                 notebookTree.blockSignals(true);
1304         notebookTree.load(books, listManager.getLocalNotebooks());
1305         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1306                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1307                 if (!found)
1308                         selectedNotebookGUIDs.remove(i);
1309         }
1310         notebookTree.blockSignals(false);
1311         
1312                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1313     }
1314     // Show/Hide note information
1315         private void toggleNotebookWindow() {
1316                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1317         if (notebookTree.isVisible())
1318                 notebookTree.hide();
1319         else
1320                 notebookTree.show();
1321         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1322         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1323         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1324     }   
1325         // Add a new notebook
1326         @SuppressWarnings("unused")
1327         private void addNotebook() {
1328                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1329                 NotebookEdit edit = new NotebookEdit();
1330                 edit.setNotebooks(listManager.getNotebookIndex());
1331                 edit.exec();
1332         
1333                 if (!edit.okPressed())
1334                         return;
1335         
1336                 Calendar currentTime = new GregorianCalendar();
1337                 Long l = new Long(currentTime.getTimeInMillis());
1338                 String randint = new String(Long.toString(l));
1339         
1340                 Notebook newBook = new Notebook();
1341                 newBook.setUpdateSequenceNum(0);
1342                 newBook.setGuid(randint);
1343                 newBook.setName(edit.getNotebook());
1344                 newBook.setServiceCreated(new Date().getTime());
1345                 newBook.setServiceUpdated(new Date().getTime());
1346                 newBook.setDefaultNotebook(false);
1347                 newBook.setPublished(false);
1348                 
1349                 listManager.getNotebookIndex().add(newBook);
1350                 if (edit.isLocal())
1351                         listManager.getLocalNotebooks().add(newBook.getGuid());
1352                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1353                 notebookIndexUpdated();
1354                 listManager.countNotebookResults(listManager.getNoteIndex());
1355 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1356                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1357         }
1358         // Edit an existing notebook
1359         @SuppressWarnings("unused")
1360         private void stackNotebook() {
1361                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1362                 StackNotebook edit = new StackNotebook();
1363                 
1364                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1365                 QTreeWidgetItem currentSelection;
1366                 for (int i=0; i<selections.size(); i++) {
1367                         currentSelection = selections.get(0);
1368                         String guid = currentSelection.text(2);
1369                         if (guid.equalsIgnoreCase("")) {
1370                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1371                                  return;
1372                         }
1373                         if (guid.equalsIgnoreCase("STACK")) {
1374                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1375                                  return;
1376                         }
1377                 }
1378
1379                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1380
1381                 
1382                 edit.exec();
1383         
1384                 if (!edit.okPressed())
1385                         return;
1386         
1387                 String stack = edit.getStackName();
1388                 
1389                 for (int i=0; i<selections.size(); i++) {
1390                         currentSelection = selections.get(i);
1391                         String guid = currentSelection.text(2);
1392                         listManager.updateNotebookStack(guid, stack);
1393                 }
1394                 notebookIndexUpdated();
1395                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1396         }
1397         // Edit an existing notebook
1398         @SuppressWarnings("unused")
1399         private void editNotebook() {
1400                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1401                 NotebookEdit edit = new NotebookEdit();
1402                 
1403                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1404                 QTreeWidgetItem currentSelection;
1405                 currentSelection = selections.get(0);
1406                 edit.setNotebook(currentSelection.text(0));
1407                 
1408                 String guid = currentSelection.text(2);
1409                 if (!guid.equalsIgnoreCase("STACK")) {
1410                         edit.setTitle(tr("Edit Notebook"));
1411                         edit.setNotebooks(listManager.getNotebookIndex());
1412                         edit.setLocalCheckboxEnabled(false);
1413                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1414                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1415                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1416                                         i=listManager.getNotebookIndex().size();
1417                                 }
1418                         }
1419                 } else {
1420                         edit.setTitle(tr("Edit Stack"));
1421                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1422                         edit.hideLocalCheckbox();
1423                         edit.hideDefaultCheckbox();
1424                 }
1425                 
1426                 edit.exec();
1427         
1428                 if (!edit.okPressed())
1429                         return;
1430         
1431                 
1432                 if (guid.equalsIgnoreCase("STACK")) {
1433                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1434                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1435                                 if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1436                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1437                         }
1438                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1439                         currentSelection.setText(0, edit.getNotebook());
1440                         return;
1441                 }
1442                 
1443                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1444                 currentSelection.setText(0, edit.getNotebook());
1445                 
1446                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1447                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1448                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1449                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1450                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1451                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1452                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1453                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1454                                 }
1455                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1456                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1457                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1458                                         linkedNotebook.setShareName(edit.getNotebook());
1459                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1460                                 }
1461                                 i=listManager.getNotebookIndex().size();
1462                         }
1463                 }
1464                 
1465                 // Build a list of non-closed notebooks
1466                 List<Notebook> nbooks = new ArrayList<Notebook>();
1467                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1468                         boolean found=false;
1469                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1470                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1471                                         found = true;
1472                         }
1473                         if (!found)
1474                                 nbooks.add(listManager.getNotebookIndex().get(i));
1475                 }
1476                 
1477                 
1478                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1479                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1480                 browserWindow.setNotebookList(filteredBooks);
1481                 Iterator<String> set = externalWindows.keySet().iterator();
1482                 while(set.hasNext())
1483                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1484                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1485         }
1486         // Publish a notebook
1487         @SuppressWarnings("unused")
1488         private void publishNotebook() {
1489                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1490                 QTreeWidgetItem currentSelection;
1491                 currentSelection = selections.get(0);
1492                 String guid = currentSelection.text(2);
1493
1494                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1495                         return;
1496                 
1497                 Notebook n = null;
1498                 int position = 0;
1499                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1500                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1501                                 n = listManager.getNotebookIndex().get(i);
1502                                 position = i;
1503                                 i = listManager.getNotebookIndex().size();
1504                         }
1505                 }
1506                 if (n == null)
1507                         return;
1508                 
1509                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1510                 publish.exec();
1511                 
1512                 if (!publish.okClicked()) 
1513                         return;
1514                 
1515                 Publishing p = publish.getPublishing();
1516                 boolean isPublished = !publish.isStopPressed();
1517                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1518                 n.setPublished(isPublished);
1519                 n.setPublishing(p);
1520                 listManager.getNotebookIndex().set(position, n);
1521                 notebookIndexUpdated();
1522         }
1523         // Publish a notebook
1524         @SuppressWarnings("unused")
1525         private void shareNotebook() {
1526                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1527                 QTreeWidgetItem currentSelection;
1528                 currentSelection = selections.get(0);
1529                 String guid = currentSelection.text(2);
1530
1531                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1532                         return;
1533                 
1534                 Notebook n = null;;
1535                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1536                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1537                                 n = listManager.getNotebookIndex().get(i);
1538                                 i = listManager.getNotebookIndex().size();
1539                         }
1540                 }
1541                                 
1542                 String authToken = null;
1543                 if (syncRunner.isConnected)
1544                         authToken = syncRunner.authToken;
1545                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1546                 share.exec();
1547                 
1548         }
1549
1550         // Delete an existing notebook
1551         @SuppressWarnings("unused")
1552         private void deleteNotebook() {
1553                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1554                 boolean stacksFound = false;
1555                 boolean notebooksFound = false;
1556                 boolean assigned = false;
1557                 // Check if any notes have this notebook
1558                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1559         for (int i=0; i<selections.size(); i++) {
1560                 QTreeWidgetItem currentSelection;
1561                 currentSelection = selections.get(i);
1562                 String guid = currentSelection.text(2);
1563                 if (!guid.equalsIgnoreCase("STACK")) {
1564                         notebooksFound = true;
1565                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1566                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1567                                 if (noteGuid.equals(guid)) {
1568                                         assigned = true;
1569                                         j=listManager.getNoteIndex().size();
1570                                         i=selections.size();
1571                                 }
1572                         }
1573                 } else {
1574                         stacksFound = true;
1575                 }
1576         }
1577                 if (assigned) {
1578                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1579                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1580                         return;
1581                 }
1582                 
1583                 if (conn.getNotebookTable().getAll().size() == 1) {
1584                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1585                         return;
1586                 }
1587         
1588         // If all notebooks are clear, verify the delete
1589                 String msg1 = new String(tr("Delete selected notebooks?"));
1590                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1591                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1592                                 " not deleted unless selected?"));
1593                 String msg = "";
1594                 if (stacksFound && notebooksFound)
1595                         msg = msg3;
1596                 if (!stacksFound && notebooksFound)
1597                         msg = msg1;
1598                 if (stacksFound && !notebooksFound)
1599                         msg = msg2;
1600                 if (QMessageBox.question(this, tr("Confirmation"), msg,
1601                         QMessageBox.StandardButton.Yes, 
1602                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1603                         return;
1604                 }
1605                 
1606                 // If confirmed, delete the notebook
1607         for (int i=selections.size()-1; i>=0; i--) {
1608                 QTreeWidgetItem currentSelection;
1609                 currentSelection = selections.get(i);
1610                 String guid = currentSelection.text(2);
1611                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1612                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1613                         listManager.renameStack(currentSelection.text(0), "");
1614                 } else {
1615                         conn.getNotebookTable().expungeNotebook(guid, true);
1616                         listManager.deleteNotebook(guid);
1617                 }
1618         }
1619
1620                 notebookIndexUpdated();
1621 //        notebookTreeSelection();
1622 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1623 //        listManager.countNotebookResults(listManager.getNoteIndex());
1624         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1625         }
1626         // A note's notebook has been updated
1627         @SuppressWarnings("unused")
1628         private void updateNoteNotebook(String guid, String notebookGuid) {
1629                 
1630                 // Update the list manager
1631                 listManager.updateNoteNotebook(guid, notebookGuid);
1632                 listManager.countNotebookResults(listManager.getNoteIndex());
1633 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1634                 
1635                 // Find the name of the notebook
1636                 String notebookName = null;
1637                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1638                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1639                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1640                                 break;
1641                         }
1642                 }
1643                 
1644                 // If we found the name, update the browser window
1645                 if (notebookName != null) {
1646                         updateListNoteNotebook(guid, notebookName);
1647                         if (guid.equals(currentNoteGuid)) {
1648                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1649                                 if (pos >=0)
1650                                         browserWindow.notebookBox.setCurrentIndex(pos);
1651                         }
1652                 }
1653                 
1654                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1655                 if (guid.equals(currentNoteGuid)) {
1656                         if (currentNote != null) {
1657                                 currentNote.setNotebookGuid(notebookGuid);
1658                         }
1659                 }
1660         }
1661         // Open/close notebooks
1662         @SuppressWarnings("unused")
1663         private void closeNotebooks() {
1664                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1665                 na.exec();
1666                 if (!na.okClicked())
1667                         return;
1668                 
1669                 waitCursor(true);
1670                 listManager.getArchiveNotebookIndex().clear();
1671                 
1672                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1673                         String text = na.getClosedBookList().takeItem(i).text();
1674                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1675                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1676                                         Notebook n = listManager.getNotebookIndex().get(j);
1677                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1678                                         listManager.getArchiveNotebookIndex().add(n);
1679                                         j=listManager.getNotebookIndex().size();
1680                                 }
1681                         }
1682                 }
1683                 
1684                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1685                         String text = na.getOpenBookList().takeItem(i).text();
1686                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1687                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1688                                         Notebook n = listManager.getNotebookIndex().get(j);
1689                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1690                                         j=listManager.getNotebookIndex().size();
1691                                 }
1692                         }
1693                 }
1694                 notebookTreeSelection();
1695                 listManager.loadNotesIndex();
1696                 notebookIndexUpdated();
1697                 noteIndexUpdated(false);
1698                 reloadTagTree(true);
1699 //              noteIndexUpdated(false);
1700                 
1701                 // Build a list of non-closed notebooks
1702                 List<Notebook> nbooks = new ArrayList<Notebook>();
1703                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1704                         boolean found=false;
1705                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1706                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1707                                         found = true;
1708                         }
1709                         if (!found)
1710                                 nbooks.add(listManager.getNotebookIndex().get(i));
1711                 }
1712                 
1713                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1714                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1715                 browserWindow.setNotebookList(filteredBooks);
1716                 
1717                 // Update any external windows
1718                 Iterator<String> set = externalWindows.keySet().iterator();
1719                 while(set.hasNext())
1720                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1721                 
1722                 waitCursor(false);
1723         }
1724         // Change the notebook's icon
1725         @SuppressWarnings("unused")
1726         private void setNotebookIcon() {
1727                 boolean stackSelected = false;
1728                 boolean allNotebookSelected = false;
1729                 
1730                 QTreeWidgetItem currentSelection;
1731                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1732                 if (selections.size() == 0)
1733                         return;
1734                 
1735                 currentSelection = selections.get(0);   
1736                 String guid = currentSelection.text(2);
1737                 if (guid.equalsIgnoreCase(""))
1738                         allNotebookSelected = true;
1739                 if (guid.equalsIgnoreCase("STACK"))
1740                         stackSelected = true;
1741
1742                 QIcon currentIcon = currentSelection.icon(0);
1743                 QIcon icon;
1744                 SetIcon dialog;
1745                 
1746                 if (!stackSelected && !allNotebookSelected) {
1747                         icon = conn.getNotebookTable().getIcon(guid);
1748                         if (icon == null) {
1749                                 dialog = new SetIcon(currentIcon, saveLastPath);
1750                                 dialog.setUseDefaultIcon(true);
1751                         } else {
1752                                 dialog = new SetIcon(icon, saveLastPath);
1753                                 dialog.setUseDefaultIcon(false);
1754                         }
1755                 } else {
1756                         if (stackSelected) {
1757                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1758                         } else {
1759                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
1760                         }
1761                         if (icon == null) {
1762                                 dialog = new SetIcon(currentIcon, saveLastPath);
1763                                 dialog.setUseDefaultIcon(true);
1764                         } else {
1765                                 dialog = new SetIcon(icon, saveLastPath);
1766                                 dialog.setUseDefaultIcon(false);
1767                         }
1768                 }
1769                 dialog.exec();
1770                 if (dialog.okPressed()) {
1771                 saveLastPath = dialog.getPath();
1772
1773                         QIcon newIcon = dialog.getIcon();
1774                         if (stackSelected) {
1775                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1776                                 if (newIcon == null) {
1777                                         newIcon = new QIcon(iconPath+"books2.png");
1778                                 }
1779                                 currentSelection.setIcon(0,newIcon);
1780                                 return;
1781                         }
1782                         if (allNotebookSelected) {
1783                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1784                                 if (newIcon == null) {
1785                                         newIcon = new QIcon(iconPath+"notebook-green.png");
1786                                 }
1787                                 currentSelection.setIcon(0,newIcon);
1788                                 return;
1789                         }
1790                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1791                         if (newIcon == null) {
1792                                 boolean isPublished = false;;
1793                                 boolean found = false;
1794                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1795                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1796                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1797                                                 found = true;
1798                                         }
1799                                 }
1800                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1801                         }
1802                         currentSelection.setIcon(0, newIcon);
1803                 }
1804         
1805         }
1806         
1807         
1808     //***************************************************************
1809     //***************************************************************
1810     //** These functions deal with Tag menu items
1811     //***************************************************************
1812     //***************************************************************
1813         // Add a new notebook
1814         @SuppressWarnings("unused")
1815         private void addTag() {
1816                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1817                 TagEdit edit = new TagEdit();
1818                 edit.setTagList(listManager.getTagIndex());
1819                 edit.exec();
1820         
1821                 if (!edit.okPressed())
1822                         return;
1823         
1824                 Calendar currentTime = new GregorianCalendar();
1825                 Long l = new Long(currentTime.getTimeInMillis());
1826                 String randint = new String(Long.toString(l));
1827         
1828                 Tag newTag = new Tag();
1829                 newTag.setUpdateSequenceNum(0);
1830                 newTag.setGuid(randint);
1831                 newTag.setName(edit.getTag());
1832                 conn.getTagTable().addTag(newTag, true);
1833                 listManager.getTagIndex().add(newTag);
1834                 reloadTagTree(true);
1835                 
1836                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1837         }
1838         @SuppressWarnings("unused")
1839         private void reloadTagTree() {
1840                 reloadTagTree(false);
1841         }
1842         private void reloadTagTree(boolean reload) {
1843                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1844                 tagIndexUpdated(reload);
1845                 boolean filter = false;
1846                 listManager.countTagResults(listManager.getNoteIndex());
1847                 if (notebookTree.selectedItems().size() > 0 
1848                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1849                                                   filter = true;
1850                 if (tagTree.selectedItems().size() > 0)
1851                         filter = true;
1852                 tagTree.showAllTags(!filter);
1853                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1854         }
1855         // Edit an existing tag
1856         @SuppressWarnings("unused")
1857         private void editTag() {
1858                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1859                 TagEdit edit = new TagEdit();
1860                 edit.setTitle("Edit Tag");
1861                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1862                 QTreeWidgetItem currentSelection;
1863                 currentSelection = selections.get(0);
1864                 edit.setTag(currentSelection.text(0));
1865                 edit.setTagList(listManager.getTagIndex());
1866                 edit.exec();
1867         
1868                 if (!edit.okPressed())
1869                         return;
1870         
1871                 String guid = currentSelection.text(2);
1872                 currentSelection.setText(0,edit.getTag());
1873                 
1874                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1875                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1876                                 listManager.getTagIndex().get(i).setName(edit.getTag());
1877                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1878                                 updateListTagName(guid);
1879                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1880                                         browserWindow.setTag(getTagNamesForNote(currentNote));
1881                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1882                                 return;
1883                         }
1884                 }
1885                 browserWindow.setTag(getTagNamesForNote(currentNote));
1886                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1887         }
1888         // Delete an existing tag
1889         @SuppressWarnings("unused")
1890         private void deleteTag() {
1891                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1892                 
1893                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1894                         QMessageBox.StandardButton.Yes, 
1895                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1896                                                         return;
1897                 }
1898                 
1899                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1900         for (int i=selections.size()-1; i>=0; i--) {
1901                 QTreeWidgetItem currentSelection;
1902                 currentSelection = selections.get(i);                   
1903                 removeTagItem(currentSelection.text(2));
1904         }
1905         tagIndexUpdated(true);
1906         tagTreeSelection();
1907         listManager.countTagResults(listManager.getNoteIndex());
1908 //              tagTree.updateCounts(listManager.getTagCounter());
1909         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1910         }
1911         // Remove a tag tree item.  Go recursively down & remove the children too
1912         private void removeTagItem(String guid) {
1913         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
1914                 String parent = listManager.getTagIndex().get(j).getParentGuid();
1915                 if (parent != null && parent.equals(guid)) {            
1916                         //Remove this tag's children
1917                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
1918                 }
1919         }
1920         //Now, remove this tag
1921         removeListTagName(guid);
1922         conn.getTagTable().expungeTag(guid, true);                      
1923         for (int a=0; a<listManager.getTagIndex().size(); a++) {
1924                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1925                         listManager.getTagIndex().remove(a);
1926                         return;
1927                 }
1928         }
1929         }
1930         // Setup the tree containing the user's tags
1931     private void initializeTagTree() {
1932         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1933 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1934 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
1935         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1936         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1937         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1938     }
1939     // Listener when a tag is selected
1940         private void tagTreeSelection() {
1941         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1942                 
1943         clearTrashFilter();
1944         clearAttributeFilter();
1945         clearSavedSearchFilter();
1946         
1947                 menuBar.noteRestoreAction.setVisible(false);
1948                 
1949         List<QTreeWidgetItem> selections = tagTree.selectedItems();
1950         QTreeWidgetItem currentSelection;
1951         selectedTagGUIDs.clear();
1952         for (int i=0; i<selections.size(); i++) {
1953                 currentSelection = selections.get(i);
1954                 selectedTagGUIDs.add(currentSelection.text(2));
1955         }
1956         if (selections.size() > 0) {
1957                 menuBar.tagEditAction.setEnabled(true);
1958                 menuBar.tagDeleteAction.setEnabled(true);
1959                 menuBar.tagIconAction.setEnabled(true);
1960         }
1961         else {
1962                 menuBar.tagEditAction.setEnabled(false);
1963                 menuBar.tagDeleteAction.setEnabled(false);
1964                 menuBar.tagIconAction.setEnabled(true);
1965         }
1966         listManager.setSelectedTags(selectedTagGUIDs);
1967         listManager.loadNotesIndex();
1968         noteIndexUpdated(false);
1969         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1970     }
1971     // trigger the tag index to be refreshed
1972     @SuppressWarnings("unused")
1973         private void tagIndexUpdated() {
1974         tagIndexUpdated(true);
1975     }
1976     private void tagIndexUpdated(boolean reload) {
1977         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1978                 if (selectedTagGUIDs == null)
1979                         selectedTagGUIDs = new ArrayList<String>();
1980                 if (reload)
1981                         listManager.reloadTagIndex();
1982
1983                 tagTree.blockSignals(true);
1984                 if (reload) {
1985                         tagTree.setIcons(conn.getTagTable().getAllIcons());
1986                         tagTree.load(listManager.getTagIndex());
1987                 }
1988         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1989                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1990                 if (!found)
1991                         selectedTagGUIDs.remove(i);
1992         }
1993         tagTree.blockSignals(false);
1994         
1995                 browserWindow.setTag(getTagNamesForNote(currentNote));
1996         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1997     }   
1998     // Show/Hide note information
1999         private void toggleTagWindow() {
2000                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2001         if (tagTree.isVisible())
2002                 tagTree.hide();
2003         else
2004                 tagTree.show();
2005         menuBar.hideTags.setChecked(tagTree.isVisible());
2006         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2007         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2008     }   
2009         // A note's tags have been updated
2010         @SuppressWarnings("unused")
2011         private void updateNoteTags(String guid, List<String> tags) {
2012                 // Save any new tags.  We'll need them later.
2013                 List<String> newTags = new ArrayList<String>();
2014                 for (int i=0; i<tags.size(); i++) {
2015                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2016                                 newTags.add(tags.get(i));
2017                 }
2018                 
2019                 listManager.saveNoteTags(guid, tags);
2020                 listManager.countTagResults(listManager.getNoteIndex());
2021                 StringBuffer names = new StringBuffer("");
2022                 for (int i=0; i<tags.size(); i++) {
2023                         names = names.append(tags.get(i));
2024                         if (i<tags.size()-1) {
2025                                 names.append(Global.tagDelimeter + " ");
2026                         }
2027                 }
2028                 browserWindow.setTag(names.toString());
2029                 noteDirty = true;
2030                 
2031                 // Now, we need to add any new tags to the tag tree
2032                 for (int i=0; i<newTags.size(); i++) 
2033                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2034         }
2035         // Get a string containing all tag names for a note
2036         private String getTagNamesForNote(Note n) {
2037                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2038                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2039                         return "";
2040                 StringBuffer buffer = new StringBuffer(100);
2041                 Vector<String> v = new Vector<String>();
2042                 List<String> guids = n.getTagGuids();
2043                 
2044                 if (guids == null) 
2045                         return "";
2046                 
2047                 for (int i=0; i<guids.size(); i++) {
2048                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2049                 }
2050                 Comparator<String> comparator = Collections.reverseOrder();
2051                 Collections.sort(v,comparator);
2052                 Collections.reverse(v);
2053                 
2054                 for (int i = 0; i<v.size(); i++) {
2055                         if (i>0) 
2056                                 buffer.append(", ");
2057                         buffer.append(v.get(i));
2058                 }
2059                 
2060                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2061                 return buffer.toString();
2062         }       
2063         // Tags were added via dropping notes from the note list
2064         @SuppressWarnings("unused")
2065         private void tagsAdded(String noteGuid, String tagGuid) {
2066                 String tagName = null;
2067                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2068                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2069                                 tagName = listManager.getTagIndex().get(i).getName();
2070                                 i=listManager.getTagIndex().size();
2071                         }
2072                 }
2073                 if (tagName == null)
2074                         return;
2075                 
2076                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2077                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2078                                 List<String> tagNames = new ArrayList<String>();
2079                                 tagNames.add(new String(tagName));
2080                                 Note n = listManager.getMasterNoteIndex().get(i);
2081                                 for (int j=0; j<n.getTagNames().size(); j++) {
2082                                         tagNames.add(new String(n.getTagNames().get(j)));
2083                                 }
2084                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2085                                 if (n.getGuid().equals(currentNoteGuid)) {
2086                                         Collections.sort(tagNames);
2087                                         String display = "";
2088                                         for (int j=0; j<tagNames.size(); j++) {
2089                                                 display = display+tagNames.get(j);
2090                                                 if (j+2<tagNames.size()) 
2091                                                         display = display+Global.tagDelimeter+" ";
2092                                         }
2093                                         browserWindow.setTag(display);
2094                                 }
2095                                 i=listManager.getMasterNoteIndex().size();
2096                         }
2097                 }
2098                 
2099                 
2100                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2101         }
2102         private void clearTagFilter() {
2103                 tagTree.blockSignals(true);
2104                 tagTree.clearSelection();
2105                 menuBar.noteRestoreAction.setVisible(false);
2106                 menuBar.tagEditAction.setEnabled(false);
2107                 menuBar.tagDeleteAction.setEnabled(false);
2108                 menuBar.tagIconAction.setEnabled(false);
2109                 selectedTagGUIDs.clear();
2110         listManager.setSelectedTags(selectedTagGUIDs);
2111         tagTree.blockSignals(false);
2112         }
2113         // Change the icon for a tag
2114         @SuppressWarnings("unused")
2115         private void setTagIcon() {
2116                 QTreeWidgetItem currentSelection;
2117                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2118                 if (selections.size() == 0)
2119                         return;
2120                 
2121                 currentSelection = selections.get(0);   
2122                 String guid = currentSelection.text(2);
2123
2124                 QIcon currentIcon = currentSelection.icon(0);
2125                 QIcon icon = conn.getTagTable().getIcon(guid);
2126                 SetIcon dialog;
2127                 if (icon == null) {
2128                         dialog = new SetIcon(currentIcon, saveLastPath);
2129                         dialog.setUseDefaultIcon(true);
2130                 } else {
2131                         dialog = new SetIcon(icon, saveLastPath);
2132                         dialog.setUseDefaultIcon(false);
2133                 }
2134                 dialog.exec();
2135                 if (dialog.okPressed()) {
2136                 saveLastPath = dialog.getPath();
2137                         QIcon newIcon = dialog.getIcon();
2138                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2139                         if (newIcon == null) 
2140                                 newIcon = new QIcon(iconPath+"tag.png");
2141                         currentSelection.setIcon(0, newIcon);
2142                 }
2143         
2144         }
2145
2146         
2147     //***************************************************************
2148     //***************************************************************
2149     //** These functions deal with Saved Search menu items
2150     //***************************************************************
2151     //***************************************************************
2152         // Add a new notebook
2153         @SuppressWarnings("unused")
2154         private void addSavedSearch() {
2155                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2156                 SavedSearchEdit edit = new SavedSearchEdit();
2157                 edit.setSearchList(listManager.getSavedSearchIndex());
2158                 edit.exec();
2159         
2160                 if (!edit.okPressed())
2161                         return;
2162         
2163                 Calendar currentTime = new GregorianCalendar();         
2164                 Long l = new Long(currentTime.getTimeInMillis());
2165                 String randint = new String(Long.toString(l));
2166         
2167                 SavedSearch search = new SavedSearch();
2168                 search.setUpdateSequenceNum(0);
2169                 search.setGuid(randint);
2170                 search.setName(edit.getName());
2171                 search.setQuery(edit.getQuery());
2172                 search.setFormat(QueryFormat.USER);
2173                 listManager.getSavedSearchIndex().add(search);
2174                 conn.getSavedSearchTable().addSavedSearch(search, true);
2175                 savedSearchIndexUpdated();
2176                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2177         }
2178         // Edit an existing tag
2179         @SuppressWarnings("unused")
2180         private void editSavedSearch() {
2181                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2182                 SavedSearchEdit edit = new SavedSearchEdit();
2183                 edit.setTitle(tr("Edit Search"));
2184                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2185                 QTreeWidgetItem currentSelection;
2186                 currentSelection = selections.get(0);
2187                 String guid = currentSelection.text(1);
2188                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2189                 edit.setName(currentSelection.text(0));
2190                 edit.setQuery(s.getQuery());
2191                 edit.setSearchList(listManager.getSavedSearchIndex());
2192                 edit.exec();
2193         
2194                 if (!edit.okPressed())
2195                         return;
2196         
2197                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2198                 SavedSearch search = null;
2199                 boolean found = false;
2200                 for (int i=0; i<list.size(); i++) {
2201                         search = list.get(i);
2202                         if (search.getGuid().equals(guid)) {
2203                                 i=list.size();
2204                                 found = true;
2205                         }
2206                 }
2207                 if (!found)
2208                         return;
2209                 search.setName(edit.getName());
2210                 search.setQuery(edit.getQuery());
2211                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2212                 savedSearchIndexUpdated();
2213                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2214         }
2215         // Delete an existing tag
2216         @SuppressWarnings("unused")
2217         private void deleteSavedSearch() {
2218                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2219                 
2220                 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2221                         QMessageBox.StandardButton.Yes, 
2222                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2223                                                         return;
2224                 }
2225                 
2226                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2227         for (int i=selections.size()-1; i>=0; i--) {
2228                 QTreeWidgetItem currentSelection;
2229                 currentSelection = selections.get(i);
2230                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2231                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2232                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2233                                 listManager.getSavedSearchIndex().remove(j);
2234                                 j=listManager.getSavedSearchIndex().size()+1;
2235                         }
2236                 }
2237                 selections.remove(i);
2238         }
2239         savedSearchIndexUpdated();
2240         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2241         }
2242     // Setup the tree containing the user's tags
2243     private void initializeSavedSearchTree() {
2244         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2245         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2246         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2247     }
2248     // Listener when a tag is selected
2249     @SuppressWarnings("unused")
2250         private void savedSearchTreeSelection() {
2251         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2252
2253         clearNotebookFilter();
2254         clearTagFilter();
2255         clearTrashFilter();
2256         clearAttributeFilter();
2257         
2258         String currentGuid = selectedSavedSearchGUID;
2259         menuBar.savedSearchEditAction.setEnabled(true);
2260         menuBar.savedSearchDeleteAction.setEnabled(true);
2261         menuBar.savedSearchIconAction.setEnabled(true);
2262         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2263         QTreeWidgetItem currentSelection;
2264         selectedSavedSearchGUID = "";
2265         for (int i=0; i<selections.size(); i++) {
2266                 currentSelection = selections.get(i);
2267                 if (currentSelection.text(1).equals(currentGuid)) {
2268                         currentSelection.setSelected(false);
2269                 } else {
2270                         selectedSavedSearchGUID = currentSelection.text(1);
2271                 }
2272 //              i = selections.size() +1;
2273         }
2274         
2275         // There is the potential for no notebooks to be selected if this 
2276         // happens then we make it look like all notebooks were selecetd.
2277         // If that happens, just select the "all notebooks"
2278         if (selections.size()==0) {
2279                 clearSavedSearchFilter();
2280         }
2281         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2282         
2283         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2284     }
2285     private void clearSavedSearchFilter() {
2286         menuBar.savedSearchEditAction.setEnabled(false);
2287         menuBar.savedSearchDeleteAction.setEnabled(false);
2288         menuBar.savedSearchIconAction.setEnabled(false);
2289         savedSearchTree.blockSignals(true);
2290         savedSearchTree.clearSelection();
2291         savedSearchTree.blockSignals(false);
2292         selectedSavedSearchGUID = "";
2293         searchField.setEditText("");
2294         searchPerformed = false;
2295         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2296     }
2297     // trigger the tag index to be refreshed
2298         private void savedSearchIndexUpdated() { 
2299                 if (selectedSavedSearchGUID == null)
2300                         selectedSavedSearchGUID = new String();
2301                 savedSearchTree.blockSignals(true);
2302                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2303         savedSearchTree.load(listManager.getSavedSearchIndex());
2304         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2305         savedSearchTree.blockSignals(false);
2306     }
2307     // trigger when the saved search selection changes
2308     @SuppressWarnings("unused")
2309         private void updateSavedSearchSelection() {
2310                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2311                 
2312         menuBar.savedSearchEditAction.setEnabled(true);
2313         menuBar.savedSearchDeleteAction.setEnabled(true);
2314         menuBar.savedSearchIconAction.setEnabled(true);
2315         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2316
2317         if (selections.size() > 0) {
2318                 menuBar.savedSearchEditAction.setEnabled(true);
2319                 menuBar.savedSearchDeleteAction.setEnabled(true);
2320                 menuBar.savedSearchIconAction.setEnabled(true);
2321                 selectedSavedSearchGUID = selections.get(0).text(1);
2322                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2323                 searchField.setEditText(s.getQuery());
2324         } else { 
2325                 menuBar.savedSearchEditAction.setEnabled(false);
2326                 menuBar.savedSearchDeleteAction.setEnabled(false);
2327                 menuBar.savedSearchIconAction.setEnabled(false);
2328                 selectedSavedSearchGUID = "";
2329                 searchField.setEditText("");
2330         }
2331         searchFieldChanged();
2332         
2333                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2334
2335         
2336     }
2337     // Show/Hide note information
2338         private void toggleSavedSearchWindow() {
2339                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2340         if (savedSearchTree.isVisible())
2341                 savedSearchTree.hide();
2342         else
2343                 savedSearchTree.show();
2344         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2345                                 
2346                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2347         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2348     }
2349         // Change the icon for a saved search
2350         @SuppressWarnings("unused")
2351         private void setSavedSearchIcon() {
2352                 QTreeWidgetItem currentSelection;
2353                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2354                 if (selections.size() == 0)
2355                         return;
2356                 
2357                 currentSelection = selections.get(0);   
2358                 String guid = currentSelection.text(1);
2359
2360                 QIcon currentIcon = currentSelection.icon(0);
2361                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2362                 SetIcon dialog;
2363                 if (icon == null) {
2364                         dialog = new SetIcon(currentIcon, saveLastPath);
2365                         dialog.setUseDefaultIcon(true);
2366                 } else {
2367                         dialog = new SetIcon(icon, saveLastPath);
2368                         dialog.setUseDefaultIcon(false);
2369                 }
2370                 dialog.exec();
2371                 if (dialog.okPressed()) {
2372                 saveLastPath = dialog.getPath();
2373                         QIcon newIcon = dialog.getIcon();
2374                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2375                         if (newIcon == null) 
2376                                 newIcon = new QIcon(iconPath+"search.png");
2377                         currentSelection.setIcon(0, newIcon);
2378                 }
2379         
2380         }
2381         
2382         
2383         
2384         
2385     //***************************************************************
2386     //***************************************************************
2387     //** These functions deal with Help menu & tool menu items
2388     //***************************************************************
2389     //***************************************************************
2390         // Show database status
2391         @SuppressWarnings("unused")
2392         private void databaseStatus() {
2393                 waitCursor(true);
2394                 int dirty = conn.getNoteTable().getDirtyCount();
2395                 int unindexed = conn.getNoteTable().getUnindexedCount();
2396                 DatabaseStatus status = new DatabaseStatus();
2397                 status.setUnsynchronized(dirty);
2398                 status.setUnindexed(unindexed);
2399                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2400                 status.setNotebookCount(listManager.getNotebookIndex().size());
2401                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2402                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2403                 status.setTagCount(listManager.getTagIndex().size());
2404                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2405                 status.setWordCount(conn.getWordsTable().getWordCount());
2406                 waitCursor(false);
2407                 status.exec();
2408         }
2409         // Compact the database
2410         @SuppressWarnings("unused")
2411         private void compactDatabase() {
2412         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2413                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2414                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2415                                 "and NeverNote will be unresponsive until it is complete.  Do you wish to continue?"),
2416                                 QMessageBox.StandardButton.Yes, 
2417                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2418                                                         return;
2419                 }
2420                 setMessage("Compacting database.");
2421                 waitCursor(true);
2422                 listManager.compactDatabase();
2423                 waitCursor(false);
2424                 setMessage("Database compact is complete.");            
2425         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2426     }
2427         @SuppressWarnings("unused")
2428         private void accountInformation() {
2429                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2430                 AccountDialog dialog = new AccountDialog();
2431                 dialog.show();
2432                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2433         }
2434         @SuppressWarnings("unused")
2435         private void releaseNotes() {
2436                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2437                 QDialog dialog = new QDialog(this);
2438                 QHBoxLayout layout = new QHBoxLayout();
2439                 QTextEdit textBox = new QTextEdit();
2440                 layout.addWidget(textBox);
2441                 textBox.setReadOnly(true);
2442                 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2443                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2444                 QIODevice.OpenModeFlag.Text)))
2445                         return;
2446                 textBox.setText(file.readAll().toString());
2447                 file.close();
2448                 dialog.setWindowTitle(tr("Release Notes"));
2449                 dialog.setLayout(layout);
2450                 dialog.show();
2451                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2452         }
2453         // Called when user picks Log from the help menu
2454         @SuppressWarnings("unused")
2455         private void logger() {
2456                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2457                 QDialog dialog = new QDialog(this);
2458                 QHBoxLayout layout = new QHBoxLayout();
2459                 QListWidget textBox = new QListWidget();
2460                 layout.addWidget(textBox);
2461                 textBox.addItems(emitLog);
2462                 
2463                 dialog.setLayout(layout);
2464                 dialog.setWindowTitle(tr("Mesasge Log"));
2465                 dialog.show();
2466                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2467         }
2468         // Menu option "help/about" was selected
2469         @SuppressWarnings("unused")
2470         private void about() {
2471                 logger.log(logger.HIGH, "Entering NeverNote.about");
2472                 QMessageBox.about(this, 
2473                                                 tr("About NeverNote"),
2474                                                 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2475                                                 +Global.version
2476                                                 +tr("<hr></center>Evernote"
2477                                                                 +"An Open Source Evernote Client.<br><br>" 
2478                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2479                                                                 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2480                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2481                                                                 +"PDFRenderer is licened under the LGPL<br>"
2482                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2483                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2484                                                                 +"Jazzy is licened under the LGPL<br>"
2485                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));     
2486                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2487         }
2488         // Hide the entire left hand side
2489         @SuppressWarnings("unused")
2490         private void toggleLeftSide() {
2491                 boolean hidden;
2492                 
2493                 hidden = !menuBar.hideLeftSide.isChecked();
2494                 menuBar.hideLeftSide.setChecked(!hidden);
2495                 
2496                 if (notebookTree.isVisible() != hidden)
2497                         toggleNotebookWindow();
2498                 if (savedSearchTree.isVisible() != hidden)
2499                         toggleSavedSearchWindow();
2500                 if (tagTree.isVisible() != hidden)
2501                         toggleTagWindow();
2502                 if (attributeTree.isVisible() != hidden)
2503                         toggleAttributesWindow();
2504                 if (trashTree.isVisible() != hidden)
2505                         toggleTrashWindow();
2506                 
2507                 Global.saveWindowVisible("leftPanel", hidden);
2508                 
2509         }
2510         public void checkForUpdates() {
2511                 // Send off thread to check for a new version
2512                 versionChecker = new QNetworkAccessManager(this);
2513                 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2514                 QNetworkRequest request = new QNetworkRequest();
2515                 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2516                 versionChecker.get(request);
2517         }
2518         @SuppressWarnings("unused")
2519         private void upgradeFileRead(QNetworkReply reply) {
2520                 if (!reply.isReadable())
2521                         return;
2522                 
2523                 String winVersion = Global.version;
2524                 String osxVersion = Global.version;
2525                 String linuxVersion = Global.version;
2526                 String linux64Version = Global.version;
2527                 String version = Global.version;
2528                 
2529                 // Determine the versions available
2530                 QByteArray data = reply.readLine();
2531                 while (data != null && !reply.atEnd()) {
2532                         String line = data.toString();
2533                         String lineVersion;
2534                         if (line.contains(":")) 
2535                                 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2536                         else
2537                                 lineVersion = "";
2538                         if (line.toLowerCase().contains("windows")) 
2539                                 winVersion = lineVersion;
2540                         else if (line.toLowerCase().contains("os-x")) 
2541                                 osxVersion = lineVersion;
2542                         else if (line.toLowerCase().contains("linux amd64")) 
2543                                 linux64Version = lineVersion;
2544                         else if (line.toLowerCase().contains("linux i386")) 
2545                                 linuxVersion = lineVersion;
2546                         else if (line.toLowerCase().contains("default")) 
2547                                 version = lineVersion;
2548                         
2549                         // Read the next line
2550                         data = reply.readLine();
2551                 }
2552                 
2553                 // Now we need to determine what system we are on.
2554                 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2555                         version = winVersion;
2556                 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2557                         version = osxVersion;
2558                 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2559                         if (System.getProperty("os.arch").contains("amd64") ||
2560                                 System.getProperty("os.arch").contains("x86_64"))
2561                                         version = linux64Version;
2562                         else
2563                                 version = linuxVersion;
2564                 }
2565                 
2566                 
2567                 if (Global.version.equals(version))
2568                         return;
2569                 
2570                 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2571                 dialog.exec();
2572                 if (dialog.remindMe())
2573                         Global.setCheckVersionUpgrade(true);
2574                 else
2575                         Global.setCheckVersionUpgrade(false);
2576         }
2577                 
2578         
2579     //***************************************************************
2580     //***************************************************************
2581     //** These functions deal with the Toolbar
2582     //***************************************************************
2583     //***************************************************************  
2584         // Text in the search bar has been cleared
2585         private void searchFieldCleared() {
2586                 saveNote();
2587                 
2588                 // This is done because we want to force a reload of
2589                 // images.  Some images we may want to highlight the text.
2590                 readOnlyCache.clear();
2591                 inkNoteCache.clear();
2592                 noteCache.clear();
2593                 QWebSettings.setMaximumPagesInCache(0);
2594                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2595         
2596                 searchField.setEditText("");
2597                 saveNoteColumnPositions();
2598                 saveNoteIndexWidth();
2599                 noteIndexUpdated(true);
2600                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2601                         currentNote = listManager.getNoteIndex().get(0);
2602                         currentNoteGuid = currentNote.getGuid();
2603                 }
2604                 if (currentNote != null)
2605                         loadNoteBrowserInformation(browserWindow);
2606         }
2607         // text in the search bar changed.  We only use this to tell if it was cleared, 
2608         // otherwise we trigger off searchFieldChanged.
2609         @SuppressWarnings("unused")
2610         private void searchFieldTextChanged(String text) {
2611                 QWebSettings.setMaximumPagesInCache(0);
2612                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2613
2614                 if (text.trim().equals("")) {
2615                         searchFieldCleared();
2616                         if (searchPerformed) {
2617
2618                                 // This is done because we want to force a reload of
2619                                 // images.  Some images we may want to highlight the text.
2620                                 noteCache.clear();
2621                                 readOnlyCache.clear();
2622                                 inkNoteCache.clear();
2623                                 
2624                                 listManager.setEnSearch("");
2625                                 listManager.loadNotesIndex();
2626                                 refreshEvernoteNote(true);
2627                                 noteIndexUpdated(false);
2628                         }
2629                         searchPerformed = false;
2630                 }
2631         }
2632     // Text in the toolbar has changed
2633     private void searchFieldChanged() {
2634         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2635         noteCache.clear();
2636         readOnlyCache.clear();
2637         inkNoteCache.clear();
2638         saveNoteColumnPositions();
2639         saveNoteIndexWidth();
2640         String text = searchField.currentText();
2641         listManager.setEnSearch(text.trim());
2642         listManager.loadNotesIndex();
2643 //--->>>        noteIndexUpdated(true);
2644         noteIndexUpdated(false);
2645         refreshEvernoteNote(true);
2646         searchPerformed = true;
2647         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2648     }
2649
2650     // Build the window tool bar
2651     private void setupToolBar() {
2652         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2653         toolBar = addToolBar(tr("Tool Bar"));   
2654         menuBar.setupToolBarVisible();
2655         if (!Global.isWindowVisible("toolBar"))
2656                 toolBar.setVisible(false);
2657         else
2658                 toolBar.setVisible(true);
2659
2660         prevButton = toolBar.addAction("Previous");
2661         QIcon prevIcon = new QIcon(iconPath+"back.png");
2662         prevButton.setIcon(prevIcon);
2663         prevButton.triggered.connect(this, "previousViewedAction()");   
2664         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2665         
2666         nextButton = toolBar.addAction("Next");
2667         QIcon nextIcon = new QIcon(iconPath+"forward.png");
2668         nextButton.setIcon(nextIcon);
2669         nextButton.triggered.connect(this, "nextViewedAction()");       
2670         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2671         
2672         upButton = toolBar.addAction("Up");
2673         QIcon upIcon = new QIcon(iconPath+"up.png");
2674         upButton.setIcon(upIcon);
2675         upButton.triggered.connect(this, "upAction()");         
2676         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2677
2678         
2679         downButton = toolBar.addAction("Down");
2680         QIcon downIcon = new QIcon(iconPath+"down.png");
2681         downButton.setIcon(downIcon);
2682         downButton.triggered.connect(this, "downAction()");
2683         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2684         
2685         synchronizeButton = toolBar.addAction("Synchronize");
2686         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2687         synchronizeIconAngle = 0;
2688         synchronizeButton.triggered.connect(this, "evernoteSync()");
2689         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2690         
2691         printButton = toolBar.addAction("Print");
2692         QIcon printIcon = new QIcon(iconPath+"print.png");
2693         printButton.setIcon(printIcon);
2694         printButton.triggered.connect(this, "printNote()");
2695         togglePrintButton(Global.isToolbarButtonVisible("print"));
2696
2697         tagButton = toolBar.addAction("Tag"); 
2698         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2699         tagButton.setIcon(tagIcon);
2700         tagButton.triggered.connect(browserWindow, "modifyTags()");
2701         toggleTagButton(Global.isToolbarButtonVisible("tag"));
2702
2703         attributeButton = toolBar.addAction("Attributes"); 
2704         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2705         attributeButton.setIcon(attributeIcon);
2706         attributeButton.triggered.connect(this, "toggleNoteInformation()");
2707         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2708                 
2709         emailButton = toolBar.addAction("Email");
2710         QIcon emailIcon = new QIcon(iconPath+"email.png");
2711         emailButton.setIcon(emailIcon);
2712         emailButton.triggered.connect(this, "emailNote()");
2713         toggleEmailButton(Global.isToolbarButtonVisible("email"));
2714
2715         deleteButton = toolBar.addAction("Delete");     
2716         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2717         deleteButton.setIcon(deleteIcon);
2718         deleteButton.triggered.connect(this, "deleteNote()");
2719         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2720
2721         newButton = toolBar.addAction("New");
2722         QIcon newIcon = new QIcon(iconPath+"new.png");
2723         newButton.triggered.connect(this, "addNote()");
2724         newButton.setIcon(newIcon);
2725         toggleNewButton(Global.isToolbarButtonVisible("new"));
2726         
2727         allNotesButton = toolBar.addAction("All Notes");
2728         QIcon allIcon = new QIcon(iconPath+"books.png");
2729         allNotesButton.triggered.connect(this, "allNotes()");
2730         allNotesButton.setIcon(allIcon);
2731         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2732         
2733         toolBar.addSeparator();
2734         toolBar.addWidget(new QLabel(tr("Quota:")));
2735         toolBar.addWidget(quotaBar);
2736         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2737         updateQuotaBar();
2738         toolBar.addSeparator();
2739         
2740         // Setup the zoom
2741         zoomSpinner = new QSpinBox();
2742         zoomSpinner.setMinimum(10);
2743         zoomSpinner.setMaximum(1000);
2744         zoomSpinner.setAccelerated(true);
2745         zoomSpinner.setSingleStep(10);
2746         zoomSpinner.setValue(100);
2747         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2748         toolBar.addWidget(new QLabel(tr("Zoom")));
2749         toolBar.addWidget(zoomSpinner);
2750         
2751         //toolBar.addWidget(new QLabel("                    "));
2752         toolBar.addSeparator();
2753         toolBar.addWidget(new QLabel(tr("  Search:")));
2754         toolBar.addWidget(searchField);
2755         QSizePolicy sizePolicy = new QSizePolicy();
2756         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2757         searchField.setSizePolicy(sizePolicy);
2758         searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2759
2760         searchClearButton = toolBar.addAction("Search Clear");
2761         QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2762         searchClearButton.setIcon(searchClearIcon);
2763         searchClearButton.triggered.connect(this, "searchFieldCleared()");
2764         toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2765
2766         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2767     }
2768     // Update the sychronize button picture
2769     @Override
2770         public QMenu createPopupMenu() {
2771         QMenu contextMenu = super.createPopupMenu();
2772         
2773         contextMenu.addSeparator();
2774         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2775         contextMenu.addAction(prevAction);
2776         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2777
2778         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2779         contextMenu.addAction(nextAction);
2780         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2781
2782         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2783         contextMenu.addAction(upAction);
2784         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2785
2786         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2787         contextMenu.addAction(downAction);
2788         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2789
2790         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2791         contextMenu.addAction(synchronizeAction);
2792         synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2793
2794         QAction printAction = addContextAction("print", tr("Print"));
2795         contextMenu.addAction(printAction);
2796         printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2797
2798         QAction tagAction = addContextAction("tag", tr("Tag"));
2799         contextMenu.addAction(tagAction);
2800         tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2801         
2802         QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2803         contextMenu.addAction(attributeAction);
2804         attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2805         
2806         QAction emailAction = addContextAction("email", tr("Email"));
2807         contextMenu.addAction(emailAction);
2808         emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2809
2810         QAction deleteAction = addContextAction("delete", tr("Delete"));
2811         contextMenu.addAction(deleteAction);
2812         deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2813
2814         QAction newAction = addContextAction("new", tr("Add"));
2815         contextMenu.addAction(newAction);
2816         newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2817
2818         QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2819         contextMenu.addAction(allNotesAction);
2820         allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2821         
2822         QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2823         contextMenu.addAction(searchClearAction);
2824         searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2825         
2826         return contextMenu;
2827         
2828     }
2829     private QAction addContextAction(String config, String name) {
2830         QAction newAction = new QAction(this);
2831                 newAction.setText(name);
2832                 newAction.setCheckable(true);
2833                 newAction.setChecked(Global.isToolbarButtonVisible(config));
2834                 return newAction;
2835     }
2836     private void togglePrevArrowButton(Boolean toggle) {
2837                 prevButton.setVisible(toggle);
2838                 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2839     }
2840     private void toggleNextArrowButton(Boolean toggle) {
2841                 nextButton.setVisible(toggle);
2842                 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2843     }
2844     private void toggleUpArrowButton(Boolean toggle) {
2845                 upButton.setVisible(toggle);
2846                 Global.saveToolbarButtonsVisible("upArrow", toggle);
2847     }
2848     private void toggleDownArrowButton(Boolean toggle) {
2849                 downButton.setVisible(toggle);
2850                 Global.saveToolbarButtonsVisible("downArrow", toggle);
2851     }
2852     private void toggleSynchronizeButton(Boolean toggle) {
2853                 synchronizeButton.setVisible(toggle);
2854                 Global.saveToolbarButtonsVisible("synchronize", toggle);
2855     }
2856     private void togglePrintButton(Boolean toggle) {
2857                 printButton.setVisible(toggle);
2858                 Global.saveToolbarButtonsVisible("print", toggle);
2859     }
2860     private void toggleTagButton(Boolean toggle) {
2861                 tagButton.setVisible(toggle);
2862                 Global.saveToolbarButtonsVisible("tag", toggle);
2863     }
2864     private void toggleAttributeButton(Boolean toggle) {
2865                 attributeButton.setVisible(toggle);
2866                 Global.saveToolbarButtonsVisible("attribute", toggle);
2867     }
2868     private void toggleEmailButton(Boolean toggle) {
2869                 emailButton.setVisible(toggle);
2870                 Global.saveToolbarButtonsVisible("email", toggle);
2871     }
2872     private void toggleDeleteButton(Boolean toggle) {
2873                 deleteButton.setVisible(toggle);
2874                 Global.saveToolbarButtonsVisible("delete", toggle);
2875     }
2876     private void toggleNewButton(Boolean toggle) {
2877                 newButton.setVisible(toggle);
2878                 Global.saveToolbarButtonsVisible("new", toggle);
2879     }
2880     private void toggleAllNotesButton(Boolean toggle) {
2881                 allNotesButton.setVisible(toggle);
2882                 Global.saveToolbarButtonsVisible("allNotes", toggle);
2883     }
2884     private void toggleSearchClearButton(Boolean toggle) {
2885                 searchClearButton.setVisible(toggle);
2886                 Global.saveToolbarButtonsVisible("searchClear", toggle);
2887     }
2888
2889
2890
2891
2892
2893     @SuppressWarnings("unused")
2894         private void updateSyncButton() {
2895                 
2896         if (syncIcons == null) {
2897                 syncIcons = new ArrayList<QPixmap>();
2898                 double angle = 0.0;
2899                 synchronizeIconAngle = 0;
2900                 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2901                 syncIcons.add(pix);
2902                 for (int i=0; i<=360; i++) {
2903                         QPixmap rotatedPix = new QPixmap(pix.size());
2904                         QPainter p = new QPainter(rotatedPix);
2905                 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2906                 QSize size = pix.size();
2907                 p.translate(size.width()/2, size.height()/2);
2908                 angle = angle+1.0;
2909                 p.rotate(angle);
2910                 p.setBackgroundMode(BGMode.OpaqueMode);
2911                 p.translate(-size.width()/2, -size.height()/2);
2912                 p.drawPixmap(0,0, pix);
2913                 p.end();
2914                 syncIcons.add(rotatedPix);
2915                 }
2916         }
2917
2918         synchronizeIconAngle++;
2919         if (synchronizeIconAngle > 359)
2920                 synchronizeIconAngle=0;
2921         synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2922         
2923     }
2924     // Synchronize with Evernote
2925         @SuppressWarnings("unused")
2926         private void evernoteSync() {
2927         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2928         if (!Global.isConnected)
2929                 remoteConnect();
2930         if (Global.isConnected)
2931                 synchronizeAnimationTimer.start(5);
2932 //                      synchronizeAnimationTimer.start(200);
2933         syncTimer();
2934         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2935     }
2936     private void updateQuotaBar() {
2937         long limit = Global.getUploadLimit();
2938         long amount = Global.getUploadAmount();
2939         if (amount>0 && limit>0) {
2940                 int percent =(int)(amount*100/limit);
2941                 quotaBar.setValue(percent);
2942         } else 
2943                 quotaBar.setValue(0);
2944     }
2945         // Zoom changed
2946     @SuppressWarnings("unused")
2947         private void zoomChanged() {
2948         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2949     }
2950
2951     //****************************************************************
2952     //****************************************************************
2953     //* System Tray functions
2954     //****************************************************************
2955     //****************************************************************
2956         private void trayToggleVisible() {
2957         if (isVisible()) {
2958                 hide();
2959         } else {
2960                 show();
2961                 if (windowMaximized)
2962                         showMaximized();
2963                 else
2964                         showNormal();
2965                 raise();
2966         }
2967     }
2968     @SuppressWarnings("unused")
2969         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2970         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2971                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2972                 trayToggleVisible();
2973         }
2974     }
2975     
2976     
2977     //***************************************************************
2978     //***************************************************************
2979     //** These functions deal with the trash tree
2980     //***************************************************************
2981     //***************************************************************    
2982     // Setup the tree containing the trash.
2983     @SuppressWarnings("unused")
2984         private void trashTreeSelection() {     
2985         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2986         
2987         clearNotebookFilter();
2988         clearTagFilter();
2989         clearAttributeFilter();
2990         clearSavedSearchFilter();
2991         
2992         String tempGuid = currentNoteGuid;
2993         
2994 //      currentNoteGuid = "";
2995         currentNote = new Note();
2996         selectedNoteGUIDs.clear();
2997         listManager.getSelectedNotebooks().clear();
2998         listManager.getSelectedTags().clear();
2999         listManager.setSelectedSavedSearch("");
3000         browserWindow.clear();
3001     
3002         // toggle the add buttons
3003         newButton.setEnabled(!newButton.isEnabled());
3004         menuBar.noteAdd.setEnabled(newButton.isEnabled());
3005         menuBar.noteAdd.setVisible(true);
3006         
3007         List<QTreeWidgetItem> selections = trashTree.selectedItems();
3008         if (selections.size() == 0) {
3009                 currentNoteGuid = trashNoteGuid;
3010                         trashNoteGuid = tempGuid;
3011                 Global.showDeleted = false;
3012                 menuBar.noteRestoreAction.setEnabled(false);
3013                 menuBar.noteRestoreAction.setVisible(false);
3014         }
3015         else {
3016                 currentNoteGuid = trashNoteGuid;
3017                         trashNoteGuid = tempGuid;
3018                 menuBar.noteRestoreAction.setEnabled(true);
3019                 menuBar.noteRestoreAction.setVisible(true);
3020                 Global.showDeleted = true;
3021         }
3022         listManager.loadNotesIndex();
3023         noteIndexUpdated(false);
3024 ////            browserWindow.setEnabled(newButton.isEnabled());
3025         browserWindow.setReadOnly(!newButton.isEnabled());
3026         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3027     }
3028     // Empty the trash file
3029     @SuppressWarnings("unused")
3030         private void emptyTrash() {
3031 //      browserWindow.clear();
3032         listManager.emptyTrash();
3033         if (trashTree.selectedItems().size() > 0) {
3034                 listManager.getSelectedNotebooks().clear();
3035                 listManager.getSelectedTags().clear();
3036                 listManager.setSelectedSavedSearch("");
3037                 newButton.setEnabled(!newButton.isEnabled());
3038                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3039                 menuBar.noteAdd.setVisible(true);
3040                 browserWindow.clear();
3041                 
3042                 clearTagFilter();
3043                 clearNotebookFilter();
3044                 clearSavedSearchFilter();
3045                 clearAttributeFilter();
3046                         
3047                 Global.showDeleted = false;
3048                 menuBar.noteRestoreAction.setEnabled(false);
3049                 menuBar.noteRestoreAction.setVisible(false);
3050                 
3051                 listManager.loadNotesIndex();
3052 //--->>>                noteIndexUpdated(true);
3053                 noteIndexUpdated(false);
3054         }       
3055    }
3056     // Show/Hide trash window
3057         private void toggleTrashWindow() {
3058                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3059         if (trashTree.isVisible())
3060                 trashTree.hide();
3061         else
3062                 trashTree.show();
3063         menuBar.hideTrash.setChecked(trashTree.isVisible());
3064         
3065                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3066         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3067     }    
3068         private void clearTrashFilter() {
3069                 Global.showDeleted = false;
3070         newButton.setEnabled(true);
3071         menuBar.noteAdd.setEnabled(true);
3072         menuBar.noteAdd.setVisible(true);
3073                 trashTree.blockSignals(true);
3074                 trashTree.clearSelection();
3075                 trashTree.blockSignals(false);
3076                 
3077         }
3078     
3079    
3080     //***************************************************************
3081     //***************************************************************
3082     //** These functions deal with connection settings
3083     //***************************************************************
3084     //***************************************************************
3085         // SyncRunner had a problem and things are disconnected
3086         @SuppressWarnings("unused")
3087         private void remoteErrorDisconnect() {
3088                 menuBar.connectAction.setText(tr("Connect"));
3089                 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3090                 menuBar.synchronizeAction.setEnabled(false);
3091                 Global.isConnected = false;
3092                 synchronizeAnimationTimer.stop();
3093                 return;
3094         }
3095         // Do a manual connect/disconnect