OSDN Git Service

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