OSDN Git Service

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