OSDN Git Service

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