OSDN Git Service

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