OSDN Git Service

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