OSDN Git Service

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