OSDN Git Service

Correct java cast exceptions when doing a getUserInformation.
[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                         Global.setDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
865                         Global.setDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
866                         QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
867                 }
868         } catch (SQLException e) {
869                         e.printStackTrace();
870                 }       
871     }
872     
873     // Decrypt the database upon shutdown
874     private void decryptOnShutdown() {
875         String dbPath= Global.getFileManager().getDbDirPath("");
876         String dbName = "NeverNote";
877         try {
878                 Statement st = conn.getConnection().createStatement();  
879                 st.execute("shutdown");
880                 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
881                         encryptCipher = "AES";
882                 else
883                         encryptCipher = "XTEA";
884                 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure", 
885                                 "Are you sure you wish to decrypt the database?"),
886                                 QMessageBox.StandardButton.Yes, 
887                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
888
889                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
890                         Global.setDatabaseUrl("");
891                         QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
892                 }
893                 } catch (SQLException e) {
894                         e.printStackTrace();
895                 }       
896     }
897     /**
898      * Encrypt/Decrypt the local database
899      **/
900     public void doDatabaseEncrypt() {
901         // The database is not currently encrypted
902         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
903                 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
904                                 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
905                                 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
906                                 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
907                                 "Do you wish to proceed?"),
908                                 QMessageBox.StandardButton.Yes, 
909                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
910                                 return;
911                 }
912                 DBEncryptDialog dialog = new DBEncryptDialog();
913                 dialog.exec();
914                 if (dialog.okPressed()) {
915                         Global.cipherPassword = dialog.getPassword();
916                         encryptOnShutdown  = true;
917                         encryptCipher = dialog.getEncryptionMethod();
918                 }
919         } else {
920             DBEncryptDialog dialog = new DBEncryptDialog();
921             dialog.setWindowTitle(tr("Database Decryption"));
922             dialog.hideEncryption();
923             dialog.exec();
924             if (dialog.okPressed()) {
925                 if (!dialog.getPassword().equals(Global.cipherPassword)) {
926                         QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
927                         return;
928                 }
929                 decryptOnShutdown  = true;
930                 encryptCipher = "";
931             }
932         }
933         return;
934     }
935
936         private static void initializeGlobalSettings(String[] args) throws InitializationException {
937                 StartupConfig   startupConfig = new StartupConfig();
938
939         for (String arg : args) {
940             String lower = arg.toLowerCase();
941             if (lower.startsWith("--name="))
942                startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
943             if (lower.startsWith("--home="))
944                startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
945             if (lower.startsWith("--disable-viewing"))
946                startupConfig.setDisableViewing(true);
947         }
948                 Global.setup(startupConfig);
949     }
950
951     // Exit point
952         @Override
953         public void closeEvent(QCloseEvent event) {     
954                 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
955                         event.ignore();
956                         hide();
957                         return;
958                 }
959                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
960                 waitCursor(true);
961                 
962                 if (currentNote!= null & browserWindow!=null) {
963                         if (!currentNote.getTitle().equals(browserWindow.getTitle()))
964                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
965                 }
966                 saveNote();
967                 setMessage(tr("Beginning shutdown."));
968                 
969                 // Close down external windows
970                 Collection<ExternalBrowse> windows = externalWindows.values();
971                 Iterator<ExternalBrowse> iterator = windows.iterator();
972                 while (iterator.hasNext()) {
973                         ExternalBrowse browser = iterator.next();
974                         browser.windowClosing.disconnect();
975                         browser.close();
976                 }
977                 
978                 
979                 externalFileEditedSaver();
980                 if (Global.isConnected && Global.synchronizeOnClose()) {
981                         setMessage(tr("Performing synchronization before closing."));
982                         syncRunner.syncNeeded = true;
983                         syncRunner.addWork("SYNC");
984                 } else {
985                         syncRunner.keepRunning = false;
986                 }
987                 syncRunner.addWork("STOP");
988                 setMessage("Closing Program.");
989                 threadMonitorTimer.stop();
990
991                 thumbnailRunner.addWork("STOP");
992                 indexRunner.addWork("STOP");
993                 saveNote();
994                 listManager.stop();
995                 saveWindowState();
996
997                 if (tempFiles != null)
998                         tempFiles.clear();
999
1000                 browserWindow.noteSignal.tagsChanged.disconnect();
1001                 browserWindow.noteSignal.titleChanged.disconnect();
1002                 browserWindow.noteSignal.noteChanged.disconnect();
1003                 browserWindow.noteSignal.notebookChanged.disconnect();
1004                 browserWindow.noteSignal.createdDateChanged.disconnect();
1005                 browserWindow.noteSignal.alteredDateChanged.disconnect();
1006                 syncRunner.searchSignal.listChanged.disconnect();
1007                 syncRunner.tagSignal.listChanged.disconnect();
1008         syncRunner.notebookSignal.listChanged.disconnect();
1009         syncRunner.noteIndexSignal.listChanged.disconnect();
1010
1011                 if (isVisible())
1012                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
1013                 saveNoteColumnPositions();
1014                 saveNoteIndexWidth();
1015                 
1016                 int width = notebookTree.columnWidth(0);
1017                 Global.setColumnWidth("notebookTreeName", width);
1018                 width = tagTree.columnWidth(0);
1019                 Global.setColumnWidth("tagTreeName", width);
1020                 
1021                 Global.saveWindowMaximized(isMaximized());
1022                 Global.saveCurrentNoteGuid(currentNoteGuid);
1023                         
1024                 int sortCol = noteTableView.proxyModel.sortColumn();
1025                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1026                 Global.setSortColumn(sortCol);
1027                 Global.setSortOrder(sortOrder);
1028                 
1029                 hide();
1030                 trayIcon.hide();
1031                 Global.keepRunning = false;
1032                 try {
1033                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1034                         if (indexRunner.thread().isAlive())
1035                                 indexRunner.thread().join(50);
1036                         if (!indexRunner.thread().isAlive())
1037                                 logger.log(logger.MEDIUM, "Index thread has stopped");
1038                         else {
1039                                 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1040                                 indexRunner.thread().interrupt();
1041                         }
1042                 } catch (InterruptedException e1) {
1043                         e1.printStackTrace();
1044                 }
1045                 
1046                 if (!syncRunner.thread().isAlive()) {
1047                         logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1048                         if (syncRunner.thread().isAlive()) {
1049                                 System.out.println(tr("Synchronizing.  Please be patient."));
1050                                 for(;syncRunner.thread().isAlive();) {
1051                                         try {
1052                                                 wait(10);
1053                                         } catch (InterruptedException e) {
1054                                                 e.printStackTrace();
1055                                         }
1056                                 }
1057                         }
1058                         logger.log(logger.MEDIUM, "Sync thread has stopped");
1059                 }
1060
1061                 if (encryptOnShutdown) {
1062                         encryptOnShutdown();
1063                 }
1064                 if (decryptOnShutdown) {
1065                         decryptOnShutdown();
1066                 }
1067                 try {
1068                         Global.getFileManager().purgeResDirectory(false);
1069                 } catch (InitializationException e) {
1070                         System.out.println(tr("Empty res directory purge failed"));
1071                         e.printStackTrace();
1072                 }
1073                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1074         }
1075
1076         @SuppressWarnings("unused")
1077         private void closeNeverNote() {
1078                 closeAction = true;
1079                 close();
1080         }
1081         public void setMessage(String s) {
1082                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1083                 
1084                 statusBar.show();
1085                 logger.log(logger.HIGH, "Message: " +s);
1086                 statusBar.showMessage(s);
1087                 emitLog.add(s);
1088                 
1089
1090                 messageTimer.stop();
1091                 messageTimer.setSingleShot(true);
1092                 messageTimer.start();
1093                 
1094                 
1095                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1096         }
1097         
1098         private void clearMessage() {
1099                 statusBar.clearMessage();
1100                 statusBar.hide();
1101         }
1102                 
1103         private void waitCursor(boolean wait) {
1104                 if (wait) {
1105                         if (QApplication.overrideCursor() == null)
1106                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1107                 }
1108                 else {
1109                         while (QApplication.overrideCursor() != null)
1110                                 QApplication.restoreOverrideCursor();
1111                 }
1112                 listManager.refreshCounters();
1113         }
1114         
1115         private void setupIndexListeners() {
1116 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1117 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1118                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1119                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1120         }
1121         private void setupSyncSignalListeners() {
1122                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1123         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1124         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1125         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1126         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1127         
1128                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1129                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1130                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1131                 
1132                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1133                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1134                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1135                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1136                 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1137                 
1138                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1139         }
1140         
1141         private void setupBrowserSignalListeners() {
1142                 setupBrowserWindowListeners(browserWindow, true);
1143         }
1144
1145         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1146                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1147                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1148             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1149             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1150             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1151             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1152             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1153             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1154             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1155             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1156             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1157             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1158             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1159             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1160         browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1161         browser.unblockApplication.connect(this, "unblockApplication()");
1162             if (master) browser.focusLost.connect(this, "saveNote()");
1163             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1164             browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1165         }
1166
1167         //**************************************************
1168         //* Setup shortcuts
1169         //**************************************************
1170         private void setupShortcut(QShortcut action, String text) {
1171                 if (!Global.shortcutKeys.containsAction(text))
1172                         return;
1173                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1174         }
1175         
1176         //***************************************************************
1177         //***************************************************************
1178         //* Settings and look & feel
1179         //***************************************************************
1180         //***************************************************************
1181         @SuppressWarnings("unused")
1182         private void settings() {
1183                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1184                 saveNoteColumnPositions();
1185                 saveNoteIndexWidth();
1186                 showColumns();
1187         ConfigDialog settings = new ConfigDialog(this);
1188         String dateFormat = Global.getDateFormat();
1189         String timeFormat = Global.getTimeFormat();
1190         
1191                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1192                 indexTimer.start(indexTime);  // reset indexing timer
1193         
1194         settings.exec();
1195         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1196         indexRunner.indexNoteBody = Global.indexNoteBody();
1197         indexRunner.indexNoteTitle = Global.indexNoteTitle();
1198         indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1199         indexRunner.indexImageRecognition = Global.indexImageRecognition();
1200         if (Global.showTrayIcon())
1201                 trayIcon.show();
1202         else
1203                 trayIcon.hide();
1204         showColumns();
1205         if (menuBar.showEditorBar.isChecked())
1206                 showEditorButtons(browserWindow);
1207         
1208         // Reset the save timer
1209         if (Global.getAutoSaveInterval() > 0)
1210                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1211         else
1212                 saveTimer.stop();
1213         
1214         
1215         // Set special reloads
1216         if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1217                 conn.executeSql("Delete from LinkedNotebook");
1218                 conn.executeSql("delete from SharedNotebook");
1219                 conn.executeSql("Delete from Notebook where linked=true");
1220                 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1221                 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1222         }
1223
1224         // Reload user data
1225         noteCache.clear();
1226         readOnlyCache.clear();
1227         inkNoteCache.clear();
1228         noteIndexUpdated(true);
1229                 
1230         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1231         }
1232         // Restore things to the way they were
1233         private void restoreWindowState(boolean mainWindow) {
1234                 // We need to name things or this doesn't work.
1235                 setObjectName("NeverNote");
1236         restoreState(Global.restoreState(objectName()));
1237                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1238                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1239                 leftSplitter1.setObjectName("leftSplitter1");   
1240                 
1241                 // Restore the actual positions.
1242                 if (mainWindow)
1243                         restoreGeometry(Global.restoreGeometry(objectName()));
1244         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1245         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1246         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1247        
1248         }
1249         // Save window positions for the next start
1250         private void saveWindowState() {
1251                 Global.saveGeometry(objectName(), saveGeometry());
1252                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1253                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1254                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1255                 Global.saveState(objectName(), saveState());
1256         }    
1257         // Load the style sheet
1258         private void loadStyleSheet() {
1259                 String styleSheetName = "default.qss";
1260                 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1261                                 styleSheetName = "default-cleanlooks.qss";
1262                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1263                 QFile file = new QFile(fileName);
1264                 
1265                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1266                 if (!file.exists()) {
1267                         fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1268                         file = new QFile(fileName);
1269                 }
1270                 file.open(OpenModeFlag.ReadOnly);
1271                 String styleSheet = file.readAll().toString();
1272                 file.close();
1273                 setStyleSheet(styleSheet);
1274         }
1275         // Save column positions for the next time
1276         private void saveNoteColumnPositions() {
1277                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1278                 Global.setColumnPosition("noteTableCreationPosition", position);
1279                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1280                 Global.setColumnPosition("noteTableTagPosition", position);
1281                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1282                 Global.setColumnPosition("noteTableNotebookPosition", position);
1283                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1284                 Global.setColumnPosition("noteTableChangedPosition", position);
1285                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1286                 Global.setColumnPosition("noteTableAuthorPosition", position);
1287                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1288                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1289                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1290                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1291                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1292                 Global.setColumnPosition("noteTableTitlePosition", position);
1293                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1294                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1295                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1296                 Global.setColumnPosition("noteTableGuidPosition", position);
1297                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1298                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1299
1300         }
1301         // Save column widths for the next time
1302         private void saveNoteIndexWidth() {
1303                 int width;
1304         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1305         Global.setColumnWidth("noteTableCreationPosition", width);
1306                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1307                 Global.setColumnWidth("noteTableChangedPosition", width);
1308                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1309                 Global.setColumnWidth("noteTableGuidPosition", width);
1310                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1311                 Global.setColumnWidth("noteTableNotebookPosition", width);
1312                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1313                 Global.setColumnWidth("noteTableTagPosition", width);
1314                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1315                 Global.setColumnWidth("noteTableTitlePosition", width);
1316                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1317                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1318                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1319                 Global.setColumnWidth("noteTableAuthorPosition", width);
1320                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1321                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1322                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1323                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1324                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1325                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1326                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1327                 Global.setColumnWidth("noteTableGuidPosition", width);
1328         }
1329         
1330         @SuppressWarnings("unused")
1331         private void toggleSearchWindow() {
1332                 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1333         searchLayout.toggleSearchField();
1334         menuBar.hideSearch.setChecked(searchField.isVisible());
1335         Global.saveWindowVisible("searchField", searchField.isVisible());
1336         logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1337     }   
1338         @SuppressWarnings("unused")
1339         private void toggleQuotaWindow() {
1340                 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1341         searchLayout.toggleQuotaBar();
1342         menuBar.hideQuota.setChecked(quotaBar.isVisible());
1343         Global.saveWindowVisible("quota", quotaBar.isVisible());
1344         logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1345     }   
1346         @SuppressWarnings("unused")
1347         private void toggleZoomWindow() {
1348                 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1349         searchLayout.toggleZoom();
1350         menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1351         Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1352         logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1353     }   
1354         
1355         
1356         
1357     //***************************************************************
1358     //***************************************************************
1359     //** These functions deal with Notebook menu items
1360     //***************************************************************
1361     //***************************************************************
1362     // Setup the tree containing the user's notebooks.
1363     private void initializeNotebookTree() {       
1364         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1365 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1366         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1367         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1368         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1369     }   
1370     // Listener when a notebook is selected
1371         private void notebookTreeSelection() {
1372                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1373
1374                 clearTrashFilter();
1375                 clearAttributeFilter();
1376                 clearSavedSearchFilter();
1377                 if (Global.mimicEvernoteInterface) {
1378                         clearTagFilter();
1379                         searchField.clear();
1380                 }
1381                 menuBar.noteRestoreAction.setVisible(false);            
1382         menuBar.notebookEditAction.setEnabled(true);
1383         menuBar.notebookDeleteAction.setEnabled(true);
1384         menuBar.notebookPublishAction.setEnabled(true);
1385         menuBar.notebookShareAction.setEnabled(true);
1386         menuBar.notebookIconAction.setEnabled(true);
1387         menuBar.notebookStackAction.setEnabled(true);
1388         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1389         selectedNotebookGUIDs.clear();
1390                 String guid = "";
1391                 String stackName = "";
1392                 if (selections.size() > 0) {
1393                 guid = (selections.get(0).text(2));
1394                 stackName = selections.get(0).text(0);
1395         }
1396                 if (!Global.mimicEvernoteInterface) {
1397                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1398                         if (selections.size()==0) {
1399                                 selectedNotebookGUIDs.clear();
1400                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1401                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1402                                 }
1403                                 menuBar.notebookEditAction.setEnabled(false);
1404                                 menuBar.notebookDeleteAction.setEnabled(false);
1405                                 menuBar.notebookStackAction.setEnabled(false);
1406                                 menuBar.notebookIconAction.setEnabled(false);
1407                         }
1408                 }
1409         if (!guid.equals("") && !guid.equals("STACK")) {
1410                 selectedNotebookGUIDs.add(guid);
1411                 menuBar.notebookIconAction.setEnabled(true);
1412         } else {
1413                 menuBar.notebookIconAction.setEnabled(true);
1414                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1415                                 Notebook book = listManager.getNotebookIndex().get(j);
1416                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1417                                         selectedNotebookGUIDs.add(book.getGuid());
1418                         }
1419         }
1420         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1421         listManager.loadNotesIndex();
1422         noteIndexUpdated(false);
1423         refreshEvernoteNote(true);
1424         listManager.refreshCounters = true;
1425         listManager.refreshCounters();
1426                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1427
1428     }
1429     private void clearNotebookFilter() {
1430         notebookTree.blockSignals(true);
1431         notebookTree.clearSelection();
1432                 menuBar.noteRestoreAction.setVisible(false);
1433         menuBar.notebookEditAction.setEnabled(false);
1434         menuBar.notebookDeleteAction.setEnabled(false);
1435         selectedNotebookGUIDs.clear();
1436         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1437         notebookTree.blockSignals(false);
1438     }
1439         // Triggered when the notebook DB has been updated
1440         private void notebookIndexUpdated() {
1441                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1442         
1443                 // Get the possible icons
1444                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1445         notebookTree.setIcons(icons);
1446         
1447         if (selectedNotebookGUIDs == null)
1448                         selectedNotebookGUIDs = new ArrayList<String>();
1449                 List<Notebook> books = conn.getNotebookTable().getAll();
1450                 for (int i=books.size()-1; i>=0; i--) {
1451                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1452                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1453                                         books.remove(i);
1454                                         j=listManager.getArchiveNotebookIndex().size();
1455                                 }
1456                         }
1457                 }
1458                 
1459                 
1460                 listManager.countNotebookResults(listManager.getNoteIndex());
1461                 notebookTree.blockSignals(true);
1462         notebookTree.load(books, listManager.getLocalNotebooks());
1463         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1464                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1465                 if (!found)
1466                         selectedNotebookGUIDs.remove(i);
1467         }
1468         listManager.refreshCounters = true;
1469         listManager.refreshCounters();
1470         notebookTree.blockSignals(false);
1471         
1472                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1473     }
1474     // Show/Hide note information
1475         @SuppressWarnings("unused")
1476         private void toggleNotebookWindow() {
1477                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1478                 searchLayout.toggleNotebook();
1479         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1480         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1481         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1482     }   
1483         // Add a new notebook
1484         @SuppressWarnings("unused")
1485         private void addNotebook() {
1486                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1487                 NotebookEdit edit = new NotebookEdit();
1488                 edit.setNotebooks(listManager.getNotebookIndex());
1489                 edit.exec();
1490         
1491                 if (!edit.okPressed())
1492                         return;
1493         
1494                 Calendar currentTime = new GregorianCalendar();
1495                 Long l = new Long(currentTime.getTimeInMillis());
1496                 String randint = new String(Long.toString(l));
1497         
1498                 Notebook newBook = new Notebook();
1499                 newBook.setUpdateSequenceNum(0);
1500                 newBook.setGuid(randint);
1501                 newBook.setName(edit.getNotebook());
1502                 newBook.setServiceCreated(new Date().getTime());
1503                 newBook.setServiceUpdated(new Date().getTime());
1504                 newBook.setDefaultNotebook(false);
1505                 newBook.setPublished(false);
1506                 
1507                 listManager.getNotebookIndex().add(newBook);
1508                 if (edit.isLocal())
1509                         listManager.getLocalNotebooks().add(newBook.getGuid());
1510                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1511                 notebookIndexUpdated();
1512                 listManager.countNotebookResults(listManager.getNoteIndex());
1513 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1514                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1515         }
1516         // Edit an existing notebook
1517         @SuppressWarnings("unused")
1518         private void stackNotebook() {
1519                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1520                 StackNotebook edit = new StackNotebook();
1521                 
1522                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1523                 QTreeWidgetItem currentSelection;
1524                 for (int i=0; i<selections.size(); i++) {
1525                         currentSelection = selections.get(0);
1526                         String guid = currentSelection.text(2);
1527                         if (guid.equalsIgnoreCase("")) {
1528                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1529                                  return;
1530                         }
1531                         if (guid.equalsIgnoreCase("STACK")) {
1532                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1533                                  return;
1534                         }
1535                 }
1536
1537                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1538
1539                 
1540                 edit.exec();
1541         
1542                 if (!edit.okPressed())
1543                         return;
1544         
1545                 String stack = edit.getStackName();
1546                 
1547                 for (int i=0; i<selections.size(); i++) {
1548                         currentSelection = selections.get(i);
1549                         String guid = currentSelection.text(2);
1550                         listManager.updateNotebookStack(guid, stack);
1551                 }
1552                 notebookIndexUpdated();
1553                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1554         }
1555         // Edit an existing notebook
1556         @SuppressWarnings("unused")
1557         private void editNotebook() {
1558                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1559                 NotebookEdit edit = new NotebookEdit();
1560                 
1561                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1562                 QTreeWidgetItem currentSelection;
1563                 currentSelection = selections.get(0);
1564                 edit.setNotebook(currentSelection.text(0));
1565                 
1566                 String guid = currentSelection.text(2);
1567                 if (!guid.equalsIgnoreCase("STACK")) {
1568                         edit.setTitle(tr("Edit Notebook"));
1569                         edit.setNotebooks(listManager.getNotebookIndex());
1570                         edit.setLocalCheckboxEnabled(false);
1571                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1572                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1573                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1574                                         i=listManager.getNotebookIndex().size();
1575                                 }
1576                         }
1577                 } else {
1578                         edit.setTitle(tr("Edit Stack"));
1579                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1580                         edit.hideLocalCheckbox();
1581                         edit.hideDefaultCheckbox();
1582                 }
1583                 
1584                 edit.exec();
1585         
1586                 if (!edit.okPressed())
1587                         return;
1588         
1589                 
1590                 if (guid.equalsIgnoreCase("STACK")) {
1591                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1592                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1593                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1594                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1595                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1596                         }
1597                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1598                         currentSelection.setText(0, edit.getNotebook());
1599                         return;
1600                 }
1601                 
1602                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1603                 currentSelection.setText(0, edit.getNotebook());
1604                 
1605                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1606                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1607                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1608                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1609                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1610                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1611                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1612                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1613                                 }
1614                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1615                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1616                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1617                                         linkedNotebook.setShareName(edit.getNotebook());
1618                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1619                                 }
1620                                 i=listManager.getNotebookIndex().size();
1621                         }
1622                 }
1623                 
1624                 // Build a list of non-closed notebooks
1625                 List<Notebook> nbooks = new ArrayList<Notebook>();
1626                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1627                         boolean found=false;
1628                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1629                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1630                                         found = true;
1631                         }
1632                         if (!found)
1633                                 nbooks.add(listManager.getNotebookIndex().get(i));
1634                 }
1635                 
1636                 
1637                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1638                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1639                 browserWindow.setNotebookList(filteredBooks);
1640                 Iterator<String> set = externalWindows.keySet().iterator();
1641                 while(set.hasNext())
1642                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1643                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1644         }
1645         // Publish a notebook
1646         @SuppressWarnings("unused")
1647         private void publishNotebook() {
1648                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1649                 QTreeWidgetItem currentSelection;
1650                 currentSelection = selections.get(0);
1651                 String guid = currentSelection.text(2);
1652
1653                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1654                         return;
1655                 
1656                 Notebook n = null;
1657                 int position = 0;
1658                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1659                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1660                                 n = listManager.getNotebookIndex().get(i);
1661                                 position = i;
1662                                 i = listManager.getNotebookIndex().size();
1663                         }
1664                 }
1665                 if (n == null)
1666                         return;
1667                 
1668                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1669                 publish.exec();
1670                 
1671                 if (!publish.okClicked()) 
1672                         return;
1673                 
1674                 Publishing p = publish.getPublishing();
1675                 boolean isPublished = !publish.isStopPressed();
1676                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1677                 n.setPublished(isPublished);
1678                 n.setPublishing(p);
1679                 listManager.getNotebookIndex().set(position, n);
1680                 notebookIndexUpdated();
1681         }
1682         // Publish a notebook
1683         @SuppressWarnings("unused")
1684         private void shareNotebook() {
1685                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1686                 QTreeWidgetItem currentSelection;
1687                 currentSelection = selections.get(0);
1688                 String guid = currentSelection.text(2);
1689
1690                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1691                         return;
1692                 
1693                 Notebook n = null;;
1694                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1695                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1696                                 n = listManager.getNotebookIndex().get(i);
1697                                 i = listManager.getNotebookIndex().size();
1698                         }
1699                 }
1700                                 
1701                 String authToken = null;
1702                 if (syncRunner.isConnected)
1703                         authToken = syncRunner.authToken;
1704                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1705                 share.exec();
1706                 
1707         }
1708
1709         // Delete an existing notebook
1710         @SuppressWarnings("unused")
1711         private void deleteNotebook() {
1712                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1713                 boolean stacksFound = false;
1714                 boolean notebooksFound = false;
1715                 boolean assigned = false;
1716                 // Check if any notes have this notebook
1717                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1718         for (int i=0; i<selections.size(); i++) {
1719                 QTreeWidgetItem currentSelection;
1720                 currentSelection = selections.get(i);
1721                 String guid = currentSelection.text(2);
1722                 if (!guid.equalsIgnoreCase("STACK")) {
1723                         notebooksFound = true;
1724                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1725                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1726                                 if (noteGuid.equals(guid)) {
1727                                         assigned = true;
1728                                         j=listManager.getNoteIndex().size();
1729                                         i=selections.size();
1730                                 }
1731                         }
1732                 } else {
1733                         stacksFound = true;
1734                 }
1735         }
1736                 if (assigned) {
1737                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1738                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1739                         return;
1740                 }
1741                 
1742                 if (conn.getNotebookTable().getAll().size() == 1) {
1743                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1744                         return;
1745                 }
1746         
1747         // If all notebooks are clear, verify the delete
1748                 String msg1 = new String(tr("Delete selected notebooks?"));
1749                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1750                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1751                                 " not deleted unless selected?"));
1752                 String msg = "";
1753                 if (stacksFound && notebooksFound)
1754                         msg = msg3;
1755                 if (!stacksFound && notebooksFound)
1756                         msg = msg1;
1757                 if (stacksFound && !notebooksFound)
1758                         msg = msg2;
1759                 if (QMessageBox.question(this, tr("Confirmation"), msg,
1760                         QMessageBox.StandardButton.Yes, 
1761                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1762                         return;
1763                 }
1764                 
1765                 // If confirmed, delete the notebook
1766         for (int i=selections.size()-1; i>=0; i--) {
1767                 QTreeWidgetItem currentSelection;
1768                 currentSelection = selections.get(i);
1769                 String guid = currentSelection.text(2);
1770                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1771                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1772                         listManager.renameStack(currentSelection.text(0), "");
1773                 } else {
1774                         conn.getNotebookTable().expungeNotebook(guid, true);
1775                         listManager.deleteNotebook(guid);
1776                 }
1777         }
1778
1779                 notebookIndexUpdated();
1780 //        notebookTreeSelection();
1781 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1782 //        listManager.countNotebookResults(listManager.getNoteIndex());
1783         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1784         }
1785         // A note's notebook has been updated
1786         @SuppressWarnings("unused")
1787         private void updateNoteNotebook(String guid, String notebookGuid) {
1788                 
1789                 // Update the list manager
1790                 listManager.updateNoteNotebook(guid, notebookGuid);
1791                 listManager.countNotebookResults(listManager.getNoteIndex());
1792 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1793                 
1794                 // Find the name of the notebook
1795                 String notebookName = null;
1796                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1797                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1798                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1799                                 break;
1800                         }
1801                 }
1802                 
1803                 // If we found the name, update the browser window
1804                 if (notebookName != null) {
1805                         updateListNoteNotebook(guid, notebookName);
1806                         if (guid.equals(currentNoteGuid)) {
1807                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1808                                 if (pos >=0)
1809                                         browserWindow.notebookBox.setCurrentIndex(pos);
1810                         }
1811                 }
1812                 
1813                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1814                 if (guid.equals(currentNoteGuid)) {
1815                         if (currentNote != null) {
1816                                 currentNote.setNotebookGuid(notebookGuid);
1817                         }
1818                 }
1819         }
1820         // Open/close notebooks
1821         @SuppressWarnings("unused")
1822         private void closeNotebooks() {
1823                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1824                 na.exec();
1825                 if (!na.okClicked())
1826                         return;
1827                 
1828                 waitCursor(true);
1829                 listManager.getArchiveNotebookIndex().clear();
1830                 
1831                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1832                         String text = na.getClosedBookList().takeItem(i).text();
1833                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1834                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1835                                         Notebook n = listManager.getNotebookIndex().get(j);
1836                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1837                                         listManager.getArchiveNotebookIndex().add(n);
1838                                         j=listManager.getNotebookIndex().size();
1839                                 }
1840                         }
1841                 }
1842                 
1843                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1844                         String text = na.getOpenBookList().takeItem(i).text();
1845                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1846                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1847                                         Notebook n = listManager.getNotebookIndex().get(j);
1848                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1849                                         j=listManager.getNotebookIndex().size();
1850                                 }
1851                         }
1852                 }
1853                 notebookTreeSelection();
1854                 listManager.loadNotesIndex();
1855                 notebookIndexUpdated();
1856                 noteIndexUpdated(false);
1857                 reloadTagTree(true);
1858 //              noteIndexUpdated(false);
1859                 
1860                 // Build a list of non-closed notebooks
1861                 List<Notebook> nbooks = new ArrayList<Notebook>();
1862                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1863                         boolean found=false;
1864                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1865                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1866                                         found = true;
1867                         }
1868                         if (!found)
1869                                 nbooks.add(listManager.getNotebookIndex().get(i));
1870                 }
1871                 
1872                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1873                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1874                 browserWindow.setNotebookList(filteredBooks);
1875                 
1876                 // Update any external windows
1877                 Iterator<String> set = externalWindows.keySet().iterator();
1878                 while(set.hasNext())
1879                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1880                 
1881                 waitCursor(false);
1882         }
1883         // Change the notebook's icon
1884         @SuppressWarnings("unused")
1885         private void setNotebookIcon() {
1886                 boolean stackSelected = false;
1887                 boolean allNotebookSelected = false;
1888                 
1889                 QTreeWidgetItem currentSelection;
1890                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1891                 if (selections.size() == 0)
1892                         return;
1893                 
1894                 currentSelection = selections.get(0);   
1895                 String guid = currentSelection.text(2);
1896                 if (guid.equalsIgnoreCase(""))
1897                         allNotebookSelected = true;
1898                 if (guid.equalsIgnoreCase("STACK"))
1899                         stackSelected = true;
1900
1901                 QIcon currentIcon = currentSelection.icon(0);
1902                 QIcon icon;
1903                 SetIcon dialog;
1904                 
1905                 if (!stackSelected && !allNotebookSelected) {
1906                         icon = conn.getNotebookTable().getIcon(guid);
1907                         if (icon == null) {
1908                                 dialog = new SetIcon(currentIcon, saveLastPath);
1909                                 dialog.setUseDefaultIcon(true);
1910                         } else {
1911                                 dialog = new SetIcon(icon, saveLastPath);
1912                                 dialog.setUseDefaultIcon(false);
1913                         }
1914                 } else {
1915                         if (stackSelected) {
1916                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1917                         } else {
1918                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
1919                         }
1920                         if (icon == null) {
1921                                 dialog = new SetIcon(currentIcon, saveLastPath);
1922                                 dialog.setUseDefaultIcon(true);
1923                         } else {
1924                                 dialog = new SetIcon(icon, saveLastPath);
1925                                 dialog.setUseDefaultIcon(false);
1926                         }
1927                 }
1928                 dialog.exec();
1929                 if (dialog.okPressed()) {
1930                 saveLastPath = dialog.getPath();
1931
1932                         QIcon newIcon = dialog.getIcon();
1933                         if (stackSelected) {
1934                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1935                                 if (newIcon == null) {
1936                                         newIcon = new QIcon(iconPath+"books2.png");
1937                                 }
1938                                 currentSelection.setIcon(0,newIcon);
1939                                 return;
1940                         }
1941                         if (allNotebookSelected) {
1942                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1943                                 if (newIcon == null) {
1944                                         newIcon = new QIcon(iconPath+"notebook-green.png");
1945                                 }
1946                                 currentSelection.setIcon(0,newIcon);
1947                                 return;
1948                         }
1949                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1950                         if (newIcon == null) {
1951                                 boolean isPublished = false;;
1952                                 boolean found = false;
1953                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1954                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1955                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1956                                                 found = true;
1957                                         }
1958                                 }
1959                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1960                         }
1961                         currentSelection.setIcon(0, newIcon);
1962                 }
1963         
1964         }
1965         
1966         
1967     //***************************************************************
1968     //***************************************************************
1969     //** These functions deal with Tag menu items
1970     //***************************************************************
1971     //***************************************************************
1972         // Add a new notebook
1973         @SuppressWarnings("unused")
1974         private void addTag() {
1975                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1976                 TagEdit edit = new TagEdit();
1977                 edit.setTagList(listManager.getTagIndex());
1978
1979                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1980                 QTreeWidgetItem currentSelection = null;
1981                 if (selections.size() > 0) {
1982                         currentSelection = selections.get(0);
1983                         edit.setParentTag(currentSelection.text(0));
1984                 }
1985
1986                 edit.exec();
1987         
1988                 if (!edit.okPressed())
1989                         return;
1990         
1991                 Calendar currentTime = new GregorianCalendar();
1992                 Long l = new Long(currentTime.getTimeInMillis());
1993                 String randint = new String(Long.toString(l));
1994         
1995                 Tag newTag = new Tag();
1996                 newTag.setUpdateSequenceNum(0);
1997                 newTag.setGuid(randint);
1998                 newTag.setName(edit.getTag());
1999                 if (edit.getParentTag().isChecked()) {
2000                         newTag.setParentGuid(currentSelection.text(2));
2001                         newTag.setParentGuidIsSet(true);
2002                         currentSelection.setExpanded(true);
2003                 }
2004                 conn.getTagTable().addTag(newTag, true);
2005                 listManager.getTagIndex().add(newTag);
2006                 reloadTagTree(true);
2007                 
2008                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2009         }
2010         @SuppressWarnings("unused")
2011         private void reloadTagTree() {
2012                 reloadTagTree(false);
2013         }
2014         private void reloadTagTree(boolean reload) {
2015                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2016                 tagIndexUpdated(reload);
2017                 boolean filter = false;
2018                 if (reload)
2019                         listManager.countTagResults(listManager.getNoteIndex());
2020                 if (notebookTree.selectedItems().size() > 0 
2021                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2022                                                   filter = true;
2023                 if (tagTree.selectedItems().size() > 0)
2024                         filter = true;
2025                 tagTree.showAllTags(!filter);
2026                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2027         }
2028         // Edit an existing tag
2029         @SuppressWarnings("unused")
2030         private void editTag() {
2031                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2032                 TagEdit edit = new TagEdit();
2033                 edit.setTitle("Edit Tag");
2034                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2035                 QTreeWidgetItem currentSelection;
2036                 currentSelection = selections.get(0);
2037                 edit.setTag(currentSelection.text(0));
2038                 edit.setTagList(listManager.getTagIndex());
2039                 edit.exec();
2040         
2041                 if (!edit.okPressed())
2042                         return;
2043         
2044                 String guid = currentSelection.text(2);
2045                 currentSelection.setText(0,edit.getTag());
2046                 
2047                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2048                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2049                                 listManager.getTagIndex().get(i).setName(edit.getTag());
2050                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2051                                 updateListTagName(guid);
2052                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2053                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2054                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2055                                 return;
2056                         }
2057                 }
2058                 browserWindow.setTag(getTagNamesForNote(currentNote));
2059                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2060         }
2061         // Delete an existing tag
2062         @SuppressWarnings("unused")
2063         private void deleteTag() {
2064                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2065                 
2066                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2067                         QMessageBox.StandardButton.Yes, 
2068                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2069                                                         return;
2070                 }
2071                 
2072                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2073         for (int i=selections.size()-1; i>=0; i--) {
2074                 QTreeWidgetItem currentSelection;
2075                 currentSelection = selections.get(i);                   
2076                 removeTagItem(currentSelection.text(2));
2077         }
2078         tagIndexUpdated(true);
2079         tagTreeSelection();
2080         listManager.countTagResults(listManager.getNoteIndex());
2081 //              tagTree.updateCounts(listManager.getTagCounter());
2082         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2083         }
2084         // Remove a tag tree item.  Go recursively down & remove the children too
2085         private void removeTagItem(String guid) {
2086         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2087                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2088                 if (parent != null && parent.equals(guid)) {            
2089                         //Remove this tag's children
2090                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2091                 }
2092         }
2093         //Now, remove this tag
2094         removeListTagName(guid);
2095         conn.getTagTable().expungeTag(guid, true);                      
2096         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2097                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2098                         listManager.getTagIndex().remove(a);
2099                         return;
2100                 }
2101         }
2102         }
2103         // Setup the tree containing the user's tags
2104     private void initializeTagTree() {
2105         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2106 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2107 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2108         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2109         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2110         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2111     }
2112     // Listener when a tag is selected
2113         private void tagTreeSelection() {
2114         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2115                 
2116         clearTrashFilter();
2117         clearAttributeFilter();
2118         clearSavedSearchFilter();
2119         
2120                 menuBar.noteRestoreAction.setVisible(false);
2121                 
2122         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2123         QTreeWidgetItem currentSelection;
2124         selectedTagGUIDs.clear();
2125         for (int i=0; i<selections.size(); i++) {
2126                 currentSelection = selections.get(i);
2127                 selectedTagGUIDs.add(currentSelection.text(2));
2128         }
2129         if (selections.size() > 0) {
2130                 menuBar.tagEditAction.setEnabled(true);
2131                 menuBar.tagDeleteAction.setEnabled(true);
2132                 menuBar.tagIconAction.setEnabled(true);
2133         }
2134         else {
2135                 menuBar.tagEditAction.setEnabled(false);
2136                 menuBar.tagDeleteAction.setEnabled(false);
2137                 menuBar.tagIconAction.setEnabled(true);
2138         }
2139         if (selections.size() > 1)
2140                 menuBar.tagMergeAction.setEnabled(true);
2141         else
2142                 menuBar.tagMergeAction.setEnabled(false);
2143         listManager.setSelectedTags(selectedTagGUIDs);
2144         listManager.loadNotesIndex();
2145         noteIndexUpdated(false);
2146         refreshEvernoteNote(true);
2147         listManager.refreshCounters = true;
2148         listManager.refreshCounters();
2149         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2150     }
2151     // trigger the tag index to be refreshed
2152     @SuppressWarnings("unused")
2153         private void tagIndexUpdated() {
2154         tagIndexUpdated(true);
2155     }
2156     private void tagIndexUpdated(boolean reload) {
2157         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2158                 if (selectedTagGUIDs == null)
2159                         selectedTagGUIDs = new ArrayList<String>();
2160                 if (reload)
2161                         listManager.reloadTagIndex();
2162
2163                 tagTree.blockSignals(true);
2164                 if (reload) {
2165                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2166                         tagTree.load(listManager.getTagIndex());
2167                 }
2168
2169         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2170                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2171                 if (!found)
2172                         selectedTagGUIDs.remove(i);
2173         }
2174         tagTree.blockSignals(false);
2175         
2176                 browserWindow.setTag(getTagNamesForNote(currentNote));
2177         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2178     }   
2179     // Show/Hide note information
2180         @SuppressWarnings("unused")
2181         private void toggleTagWindow() {
2182                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2183         if (tagTree.isVisible())
2184                 tagTree.hide();
2185         else
2186                 tagTree.show();
2187         menuBar.hideTags.setChecked(tagTree.isVisible());
2188         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2189         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2190     }   
2191         // A note's tags have been updated
2192         @SuppressWarnings("unused")
2193         private void updateNoteTags(String guid, List<String> tags) {
2194                 // Save any new tags.  We'll need them later.
2195                 List<String> newTags = new ArrayList<String>();
2196                 for (int i=0; i<tags.size(); i++) {
2197                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2198                                 newTags.add(tags.get(i));
2199                 }
2200                 
2201                 listManager.saveNoteTags(guid, tags);
2202                 listManager.countTagResults(listManager.getNoteIndex());
2203                 StringBuffer names = new StringBuffer("");
2204                 for (int i=0; i<tags.size(); i++) {
2205                         names = names.append(tags.get(i));
2206                         if (i<tags.size()-1) {
2207                                 names.append(Global.tagDelimeter + " ");
2208                         }
2209                 }
2210                 browserWindow.setTag(names.toString());
2211                 noteDirty = true;
2212                 
2213                 // Now, we need to add any new tags to the tag tree
2214                 for (int i=0; i<newTags.size(); i++) 
2215                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2216         }
2217         // Get a string containing all tag names for a note
2218         private String getTagNamesForNote(Note n) {
2219                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2220                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2221                         return "";
2222                 StringBuffer buffer = new StringBuffer(100);
2223                 Vector<String> v = new Vector<String>();
2224                 List<String> guids = n.getTagGuids();
2225                 
2226                 if (guids == null) 
2227                         return "";
2228                 
2229                 for (int i=0; i<guids.size(); i++) {
2230                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2231                 }
2232                 Comparator<String> comparator = Collections.reverseOrder();
2233                 Collections.sort(v,comparator);
2234                 Collections.reverse(v);
2235                 
2236                 for (int i = 0; i<v.size(); i++) {
2237                         if (i>0) 
2238                                 buffer.append(", ");
2239                         buffer.append(v.get(i));
2240                 }
2241                 
2242                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2243                 return buffer.toString();
2244         }       
2245         // Tags were added via dropping notes from the note list
2246         @SuppressWarnings("unused")
2247         private void tagsAdded(String noteGuid, String tagGuid) {
2248                 String tagName = null;
2249                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2250                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2251                                 tagName = listManager.getTagIndex().get(i).getName();
2252                                 i=listManager.getTagIndex().size();
2253                         }
2254                 }
2255                 if (tagName == null)
2256                         return;
2257                 
2258                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2259                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2260                                 List<String> tagNames = new ArrayList<String>();
2261                                 tagNames.add(new String(tagName));
2262                                 Note n = listManager.getMasterNoteIndex().get(i);
2263                                 for (int j=0; j<n.getTagNames().size(); j++) {
2264                                         tagNames.add(new String(n.getTagNames().get(j)));
2265                                 }
2266                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2267                                 if (n.getGuid().equals(currentNoteGuid)) {
2268                                         Collections.sort(tagNames);
2269                                         String display = "";
2270                                         for (int j=0; j<tagNames.size(); j++) {
2271                                                 display = display+tagNames.get(j);
2272                                                 if (j+2<tagNames.size()) 
2273                                                         display = display+Global.tagDelimeter+" ";
2274                                         }
2275                                         browserWindow.setTag(display);
2276                                 }
2277                                 i=listManager.getMasterNoteIndex().size();
2278                         }
2279                 }
2280                 
2281                 
2282                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2283         }
2284         private void clearTagFilter() {
2285                 tagTree.blockSignals(true);
2286                 tagTree.clearSelection();
2287                 menuBar.noteRestoreAction.setVisible(false);
2288                 menuBar.tagEditAction.setEnabled(false);
2289                 menuBar.tagMergeAction.setEnabled(false);
2290                 menuBar.tagDeleteAction.setEnabled(false);
2291                 menuBar.tagIconAction.setEnabled(false);
2292                 selectedTagGUIDs.clear();
2293         listManager.setSelectedTags(selectedTagGUIDs);
2294         tagTree.blockSignals(false);
2295         }
2296         // Change the icon for a tag
2297         @SuppressWarnings("unused")
2298         private void setTagIcon() {
2299                 QTreeWidgetItem currentSelection;
2300                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2301                 if (selections.size() == 0)
2302                         return;
2303                 
2304                 currentSelection = selections.get(0);   
2305                 String guid = currentSelection.text(2);
2306
2307                 QIcon currentIcon = currentSelection.icon(0);
2308                 QIcon icon = conn.getTagTable().getIcon(guid);
2309                 SetIcon dialog;
2310                 if (icon == null) {
2311                         dialog = new SetIcon(currentIcon, saveLastPath);
2312                         dialog.setUseDefaultIcon(true);
2313                 } else {
2314                         dialog = new SetIcon(icon, saveLastPath);
2315                         dialog.setUseDefaultIcon(false);
2316                 }
2317                 dialog.exec();
2318                 if (dialog.okPressed()) {
2319                 saveLastPath = dialog.getPath();
2320                         QIcon newIcon = dialog.getIcon();
2321                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2322                         if (newIcon == null) 
2323                                 newIcon = new QIcon(iconPath+"tag.png");
2324                         currentSelection.setIcon(0, newIcon);
2325                 }
2326         
2327         }
2328         // Merge tags
2329         @SuppressWarnings("unused")
2330         private void mergeTags() {
2331                 List<Tag> tags = new ArrayList<Tag>();
2332                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2333                 for (int i=0; i<selections.size(); i++) {
2334                         Tag record = new Tag();
2335                         record.setGuid(selections.get(i).text(2));
2336                         record.setName(selections.get(i).text(0));
2337                         tags.add(record);
2338                 }
2339
2340                 TagMerge mergeDialog = new TagMerge(tags);
2341                 mergeDialog.exec();
2342                 if (!mergeDialog.okClicked())
2343                         return;
2344                 String newGuid = mergeDialog.getNewTagGuid();
2345                 
2346                 for (int i=0; i<tags.size(); i++) {
2347                         if (!tags.get(i).getGuid().equals(newGuid)) {
2348                                 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2349                                 for (int j=0; j<noteGuids.size(); j++) {
2350                                         String noteGuid = noteGuids.get(j);
2351                                         conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2352                                         if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2353                                                 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2354                                 }
2355                         }
2356                 }
2357                 listManager.reloadIndexes();
2358         }
2359         
2360     //***************************************************************
2361     //***************************************************************
2362     //** These functions deal with Saved Search menu items
2363     //***************************************************************
2364     //***************************************************************
2365         // Add a new notebook
2366         @SuppressWarnings("unused")
2367         private void addSavedSearch() {
2368                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2369                 SavedSearchEdit edit = new SavedSearchEdit();
2370                 edit.setSearchList(listManager.getSavedSearchIndex());
2371                 edit.exec();
2372         
2373                 if (!edit.okPressed())
2374                         return;
2375         
2376                 Calendar currentTime = new GregorianCalendar();         
2377                 Long l = new Long(currentTime.getTimeInMillis());
2378                 String randint = new String(Long.toString(l));
2379         
2380                 SavedSearch search = new SavedSearch();
2381                 search.setUpdateSequenceNum(0);
2382                 search.setGuid(randint);
2383                 search.setName(edit.getName());
2384                 search.setQuery(edit.getQuery());
2385                 search.setFormat(QueryFormat.USER);
2386                 listManager.getSavedSearchIndex().add(search);
2387                 conn.getSavedSearchTable().addSavedSearch(search, true);
2388                 savedSearchIndexUpdated();
2389                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2390         }
2391         // Edit an existing tag
2392         @SuppressWarnings("unused")
2393         private void editSavedSearch() {
2394                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2395                 SavedSearchEdit edit = new SavedSearchEdit();
2396                 edit.setTitle(tr("Edit Search"));
2397                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2398                 QTreeWidgetItem currentSelection;
2399                 currentSelection = selections.get(0);
2400                 String guid = currentSelection.text(1);
2401                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2402                 edit.setName(currentSelection.text(0));
2403                 edit.setQuery(s.getQuery());
2404                 edit.setSearchList(listManager.getSavedSearchIndex());
2405                 edit.exec();
2406         
2407                 if (!edit.okPressed())
2408                         return;
2409         
2410                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2411                 SavedSearch search = null;
2412                 boolean found = false;
2413                 for (int i=0; i<list.size(); i++) {
2414                         search = list.get(i);
2415                         if (search.getGuid().equals(guid)) {
2416                                 i=list.size();
2417                                 found = true;
2418                         }
2419                 }
2420                 if (!found)
2421                         return;
2422                 search.setName(edit.getName());
2423                 search.setQuery(edit.getQuery());
2424                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2425                 savedSearchIndexUpdated();
2426                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2427         }
2428         // Delete an existing tag
2429         @SuppressWarnings("unused")
2430         private void deleteSavedSearch() {
2431                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2432                 
2433                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2434                         QMessageBox.StandardButton.Yes, 
2435                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2436                                                         return;
2437                 }
2438                 
2439                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2440         for (int i=selections.size()-1; i>=0; i--) {
2441                 QTreeWidgetItem currentSelection;
2442                 currentSelection = selections.get(i);
2443                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2444                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2445                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2446                                 listManager.getSavedSearchIndex().remove(j);
2447                                 j=listManager.getSavedSearchIndex().size()+1;
2448                         }
2449                 }
2450                 selections.remove(i);
2451         }
2452         savedSearchIndexUpdated();
2453         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2454         }
2455     // Setup the tree containing the user's tags
2456     private void initializeSavedSearchTree() {
2457         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2458         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2459         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2460     }
2461     // Listener when a tag is selected
2462     @SuppressWarnings("unused")
2463         private void savedSearchTreeSelection() {
2464         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2465
2466         clearNotebookFilter();
2467         clearTagFilter();
2468         clearTrashFilter();
2469         clearAttributeFilter();
2470         
2471         String currentGuid = selectedSavedSearchGUID;
2472         menuBar.savedSearchEditAction.setEnabled(true);
2473         menuBar.savedSearchDeleteAction.setEnabled(true);
2474         menuBar.savedSearchIconAction.setEnabled(true);
2475         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2476         QTreeWidgetItem currentSelection;
2477         selectedSavedSearchGUID = "";
2478         for (int i=0; i<selections.size(); i++) {
2479                 currentSelection = selections.get(i);
2480                 if (currentSelection.text(1).equals(currentGuid)) {
2481                         currentSelection.setSelected(false);
2482                 } else {
2483                         selectedSavedSearchGUID = currentSelection.text(1);
2484                 }
2485 //              i = selections.size() +1;
2486         }
2487         
2488         // There is the potential for no notebooks to be selected if this 
2489         // happens then we make it look like all notebooks were selecetd.
2490         // If that happens, just select the "all notebooks"
2491         if (selections.size()==0) {
2492                 clearSavedSearchFilter();
2493         }
2494         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2495         
2496         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2497     }
2498     private void clearSavedSearchFilter() {
2499         menuBar.savedSearchEditAction.setEnabled(false);
2500         menuBar.savedSearchDeleteAction.setEnabled(false);
2501         menuBar.savedSearchIconAction.setEnabled(false);
2502         savedSearchTree.blockSignals(true);
2503         savedSearchTree.clearSelection();
2504         savedSearchTree.blockSignals(false);
2505         selectedSavedSearchGUID = "";
2506         searchField.setEditText("");
2507         searchPerformed = false;
2508         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2509     }
2510     // trigger the tag index to be refreshed
2511         private void savedSearchIndexUpdated() { 
2512                 if (selectedSavedSearchGUID == null)
2513                         selectedSavedSearchGUID = new String();
2514                 savedSearchTree.blockSignals(true);
2515                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2516         savedSearchTree.load(listManager.getSavedSearchIndex());
2517         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2518         savedSearchTree.blockSignals(false);
2519     }
2520     // trigger when the saved search selection changes
2521     @SuppressWarnings("unused")
2522         private void updateSavedSearchSelection() {
2523                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2524                 
2525         menuBar.savedSearchEditAction.setEnabled(true);
2526         menuBar.savedSearchDeleteAction.setEnabled(true);
2527         menuBar.savedSearchIconAction.setEnabled(true);
2528         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2529
2530         if (selections.size() > 0) {
2531                 menuBar.savedSearchEditAction.setEnabled(true);
2532                 menuBar.savedSearchDeleteAction.setEnabled(true);
2533                 menuBar.savedSearchIconAction.setEnabled(true);
2534                 selectedSavedSearchGUID = selections.get(0).text(1);
2535                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2536                 searchField.setEditText(s.getQuery());
2537         } else { 
2538                 menuBar.savedSearchEditAction.setEnabled(false);
2539                 menuBar.savedSearchDeleteAction.setEnabled(false);
2540                 menuBar.savedSearchIconAction.setEnabled(false);
2541                 selectedSavedSearchGUID = "";
2542                 searchField.setEditText("");
2543         }
2544         searchFieldChanged();
2545         
2546                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2547
2548         
2549     }
2550     // Show/Hide note information
2551         @SuppressWarnings("unused")
2552         private void toggleSavedSearchWindow() {
2553                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2554         if (savedSearchTree.isVisible())
2555                 savedSearchTree.hide();
2556         else
2557                 savedSearchTree.show();
2558         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2559                                 
2560                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2561         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2562     }
2563         // Change the icon for a saved search
2564         @SuppressWarnings("unused")
2565         private void setSavedSearchIcon() {
2566                 QTreeWidgetItem currentSelection;
2567                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2568                 if (selections.size() == 0)
2569                         return;
2570                 
2571                 currentSelection = selections.get(0);   
2572                 String guid = currentSelection.text(1);
2573
2574                 QIcon currentIcon = currentSelection.icon(0);
2575                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2576                 SetIcon dialog;
2577                 if (icon == null) {
2578                         dialog = new SetIcon(currentIcon, saveLastPath);
2579                         dialog.setUseDefaultIcon(true);
2580                 } else {
2581                         dialog = new SetIcon(icon, saveLastPath);
2582                         dialog.setUseDefaultIcon(false);
2583                 }
2584                 dialog.exec();
2585                 if (dialog.okPressed()) {
2586                 saveLastPath = dialog.getPath();
2587                         QIcon newIcon = dialog.getIcon();
2588                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2589                         if (newIcon == null) 
2590                                 newIcon = new QIcon(iconPath+"search.png");
2591                         currentSelection.setIcon(0, newIcon);
2592                 }
2593         
2594         }
2595         
2596         
2597         
2598         
2599     //***************************************************************
2600     //***************************************************************
2601     //** These functions deal with Help menu & tool menu items
2602     //***************************************************************
2603     //***************************************************************
2604         // Show database status
2605         @SuppressWarnings("unused")
2606         private void databaseStatus() {
2607                 waitCursor(true);
2608                 indexRunner.interrupt = true;
2609                 int dirty = conn.getNoteTable().getDirtyCount();
2610                 int unindexed = conn.getNoteTable().getUnindexedCount();
2611                 DatabaseStatus status = new DatabaseStatus();
2612                 status.setUnsynchronized(dirty);
2613                 status.setUnindexed(unindexed);
2614                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2615                 status.setNotebookCount(listManager.getNotebookIndex().size());
2616                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2617                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2618                 status.setTagCount(listManager.getTagIndex().size());
2619                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2620                 status.setWordCount(conn.getWordsTable().getWordCount());
2621                 waitCursor(false);
2622                 status.exec();
2623         }
2624         // Compact the database
2625         @SuppressWarnings("unused")
2626         private void compactDatabase() {
2627         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2628                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2629                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2630                                 "and NeverNote will be unresponsive until it is complete.  Do you wish to continue?"),
2631                                 QMessageBox.StandardButton.Yes, 
2632                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2633                                                         return;
2634                 }
2635                 setMessage("Compacting database.");
2636                 waitCursor(true);
2637                 listManager.compactDatabase();
2638                 waitCursor(false);
2639                 setMessage("Database compact is complete.");            
2640         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2641     }
2642         @SuppressWarnings("unused")
2643         private void accountInformation() {
2644                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2645                 AccountDialog dialog = new AccountDialog();
2646                 dialog.show();
2647                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2648         }
2649         @SuppressWarnings("unused")
2650         private void releaseNotes() {
2651                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2652                 QDialog dialog = new QDialog(this);
2653                 QHBoxLayout layout = new QHBoxLayout();
2654                 QTextEdit textBox = new QTextEdit();
2655                 layout.addWidget(textBox);
2656                 textBox.setReadOnly(true);
2657                 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2658                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2659                 QIODevice.OpenModeFlag.Text)))
2660                         return;
2661                 textBox.setText(file.readAll().toString());
2662                 file.close();
2663                 dialog.setWindowTitle(tr("Release Notes"));
2664                 dialog.setLayout(layout);
2665                 dialog.show();
2666                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2667         }
2668         // Called when user picks Log from the help menu
2669         @SuppressWarnings("unused")
2670         private void logger() {
2671                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2672                 LogFileDialog dialog = new LogFileDialog(emitLog);
2673                 dialog.exec();
2674                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2675         }
2676         // Menu option "help/about" was selected
2677         @SuppressWarnings("unused")
2678         private void about() {
2679                 logger.log(logger.HIGH, "Entering NeverNote.about");
2680                 QMessageBox.about(this, 
2681                                                 tr("About NeverNote"),
2682                                                 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2683                                                 +Global.version
2684                                                 +tr("<hr></center>Evernote"
2685                                                                 +"An Open Source Evernote Client.<br><br>" 
2686                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2687                                                                 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2688                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2689                                                                 +"PDFRenderer is licened under the LGPL<br>"
2690                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2691                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2692                                                                 +"Jazzy is licened under the LGPL<br>"
2693                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2694                                                                 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2695                                                                 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2696                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2697         }
2698         // Hide the entire left hand side
2699         @SuppressWarnings("unused")
2700         private void toggleLeftSide() {
2701                 boolean hidden;
2702                 
2703                 hidden = !menuBar.hideLeftSide.isChecked();
2704                 menuBar.hideLeftSide.setChecked(!hidden);
2705                 
2706                 if (!hidden) 
2707                         leftSplitter1.setHidden(true);
2708                 else
2709                         leftSplitter1.setHidden(false);
2710                 
2711                 Global.saveWindowVisible("leftPanel", hidden);
2712                 
2713         }
2714         public void checkForUpdates() {
2715                 // Send off thread to check for a new version
2716                 versionChecker = new QNetworkAccessManager(this);
2717                 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2718                 QNetworkRequest request = new QNetworkRequest();
2719                 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2720                 versionChecker.get(request);
2721         }
2722         @SuppressWarnings("unused")
2723         private void upgradeFileRead(QNetworkReply reply) {
2724                 if (!reply.isReadable())
2725                         return;
2726                 
2727                 String winVersion = Global.version;
2728                 String osxVersion = Global.version;
2729                 String linuxVersion = Global.version;
2730                 String linux64Version = Global.version;
2731                 String version = Global.version;
2732                 
2733                 // Determine the versions available
2734                 QByteArray data = reply.readLine();
2735                 while (data != null && !reply.atEnd()) {
2736                         String line = data.toString();
2737                         String lineVersion;
2738                         if (line.contains(":")) 
2739                                 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2740                         else
2741                                 lineVersion = "";
2742                         if (line.toLowerCase().contains("windows")) 
2743                                 winVersion = lineVersion;
2744                         else if (line.toLowerCase().contains("os-x")) 
2745                                 osxVersion = lineVersion;
2746                         else if (line.toLowerCase().contains("linux amd64")) 
2747                                 linux64Version = lineVersion;
2748                         else if (line.toLowerCase().contains("linux i386")) 
2749                                 linuxVersion = lineVersion;
2750                         else if (line.toLowerCase().contains("default")) 
2751                                 version = lineVersion;
2752                         
2753                         // Read the next line
2754                         data = reply.readLine();
2755                 }
2756                 
2757                 // Now we need to determine what system we are on.
2758                 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2759                         version = winVersion;
2760                 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2761                         version = osxVersion;
2762                 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2763                         if (System.getProperty("os.arch").contains("amd64") ||
2764                                 System.getProperty("os.arch").contains("x86_64"))
2765                                         version = linux64Version;
2766                         else
2767                                 version = linuxVersion;
2768                 }
2769                 
2770                 
2771                 for (String validVersion : Global.validVersions) {
2772                         if (version.equals(validVersion))
2773                                 return;
2774                 }
2775                 
2776                 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2777                 dialog.exec();
2778                 if (dialog.remindMe())
2779                         Global.setCheckVersionUpgrade(true);
2780                 else
2781                         Global.setCheckVersionUpgrade(false);
2782         }
2783                 
2784         
2785     //***************************************************************
2786     //***************************************************************
2787     //** These functions deal with the Toolbar
2788     //***************************************************************
2789     //*************************************************************** 
2790         @SuppressWarnings("unused")
2791         private void focusSearch() {
2792                 searchField.setFocus();
2793         }
2794
2795         // Text in the search bar has been cleared
2796         private void searchFieldCleared() {
2797                 saveNote();
2798                 
2799                 // This is done because we want to force a reload of
2800                 // images.  Some images we may want to highlight the text.
2801                 readOnlyCache.clear();
2802                 inkNoteCache.clear();
2803                 noteCache.clear();
2804                 QWebSettings.setMaximumPagesInCache(0);
2805                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2806         
2807                 searchField.setEditText("");
2808                 saveNoteColumnPositions();
2809                 saveNoteIndexWidth();
2810                 noteIndexUpdated(true);
2811                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2812                         currentNote = listManager.getNoteIndex().get(0);
2813                         currentNoteGuid = currentNote.getGuid();
2814                 }
2815                 refreshEvernoteNote(true);
2816                 if (currentNote != null)
2817                         loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2818         }
2819         // text in the search bar changed.  We only use this to tell if it was cleared, 
2820         // otherwise we trigger off searchFieldChanged.
2821         @SuppressWarnings("unused")
2822         private void searchFieldTextChanged(String text) {
2823                 QWebSettings.setMaximumPagesInCache(0);
2824                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2825
2826                 if (text.trim().equals("")) {
2827                         searchFieldCleared();
2828                         if (searchPerformed) {
2829
2830                                 // This is done because we want to force a reload of
2831                                 // images.  Some images we may want to highlight the text.
2832                                 noteCache.clear();
2833                                 readOnlyCache.clear();
2834                                 inkNoteCache.clear();
2835                                 
2836                                 listManager.setEnSearch("");
2837                                 listManager.loadNotesIndex();
2838                                 refreshEvernoteNote(true);
2839                                 noteIndexUpdated(false);
2840                                 refreshEvernoteNote(true);
2841                         }
2842                         searchPerformed = false;
2843                 }
2844         }
2845     // Text in the toolbar has changed
2846     private void searchFieldChanged() {
2847         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2848         noteCache.clear();
2849         readOnlyCache.clear();
2850         inkNoteCache.clear();
2851         saveNoteColumnPositions();
2852         saveNoteIndexWidth();
2853         String text = searchField.currentText();
2854         listManager.setEnSearch(text.trim());
2855         listManager.loadNotesIndex();
2856         noteIndexUpdated(false);
2857         refreshEvernoteNote(true);
2858         searchPerformed = true;
2859         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2860     }
2861
2862     // Build the window tool bar
2863     private void setupToolBar() {
2864         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2865         toolBar = addToolBar(tr("Tool Bar"));   
2866         toolBar.setObjectName("toolBar");
2867         menuBar.setupToolBarVisible();
2868         if (!Global.isWindowVisible("toolBar"))
2869                 toolBar.setVisible(false);
2870         else
2871                 toolBar.setVisible(true);
2872
2873 //      toolBar.addWidget(menuBar);
2874 //      menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2875 //      toolBar.addSeparator();
2876         prevButton = toolBar.addAction(tr("Previous"));
2877         QIcon prevIcon = new QIcon(iconPath+"back.png");
2878         prevButton.setIcon(prevIcon);
2879         prevButton.triggered.connect(this, "previousViewedAction()");   
2880         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2881         
2882         nextButton = toolBar.addAction(tr("Next"));
2883         QIcon nextIcon = new QIcon(iconPath+"forward.png");
2884         nextButton.setIcon(nextIcon);
2885         nextButton.triggered.connect(this, "nextViewedAction()");       
2886         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2887         
2888         upButton = toolBar.addAction(tr("Up"));
2889         QIcon upIcon = new QIcon(iconPath+"up.png");
2890         upButton.setIcon(upIcon);
2891         upButton.triggered.connect(this, "upAction()");         
2892         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2893
2894         
2895         downButton = toolBar.addAction(tr("Down"));
2896         QIcon downIcon = new QIcon(iconPath+"down.png");
2897         downButton.setIcon(downIcon);
2898         downButton.triggered.connect(this, "downAction()");
2899         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2900         
2901         synchronizeButton = toolBar.addAction(tr("Synchronize"));
2902         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2903         synchronizeIconAngle = 0;
2904         synchronizeButton.triggered.connect(this, "evernoteSync()");
2905         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2906         
2907         printButton = toolBar.addAction(tr("Print"));
2908         QIcon printIcon = new QIcon(iconPath+"print.png");
2909         printButton.setIcon(printIcon);
2910         printButton.triggered.connect(this, "printNote()");
2911         togglePrintButton(Global.isToolbarButtonVisible("print"));
2912
2913         tagButton = toolBar.addAction(tr("Tag")); 
2914         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2915         tagButton.setIcon(tagIcon);
2916         tagButton.triggered.connect(browserWindow, "modifyTags()");
2917         toggleTagButton(Global.isToolbarButtonVisible("tag"));
2918
2919         attributeButton = toolBar.addAction(tr("Attributes")); 
2920         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2921         attributeButton.setIcon(attributeIcon);
2922         attributeButton.triggered.connect(this, "toggleNoteInformation()");
2923         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2924                 
2925         emailButton = toolBar.addAction(tr("Email"));
2926         QIcon emailIcon = new QIcon(iconPath+"email.png");
2927         emailButton.setIcon(emailIcon);
2928         emailButton.triggered.connect(this, "emailNote()");
2929         toggleEmailButton(Global.isToolbarButtonVisible("email"));
2930
2931         deleteButton = toolBar.addAction(tr("Delete"));         
2932         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2933         deleteButton.setIcon(deleteIcon);
2934         deleteButton.triggered.connect(this, "deleteNote()");
2935         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2936
2937         newButton = toolBar.addAction(tr("New"));
2938         QIcon newIcon = new QIcon(iconPath+"new.png");
2939         newButton.triggered.connect(this, "addNote()");
2940         newButton.setIcon(newIcon);
2941         toggleNewButton(Global.isToolbarButtonVisible("new"));
2942         
2943         allNotesButton = toolBar.addAction(tr("All Notes"));
2944         QIcon allIcon = new QIcon(iconPath+"books.png");
2945         allNotesButton.triggered.connect(this, "allNotes()");
2946         allNotesButton.setIcon(allIcon);
2947         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2948         
2949         //toolBar.addSeparator();
2950         //toolBar.addWidget(new QLabel(tr("Quota:")));
2951         //toolBar.addWidget(quotaBar);
2952         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2953         updateQuotaBar();
2954         //toolBar.addSeparator();
2955         
2956         //toolBar.addWidget(new QLabel(tr("Zoom")));
2957         //toolBar.addWidget(zoomSpinner);
2958         
2959         //toolBar.addWidget(new QLabel("                    "));
2960         //toolBar.addSeparator();
2961         //toolBar.addWidget(new QLabel(tr("  Search:")));
2962         //toolBar.addWidget(searchField);
2963         QSizePolicy sizePolicy = new QSizePolicy();
2964         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2965         QLabel spacer = new QLabel("");
2966         spacer.setSizePolicy(sizePolicy);
2967         toolBar.addWidget(spacer);
2968         //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2969
2970         //searchClearButton = toolBar.addAction("Search Clear");
2971         //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2972         //searchClearButton.setIcon(searchClearIcon);
2973         //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2974         //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2975
2976         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2977     }
2978     // Update the sychronize button picture
2979     @Override
2980         public QMenu createPopupMenu() {
2981         QMenu contextMenu = super.createPopupMenu();
2982         
2983         contextMenu.addSeparator();
2984         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2985         contextMenu.addAction(prevAction);
2986         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2987
2988         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2989         contextMenu.addAction(nextAction);
2990         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2991
2992         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2993         contextMenu.addAction(upAction);
2994         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2995
2996         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2997         contextMenu.addAction(downAction);
2998         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2999
3000         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3001         contextMenu.addAction(synchronizeAction);
3002         synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3003
3004         QAction printAction = addContextAction("print", tr("Print"));
3005         contextMenu.addAction(printAction);
3006         printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3007
3008         QAction tagAction = addContextAction("tag", tr("Tag"));
3009         contextMenu.addAction(tagAction);
3010         tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3011         
3012         QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3013         contextMenu.addAction(attributeAction);
3014         attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3015         
3016         QAction emailAction = addContextAction("email", tr("Email"));
3017         contextMenu.addAction(emailAction);
3018         emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3019
3020         QAction deleteAction = addContextAction("delete", tr("Delete"));
3021         contextMenu.addAction(deleteAction);
3022         deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3023
3024         QAction newAction = addContextAction("new", tr("Add"));
3025         contextMenu.addAction(newAction);
3026         newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3027
3028         QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3029         contextMenu.addAction(allNotesAction);
3030         allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3031         
3032         QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3033         contextMenu.addAction(searchClearAction);
3034         searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3035         
3036         return contextMenu;
3037         
3038     }
3039     private QAction addContextAction(String config, String name) {
3040         QAction newAction = new QAction(this);
3041                 newAction.setText(name);
3042                 newAction.setCheckable(true);
3043                 newAction.setChecked(Global.isToolbarButtonVisible(config));
3044                 return newAction;
3045     }
3046     private void togglePrevArrowButton(Boolean toggle) {
3047                 prevButton.setVisible(toggle);
3048                 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3049     }
3050     private void toggleNextArrowButton(Boolean toggle) {