OSDN Git Service

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