OSDN Git Service

- Correct issue with importing when not a premium member.
[neighbornote/NeighborNote.git] / src / cx / fbn / nevernote / NeverNote.java
1 /*
2   * This file is part of NixNote 
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.io.FileOutputStream;
25 import java.net.Authenticator;
26 import java.net.PasswordAuthentication;
27 import java.security.MessageDigest;
28 import java.security.NoSuchAlgorithmException;
29 import java.sql.Connection;
30 import java.sql.DriverManager;
31 import java.sql.SQLException;
32 import java.sql.Statement;
33 import java.text.SimpleDateFormat;
34 import java.util.ArrayList;
35 import java.util.Calendar;
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.Comparator;
39 import java.util.Date;
40 import java.util.GregorianCalendar;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.SortedMap;
45 import java.util.Vector;
46
47 import org.apache.log4j.Level;
48 import org.apache.log4j.Logger;
49 import org.apache.thrift.TException;
50 import org.h2.tools.ChangeFileEncryption;
51
52 import com.evernote.edam.error.EDAMNotFoundException;
53 import com.evernote.edam.error.EDAMSystemException;
54 import com.evernote.edam.error.EDAMUserException;
55 import com.evernote.edam.notestore.NoteFilter;
56 import com.evernote.edam.notestore.NoteVersionId;
57 import com.evernote.edam.type.Data;
58 import com.evernote.edam.type.LinkedNotebook;
59 import com.evernote.edam.type.Note;
60 import com.evernote.edam.type.NoteAttributes;
61 import com.evernote.edam.type.Notebook;
62 import com.evernote.edam.type.Publishing;
63 import com.evernote.edam.type.QueryFormat;
64 import com.evernote.edam.type.Resource;
65 import com.evernote.edam.type.SavedSearch;
66 import com.evernote.edam.type.Tag;
67 import com.evernote.edam.type.User;
68 import com.trolltech.qt.QThread;
69 import com.trolltech.qt.core.QByteArray;
70 import com.trolltech.qt.core.QDateTime;
71 import com.trolltech.qt.core.QDir;
72 import com.trolltech.qt.core.QEvent;
73 import com.trolltech.qt.core.QFile;
74 import com.trolltech.qt.core.QFileInfo;
75 import com.trolltech.qt.core.QFileSystemWatcher;
76 import com.trolltech.qt.core.QIODevice;
77 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
78 import com.trolltech.qt.core.QLocale;
79 import com.trolltech.qt.core.QMimeData;
80 import com.trolltech.qt.core.QModelIndex;
81 import com.trolltech.qt.core.QSize;
82 import com.trolltech.qt.core.QTemporaryFile;
83 import com.trolltech.qt.core.QTextCodec;
84 import com.trolltech.qt.core.QThreadPool;
85 import com.trolltech.qt.core.QTimer;
86 import com.trolltech.qt.core.QTranslator;
87 import com.trolltech.qt.core.QUrl;
88 import com.trolltech.qt.core.Qt;
89 import com.trolltech.qt.core.Qt.BGMode;
90 import com.trolltech.qt.core.Qt.ItemDataRole;
91 import com.trolltech.qt.core.Qt.KeyboardModifier;
92 import com.trolltech.qt.core.Qt.MouseButton;
93 import com.trolltech.qt.core.Qt.SortOrder;
94 import com.trolltech.qt.core.Qt.WidgetAttribute;
95 import com.trolltech.qt.gui.QAbstractItemView;
96 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
97 import com.trolltech.qt.gui.QAction;
98 import com.trolltech.qt.gui.QApplication;
99 import com.trolltech.qt.gui.QClipboard;
100 import com.trolltech.qt.gui.QCloseEvent;
101 import com.trolltech.qt.gui.QColor;
102 import com.trolltech.qt.gui.QComboBox;
103 import com.trolltech.qt.gui.QCursor;
104 import com.trolltech.qt.gui.QDesktopServices;
105 import com.trolltech.qt.gui.QDialog;
106 import com.trolltech.qt.gui.QFileDialog;
107 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
108 import com.trolltech.qt.gui.QFileDialog.FileMode;
109 import com.trolltech.qt.gui.QGridLayout;
110 import com.trolltech.qt.gui.QHBoxLayout;
111 import com.trolltech.qt.gui.QIcon;
112 import com.trolltech.qt.gui.QImage;
113 import com.trolltech.qt.gui.QKeySequence;
114 import com.trolltech.qt.gui.QLabel;
115 import com.trolltech.qt.gui.QMainWindow;
116 import com.trolltech.qt.gui.QMenu;
117 import com.trolltech.qt.gui.QMessageBox;
118 import com.trolltech.qt.gui.QMessageBox.StandardButton;
119 import com.trolltech.qt.gui.QPainter;
120 import com.trolltech.qt.gui.QPalette.ColorRole;
121 import com.trolltech.qt.gui.QPixmap;
122 import com.trolltech.qt.gui.QPrintDialog;
123 import com.trolltech.qt.gui.QPrinter;
124 import com.trolltech.qt.gui.QShortcut;
125 import com.trolltech.qt.gui.QSizePolicy;
126 import com.trolltech.qt.gui.QSizePolicy.Policy;
127 import com.trolltech.qt.gui.QSpinBox;
128 import com.trolltech.qt.gui.QSplashScreen;
129 import com.trolltech.qt.gui.QSplitter;
130 import com.trolltech.qt.gui.QStatusBar;
131 import com.trolltech.qt.gui.QSystemTrayIcon;
132 import com.trolltech.qt.gui.QTableWidgetItem;
133 import com.trolltech.qt.gui.QTextEdit;
134 import com.trolltech.qt.gui.QToolBar;
135 import com.trolltech.qt.gui.QTreeWidgetItem;
136 import com.trolltech.qt.network.QNetworkAccessManager;
137 import com.trolltech.qt.network.QNetworkReply;
138 import com.trolltech.qt.network.QNetworkRequest;
139 import com.trolltech.qt.webkit.QWebPage.WebAction;
140 import com.trolltech.qt.webkit.QWebSettings;
141
142 import cx.fbn.nevernote.config.InitializationException;
143 import cx.fbn.nevernote.config.StartupConfig;
144 import cx.fbn.nevernote.dialog.AccountDialog;
145 import cx.fbn.nevernote.dialog.ConfigDialog;
146 import cx.fbn.nevernote.dialog.DBEncryptDialog;
147 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
148 import cx.fbn.nevernote.dialog.DatabaseStatus;
149 import cx.fbn.nevernote.dialog.FindDialog;
150 import cx.fbn.nevernote.dialog.IgnoreSync;
151 import cx.fbn.nevernote.dialog.LogFileDialog;
152 import cx.fbn.nevernote.dialog.NotebookArchive;
153 import cx.fbn.nevernote.dialog.NotebookEdit;
154 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
155 import cx.fbn.nevernote.dialog.PublishNotebook;
156 import cx.fbn.nevernote.dialog.SavedSearchEdit;
157 import cx.fbn.nevernote.dialog.SetIcon;
158 import cx.fbn.nevernote.dialog.ShareNotebook;
159 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
160 import cx.fbn.nevernote.dialog.StackNotebook;
161 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
162 import cx.fbn.nevernote.dialog.TagEdit;
163 import cx.fbn.nevernote.dialog.TagMerge;
164 import cx.fbn.nevernote.dialog.ThumbnailViewer;
165 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
166 import cx.fbn.nevernote.dialog.WatchFolder;
167 import cx.fbn.nevernote.evernote.NoteMetadata;
168 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
169 import cx.fbn.nevernote.filters.FilterEditorTags;
170 import cx.fbn.nevernote.gui.AttributeTreeWidget;
171 import cx.fbn.nevernote.gui.BrowserWindow;
172 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
173 import cx.fbn.nevernote.gui.ExternalBrowse;
174 import cx.fbn.nevernote.gui.MainMenuBar;
175 import cx.fbn.nevernote.gui.NotebookTreeWidget;
176 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
177 import cx.fbn.nevernote.gui.SearchPanel;
178 import cx.fbn.nevernote.gui.TableView;
179 import cx.fbn.nevernote.gui.TagTreeWidget;
180 import cx.fbn.nevernote.gui.Thumbnailer;
181 import cx.fbn.nevernote.gui.TrashTreeWidget;
182 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
183 import cx.fbn.nevernote.oauth.OAuthTokenizer;
184 import cx.fbn.nevernote.oauth.OAuthWindow;
185 import cx.fbn.nevernote.sql.DatabaseConnection;
186 import cx.fbn.nevernote.sql.WatchFolderRecord;
187 import cx.fbn.nevernote.threads.IndexRunner;
188 import cx.fbn.nevernote.threads.SyncRunner;
189 import cx.fbn.nevernote.threads.ThumbnailRunner;
190 import cx.fbn.nevernote.utilities.AESEncrypter;
191 import cx.fbn.nevernote.utilities.ApplicationLogger;
192 import cx.fbn.nevernote.utilities.FileImporter;
193 import cx.fbn.nevernote.utilities.FileUtils;
194 import cx.fbn.nevernote.utilities.ListManager;
195 import cx.fbn.nevernote.utilities.SyncTimes;
196 import cx.fbn.nevernote.xml.ExportData;
197 import cx.fbn.nevernote.xml.ImportData;
198 import cx.fbn.nevernote.xml.ImportEnex;
199 import cx.fbn.nevernote.xml.NoteFormatter;
200
201
202 public class NeverNote extends QMainWindow{
203         
204         QStatusBar                              statusBar;                                      // Application status bar
205         
206         DatabaseConnection              conn;
207         
208         MainMenuBar                             menuBar;                                        // Main menu bar
209         FindDialog                              find;                                           // Text search in note dialog
210         List<String>                    emitLog;                                        // Messages displayed in the status bar;
211         QSystemTrayIcon                 trayIcon;                                       // little tray icon
212         QMenu                                   trayMenu;                                       // System tray menu
213         QAction                                 trayExitAction;                         // Exit the application
214         QAction                                 trayShowAction;                         // toggle the show/hide action          
215         QAction                                 trayAddNoteAction;                      // Add a note from the system tray
216         QNetworkAccessManager   versionChecker;                         // Used when checking for new versions
217         
218     NotebookTreeWidget          notebookTree;                           // List of notebooks
219     AttributeTreeWidget         attributeTree;                          // List of note attributes
220     TagTreeWidget                       tagTree;                                        // list of user created tags
221     SavedSearchTreeWidget       savedSearchTree;                        // list of saved searches
222     TrashTreeWidget                     trashTree;                                      // Trashcan
223     TableView                           noteTableView;                          //      List of notes (the widget).
224
225     public BrowserWindow        browserWindow;                          // Window containing browser & labels
226     public QToolBar             toolBar;                                        // The tool bar under the menu
227     QComboBox                           searchField;                            // search filter bar on the toolbar;
228     QShortcut                           searchShortcut;                         // Shortcut to search bar
229     boolean                                     searchPerformed = false;        // Search was done?
230     QuotaProgressBar            quotaBar;                                       // The current quota usage
231     
232     ApplicationLogger           logger;
233     List<String>                        selectedNotebookGUIDs;          // List of notebook GUIDs
234     List<String>                        selectedTagGUIDs;                       // List of selected tag GUIDs
235     List<String>                        selectedNoteGUIDs;                      // List of selected notes
236     String                                      selectedSavedSearchGUID;        // Currently selected saved searches
237     private final HashMap<String, ExternalBrowse>       externalWindows;        // Notes being edited by an external window;
238     
239     NoteFilter                          filter;                                         // Note filter
240     String                                      currentNoteGuid;                        // GUID of the current note 
241     Note                                        currentNote;                            // The currently viewed note
242     boolean                                     noteDirty;                                      // Has the note been changed?
243     boolean                             inkNote;                   // if this is an ink note, it is read only
244     boolean                                     readOnly;                                       // Is this note read-only?
245         
246   
247     ListManager                         listManager;                                    // DB runnable task
248     
249     List<QTemporaryFile>        tempFiles;                                      // Array of temporary files;
250     
251     QTimer                                      indexTimer;                                     // timer to start the index thread
252     IndexRunner                         indexRunner;                            // thread to index notes
253     QThread                                     indexThread;
254     
255     QTimer                                      syncTimer;                                      // Sync on an interval
256     QTimer                                      syncDelayTimer;                         // Sync delay to free up database
257     SyncRunner                          syncRunner;                                     // thread to do a sync.
258     QThread                                     syncThread;                                     // Thread which talks to evernote
259     ThumbnailRunner                     thumbnailRunner;                        // Runner for thumbnail thread
260     QThread                                     thumbnailThread;                        // Thread that generates pretty pictures
261     QTimer                                      saveTimer;                                      // Timer to save note contents
262     
263     QTimer                                      authTimer;                                      // Refresh authentication
264     QTimer                                      externalFileSaveTimer;          // Save files altered externally
265     QTimer                                      thumbnailTimer;                         // Wakeup & scan for thumbnails
266     List<String>                        externalFiles;                          // External files to save later
267     List<String>                        importFilesKeep;                        // Auto-import files to save later
268     List<String>                        importFilesDelete;                      // Auto-import files to save later
269     
270     int                                         indexTime;                                      // how often to try and index
271     boolean                                     indexRunning;                           // Is indexing running?
272     boolean                                     indexDisabled;                          // Is indexing disabled?
273     
274     int                                         syncThreadsReady;                       // number of sync threads that are free
275     int                                         syncTime;                                       // Sync interval
276     boolean                                     syncRunning;                            // Is sync running?
277     boolean                                     automaticSync;                          // do sync automatically?
278     QTreeWidgetItem                     attributeTreeSelected;
279
280     QAction                             prevButton;                                     // Go to the previous item viewed
281     QAction                             nextButton;                                     // Go to the next item in the history
282     QAction                             downButton;                                     // Go to the next item in the list
283     QAction                             upButton;                                       // Go to the prev. item in the list;
284     QAction                             synchronizeButton;                      // Synchronize with Evernote
285     QAction                             allNotesButton;                         // Reset & view all notes
286     QTimer                              synchronizeAnimationTimer;      // Timer to change animation button
287     int                                 synchronizeIconAngle;           // Used to rotate sync icon
288     QAction                     printButton;                            // Print Button
289     QAction                             tagButton;                                      // Tag edit button
290     QAction                             attributeButton;                        // Attribute information button
291     QAction                     emailButton;                            // Email button
292     QAction                     deleteButton;                           // Delete button
293     QAction                             newButton;                                      // new Note Button;
294     QSpinBox                    zoomSpinner;                            // Zoom zoom
295     QAction                             searchClearButton;                      // Clear the search field
296     
297     SearchPanel                 searchLayout;                           // Widget to hold search field, zoom, & quota
298     
299     QSplitter                   mainLeftRightSplitter;          // main splitter for left/right side
300     QSplitter                   leftSplitter1;                          // first left hand splitter
301     QSplitter                   browserIndexSplitter;           // splitter between note index & note text
302     
303     QFileSystemWatcher  importKeepWatcher;                      // Watch & keep auto-import
304     QFileSystemWatcher  importDeleteWatcher;            // Watch & Delete auto-import
305     List<String>                importedFiles;                          // History of imported files (so we don't import twice)
306     
307     OnlineNoteHistory   historyWindow;                          // online history window 
308     List<NoteVersionId> versions;                                       // history versions
309     
310     QTimer                              threadMonitorTimer;                     // Timer to watch threads.
311     int                                 dbThreadDeadCount=0;            // number of consecutive dead times for the db thread
312     int                                 syncThreadDeadCount=0;          // number of consecutive dead times for the sync thread
313     int                                 indexThreadDeadCount=0;         // number of consecutive dead times for the index thread
314     int                                 notebookThreadDeadCount=0;      // number of consecutive dead times for the notebook thread
315     int                                 tagDeadCount=0;                         // number of consecutive dead times for the tag thread
316     int                                 trashDeadCount=0;                       // number of consecutive dead times for the trash thread
317     int                                 saveThreadDeadCount=0;          // number of consecutive dead times for the save thread
318     boolean                             disableTagThreadCheck=false;
319     boolean                             disableNotebookThreadCheck=false;
320     boolean                             disableTrashThreadCheck=false;
321     boolean                             disableSaveThreadCheck=false;
322     boolean                             disableSyncThreadCheck=false;
323     boolean                             disableIndexThreadCheck=false;
324     
325     HashMap<String, String>             noteCache;                      // Cash of note content 
326     HashMap<String, Boolean>    readOnlyCache;          // List of cashe notes that are read-only
327     HashMap<String, Boolean>    inkNoteCache;           // List of cache notes that are ink notes 
328     List<String>                historyGuids;                           // GUIDs of previously viewed items
329     int                                 historyPosition;                        // Position within the viewed items
330     boolean                             fromHistory;                            // Is this from the history queue?
331     String                              trashNoteGuid;                          // Guid to restore / set into or out of trash to save position
332     List<Thumbnailer>   thumbGenerators;                                // generate preview image
333     ThumbnailViewer             thumbnailViewer;                        // View preview thumbnail; 
334     boolean                             encryptOnShutdown;                      // should I encrypt when I close?
335     boolean                             decryptOnShutdown;                      // should I decrypt on shutdown;
336     String                              encryptCipher;                          // What cipher should I use?
337     //Signal0                   minimizeToTray;
338     boolean                             windowMaximized = false;        // Keep track of the window state for restores
339     List<String>                pdfReadyQueue;                          // Queue of PDFs that are ready to be rendered.
340     List<QPixmap>               syncIcons;                                      // Array of icons used in sync animation
341     private boolean             closeAction = false;            // Used to say when to close or when to minimize
342     private static Logger log = Logger.getLogger(NeverNote.class); 
343     private String              saveLastPath;                           // last path we used
344     private final QTimer                messageTimer;                           // Timer to clear the status message.
345     private QTimer              blockTimer;
346     BrowserWindow               blockingWindow;
347     
348     String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
349         
350         
351     //***************************************************************
352     //***************************************************************
353     //** Constructor & main entry point
354     //***************************************************************
355     //***************************************************************
356     // Application Constructor  
357         @SuppressWarnings("static-access")
358         public NeverNote(DatabaseConnection dbConn)  {
359                 conn = dbConn;          
360                 if (conn.getConnection() == null) {
361                         String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
362                                 "is accessing the database or NixNote is already running.\n\n" +
363                                 "Please end any other process or shutdown the other NixNote before starting.\n\nExiting program."));
364                         
365             QMessageBox.critical(null, tr("Database Connection Error") ,msg);
366                         System.exit(16);
367                 }
368                 setObjectName("mainWindow");
369 //              thread().setPriority(Thread.MAX_PRIORITY);
370                 
371                 logger = new ApplicationLogger("nevernote.log");
372                 logger.log(logger.HIGH, "Starting Application");
373                 
374                 decryptOnShutdown = false;
375                 encryptOnShutdown = false;
376                 conn.checkDatabaseVersion();
377                 
378                 
379                 
380                 // Start building the invalid XML tables
381                 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
382                 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
383                 
384                 for (int i=0; i<elements.size(); i++) {
385                         Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
386                 }
387                 
388                 logger.log(logger.EXTREME, "Starting GUI build");
389
390                 QTranslator nevernoteTranslator = new QTranslator();
391                 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
392                 QApplication.instance().installTranslator(nevernoteTranslator);
393
394                 Global.originalPalette = QApplication.palette();
395                 QApplication.setStyle(Global.getStyle());
396                 if (Global.useStandardPalette())
397                         QApplication.setPalette(QApplication.style().standardPalette());
398         setWindowTitle(tr("NixNote"));
399
400         mainLeftRightSplitter = new QSplitter();
401         setCentralWidget(mainLeftRightSplitter);
402         leftSplitter1 = new QSplitter();
403         leftSplitter1.setOrientation(Qt.Orientation.Vertical);
404                 
405         browserIndexSplitter = new QSplitter();
406         browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
407         
408         //* Setup threads & thread timers
409 //        int indexRunnerCount = Global.getIndexThreads();
410 //       indexRunnerCount = 1;
411         QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount);     // increase max thread count
412
413                 logger.log(logger.EXTREME, "Building list manager");
414         listManager = new ListManager(conn, logger);
415         
416                 logger.log(logger.EXTREME, "Building index runners & timers");
417         indexRunner = new IndexRunner("indexRunner.log", 
418                         Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
419                         Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
420                 indexThread = new QThread(indexRunner, "Index Thread");
421         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
422         indexRunner.indexImageRecognition = Global.indexImageRecognition();
423         indexRunner.indexNoteBody = Global.indexNoteBody();
424         indexRunner.indexNoteTitle = Global.indexNoteTitle();
425         indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
426                 indexThread.start();
427                 
428         synchronizeAnimationTimer = new QTimer();
429         synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
430         
431                 indexTimer = new QTimer();
432                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
433                 indexTimer.start(indexTime);  // Start indexing timer
434                 indexTimer.timeout.connect(this, "indexTimer()");
435                 indexDisabled = false;
436                 indexRunning = false;
437                                 
438                 logger.log(logger.EXTREME, "Setting sync thread & timers");
439                 syncThreadsReady=1;
440                 syncRunner = new SyncRunner("syncRunner.log", 
441                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
442                                 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
443                 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
444                 syncTimer = new QTimer();
445                 syncTimer.timeout.connect(this, "syncTimer()");
446         syncRunner.status.message.connect(this, "setMessage(String)");
447         syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
448         syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
449         syncRunning = false;    
450                 if (syncTime > 0) {
451                         automaticSync = true;
452                         syncTimer.start(syncTime*60*1000);
453                 } else {
454                         automaticSync = false;
455                         syncTimer.stop();
456                 }
457                 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
458                 syncThread = new QThread(syncRunner, "Synchronization Thread");
459                 syncThread.start();
460                 
461                 
462                 logger.log(logger.EXTREME, "Starting thumnail thread");
463                 pdfReadyQueue = new ArrayList<String>();
464                 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", 
465                                 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
466                                 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
467                 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
468                 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
469                 thumbnailThread.start();
470                 thumbGenerators = new ArrayList<Thumbnailer>();
471                 thumbnailTimer = new QTimer();
472                 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
473                 thumbnailTimer();
474                 thumbnailTimer.setInterval(500*1000);  // Thumbnail every minute
475                 thumbnailTimer.start();
476                 
477                 logger.log(logger.EXTREME, "Starting authentication timer");
478                 authTimer = new QTimer();
479                 authTimer.timeout.connect(this, "authTimer()");
480                 authTimer.start(1000*60*15);
481                 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
482                 
483                 logger.log(logger.EXTREME, "Setting save note timer");
484                 saveTimer = new QTimer();
485                 saveTimer.timeout.connect(this, "saveNote()");
486                 if (Global.getAutoSaveInterval() > 0) {
487                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval()); 
488                         saveTimer.start();
489                 }
490                 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
491                 
492                 logger.log(logger.EXTREME, "Starting external file monitor timer");
493                 externalFileSaveTimer = new QTimer();
494                 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
495                 externalFileSaveTimer.setInterval(1000*5);   // save every 5 seconds;
496                 externalFiles = new ArrayList<String>();
497                 importFilesDelete = new ArrayList<String>();
498                 importFilesKeep = new ArrayList<String>();
499                 externalFileSaveTimer.start();
500                 
501         notebookTree = new NotebookTreeWidget(conn);
502         attributeTree = new AttributeTreeWidget();
503         tagTree = new TagTreeWidget(conn);
504         savedSearchTree = new SavedSearchTreeWidget();
505         trashTree = new TrashTreeWidget();
506         noteTableView = new TableView(logger, listManager);        
507         
508         searchField = new QComboBox();
509         searchField.setObjectName("searchField");
510         //setStyleSheet("QComboBox#searchField { background-color: yellow }");
511         searchField.setEditable(true);
512         searchField.activatedIndex.connect(this, "searchFieldChanged()");
513         searchField.setDuplicatesEnabled(false);
514         searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
515         searchShortcut = new QShortcut(this);
516         setupShortcut(searchShortcut, "Focus_Search");
517         searchShortcut.activated.connect(this, "focusSearch()");
518         
519         quotaBar = new QuotaProgressBar();
520         // Setup the zoom
521         zoomSpinner = new QSpinBox();
522         zoomSpinner.setMinimum(10);
523         zoomSpinner.setMaximum(1000);
524         zoomSpinner.setAccelerated(true);
525         zoomSpinner.setSingleStep(10);
526         zoomSpinner.setValue(100);
527         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
528         
529         searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
530         
531         
532         QGridLayout leftGrid = new QGridLayout();
533         leftSplitter1.setContentsMargins(5, 0, 0, 7);
534         leftSplitter1.setLayout(leftGrid);
535         leftGrid.addWidget(searchLayout,1,1);
536         leftGrid.addWidget(tagTree,2,1);
537         leftGrid.addWidget(attributeTree,3,1);
538         leftGrid.addWidget(savedSearchTree,4,1);
539         leftGrid.addWidget(trashTree,5, 1);
540         
541         // Setup the browser window
542         noteCache = new HashMap<String,String>();
543         readOnlyCache = new HashMap<String, Boolean>();
544         inkNoteCache = new HashMap<String, Boolean>();
545         browserWindow = new BrowserWindow(conn);
546
547         mainLeftRightSplitter.addWidget(leftSplitter1);
548         mainLeftRightSplitter.addWidget(browserIndexSplitter);
549         
550         if (Global.getListView() == Global.View_List_Wide) {
551                 browserIndexSplitter.addWidget(noteTableView);
552                 browserIndexSplitter.addWidget(browserWindow); 
553         } else {
554                 mainLeftRightSplitter.addWidget(noteTableView);
555                 mainLeftRightSplitter.addWidget(browserWindow); 
556         }
557         
558         // Setup the thumbnail viewer
559         thumbnailViewer = new ThumbnailViewer();
560         thumbnailViewer.upArrow.connect(this, "upAction()");
561         thumbnailViewer.downArrow.connect(this, "downAction()");
562         thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
563         thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
564         
565         //Setup external browser manager
566         externalWindows = new HashMap<String, ExternalBrowse>();
567
568         listManager.loadNotesIndex();
569         initializeNotebookTree();
570         initializeTagTree();
571         initializeSavedSearchTree();
572         attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
573         attributeTreeSelected = null;
574         initializeNoteTable();    
575
576                 selectedNoteGUIDs = new ArrayList<String>();
577                 statusBar = new QStatusBar();
578                 setStatusBar(statusBar);
579                 menuBar = new MainMenuBar(this);
580                 emitLog = new ArrayList<String>();
581                 
582                 tagTree.setDeleteAction(menuBar.tagDeleteAction);
583                 tagTree.setMergeAction(menuBar.tagMergeAction);
584                 tagTree.setEditAction(menuBar.tagEditAction);
585                 tagTree.setAddAction(menuBar.tagAddAction);
586                 tagTree.setIconAction(menuBar.tagIconAction);
587                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
588                 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
589                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
590                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
591                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
592                 
593                 if (!Global.isWindowVisible("zoom")) {
594                         searchLayout.hideZoom();
595                         menuBar.hideZoom.setChecked(false);
596                 } 
597         
598                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
599                 notebookTree.setEditAction(menuBar.notebookEditAction);
600                 notebookTree.setAddAction(menuBar.notebookAddAction);
601                 notebookTree.setIconAction(menuBar.notebookIconAction);
602                 notebookTree.setStackAction(menuBar.notebookStackAction);
603                 notebookTree.setPublishAction(menuBar.notebookPublishAction);
604                 notebookTree.setShareAction(menuBar.notebookShareAction);
605                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
606                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
607                 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
608             notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
609                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
610
611                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
612                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
613                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
614                 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
615                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
616                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
617                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
618                         
619                 noteTableView.setAddAction(menuBar.noteAdd);
620                 noteTableView.setDeleteAction(menuBar.noteDelete);
621                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
622                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
623                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
624                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
625                 noteTableView.noteSignal.notePinned.connect(this, "notePinned()");
626                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
627                 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
628                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
629                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
630                 
631                 quotaBar.setMouseClickAction(menuBar.accountAction);
632                 
633                 trashTree.load();
634         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
635                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
636                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
637                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
638                 trashTree.updateCounts(listManager.getTrashCount());
639                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
640                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
641
642                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
643                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
644                 
645                 if (!Global.isWindowVisible("editorButtonBar"))
646                         toggleEditorButtonBar();
647                 if (!Global.isWindowVisible("leftPanel"))
648                         menuBar.hideLeftSide.setChecked(true);
649                 if (Global.isWindowVisible("noteInformation"))
650                         toggleNoteInformation();
651                 quotaBar.setVisible(Global.isWindowVisible("quota"));
652                 if (!quotaBar.isVisible())
653                         menuBar.hideQuota.setChecked(false);
654                 searchField.setVisible(Global.isWindowVisible("searchField"));
655                 if (!searchField.isVisible())
656                         menuBar.hideSearch.setChecked(false);
657                 
658                 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
659                         searchLayout.hide();
660                 
661                 setMenuBar(menuBar);
662                 setupToolBar();
663                 find = new FindDialog();
664                 find.getOkButton().clicked.connect(this, "doFindText()");
665                 
666                 // Setup the tray icon menu bar
667                 trayShowAction = new QAction(tr("Show/Hide"), this);
668                 trayExitAction = new QAction(tr("Exit"), this);
669                 trayAddNoteAction = new QAction(tr("Add Note"), this);
670                 
671                 trayExitAction.triggered.connect(this, "closeNeverNote()");
672                 trayAddNoteAction.triggered.connect(this, "addNote()");
673                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
674                 
675                 trayMenu = new QMenu(this);
676                 trayMenu.addAction(trayAddNoteAction);
677                 trayMenu.addAction(trayShowAction);
678                 trayMenu.addAction(trayExitAction);
679                 
680                 
681                 trayIcon = new QSystemTrayIcon(this);
682                 trayIcon.setToolTip(tr("NixNote"));
683                 trayIcon.setContextMenu(trayMenu);
684                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
685
686                 currentNoteGuid="";
687                 currentNoteGuid = Global.getLastViewedNoteGuid();
688         historyGuids = new ArrayList<String>();
689         historyPosition = 0;
690         fromHistory = false;
691                 noteDirty = false;
692                 if (!currentNoteGuid.trim().equals("")) {
693                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
694                 }
695                 
696                 noteIndexUpdated(true);
697                 showColumns();
698                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
699                 if (menuBar.showEditorBar.isChecked())
700                 showEditorButtons(browserWindow);
701                 tagIndexUpdated(true);
702                 savedSearchIndexUpdated();
703                 notebookIndexUpdated();
704                 updateQuotaBar();
705         setupSyncSignalListeners();        
706         setupBrowserSignalListeners();
707         setupIndexListeners();
708               
709         
710         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
711         tagTree.showAllTags(true);
712
713                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
714                 if (QSystemTrayIcon.isSystemTrayAvailable()) {
715                         setWindowIcon(appIcon);
716                         trayIcon.setIcon(appIcon);
717                         if (Global.showTrayIcon() || Global.minimizeOnClose())
718                                 trayIcon.show();
719                         else
720                                 trayIcon.hide();
721                 }
722         
723         scrollToGuid(currentNoteGuid);
724         if (Global.automaticLogin()) {
725                 remoteConnect();
726                 if (Global.isConnected)
727                         syncTimer();
728         }
729         setupFolderImports();
730         
731         loadStyleSheet();
732         restoreWindowState(true);
733         
734         if (Global.mimicEvernoteInterface) {
735                 notebookTree.selectGuid("");
736         }
737         
738         threadMonitorTimer = new QTimer();
739         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
740         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
741         
742         historyGuids.add(currentNoteGuid);
743         historyPosition = 1;
744         
745         menuBar.blockSignals(true);
746         menuBar.narrowListView.blockSignals(true);
747         menuBar.wideListView.blockSignals(true);
748         if (Global.getListView() == Global.View_List_Narrow) { 
749                 menuBar.narrowListView.setChecked(true);
750         }
751         else{ 
752                 menuBar.wideListView.setChecked(true);
753         }
754         menuBar.blockSignals(false);
755         menuBar.narrowListView.blockSignals(false);
756         menuBar.wideListView.blockSignals(false);
757
758         if (Global.getListView() == Global.View_List_Wide) {
759                 browserIndexSplitter.addWidget(noteTableView);
760                 browserIndexSplitter.addWidget(browserWindow); 
761         } else {
762                 mainLeftRightSplitter.addWidget(noteTableView);
763                 mainLeftRightSplitter.addWidget(browserWindow); 
764         }
765         
766                 messageTimer = new QTimer();
767                 messageTimer.timeout.connect(this, "clearMessage()");
768                 messageTimer.setInterval(1000*15);
769                 clearMessage();
770         
771         int sortCol = Global.getSortColumn();
772                 int sortOrder = Global.getSortOrder();
773                 noteTableView.proxyModel.blocked = true;
774                 // We sort the table twice to fix a bug.  For some reaosn the table won't sort properly if it is in narrow
775                 // list view and sorted descending on the date  created.  By sorting it twice it forces the proper sort.  Ugly.
776                 if (sortCol == 0 && sortOrder == 1 && Global.getListView() == Global.View_List_Narrow) 
777                         noteTableView.sortByColumn(sortCol, SortOrder.resolve(0));   
778                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
779                 noteTableView.proxyModel.blocked = false;
780                 noteTableView.proxyModel.sortChanged.connect(this, "tableSortOrderChanged(Integer,Integer)");
781                 
782                 // Set the startup notebook
783         String defaultNotebook = Global.getStartupNotebook();
784         if (!defaultNotebook.equals("AllNotebooks") && !defaultNotebook.equals("")) {
785                 for (int k=0; k<listManager.getNotebookIndex().size(); k++) {
786                         if (listManager.getNotebookIndex().get(k).isDefaultNotebook()) {
787                                 notebookTree.clearSelection();
788                                 notebookTree.selectGuid(listManager.getNotebookIndex().get(k).getGuid());
789                                 notebookTree.selectionSignal.emit();
790                         }
791                 }
792         }
793                 
794                 if (Global.checkVersionUpgrade())
795                         checkForUpdates();
796         }
797                 
798         // Main entry point
799         public static void main(String[] args) {
800                 log.setLevel(Level.FATAL);
801                 QApplication.initialize(args);
802                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
803                 QSplashScreen splash = new QSplashScreen(pixmap);
804                 boolean showSplash;
805                 
806                 DatabaseConnection dbConn;
807
808         try {
809             initializeGlobalSettings(args);
810
811             showSplash = Global.isWindowVisible("SplashScreen");
812             if (showSplash)
813                 splash.show();
814
815             dbConn = setupDatabaseConnection();
816
817             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
818             Global.getFileManager().purgeResDirectory(true);
819
820         } catch (InitializationException e) {
821             // Fatal
822             e.printStackTrace();
823             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
824             return;
825         }
826
827         NeverNote application = new NeverNote(dbConn);
828                 if (Global.syncOnly) {
829                         System.out.println("Performing synchronization only.");
830                         application.remoteConnect();
831                         if (Global.isConnected) {
832                                 application.syncRunner.syncNeeded = true;
833                                 application.syncRunner.addWork("SYNC");
834                                 application.syncRunner.addWork("STOP");
835                                 while(!application.syncRunner.isIdle());
836                                 application.closeNeverNote();
837                         }
838                         return;
839                 }
840
841                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
842                 if (Global.startMinimized()) 
843                         application.showMinimized();
844                 else {
845                         if (Global.wasWindowMaximized())
846                                 application.showMaximized();
847                         else
848                                 application.show();
849                 }
850                 
851                 if (showSplash)
852                         splash.finish(application);
853                 QApplication.exec();
854                 System.out.println("Goodbye.");
855                 QApplication.exit();
856         }
857
858     /**
859      * Open the internal database, or create if not present
860      *
861      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
862      */
863     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
864         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
865         
866         File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
867         File fr = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
868         File fi = Global.getFileManager().getDbDirFile(Global.resourceDatabaseName + ".h2.db");
869                 if (!f.exists())
870                         Global.setDatabaseUrl("");
871                 if (!fr.exists())
872                         Global.setResourceDatabaseUrl("");              
873                 if (!fi.exists())
874                         Global.setIndexDatabaseUrl(""); 
875         
876         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
877             boolean goodCheck = false;
878             while (!goodCheck) {
879                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
880                 dialog.exec();
881                 if (!dialog.okPressed())
882                     System.exit(0);
883                 Global.cipherPassword = dialog.getPassword();
884                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
885                         Global.getDatabaseUserPassword(), Global.cipherPassword);
886             }
887         }
888         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), 
889                         Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
890                         Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
891        return dbConn;
892     }
893     
894     // Encrypt the database upon shutdown
895     private void encryptOnShutdown() {
896         String dbPath= Global.getFileManager().getDbDirPath("");
897         try {
898                 
899                 Statement st = conn.getConnection().createStatement();  
900                 st.execute("shutdown");
901                 st = conn.getResourceConnection().createStatement();
902                 st.execute("shutdown");
903                 st = conn.getIndexConnection().createStatement();
904                 st.execute("shutdown");
905                 if (QMessageBox.question(this, tr("Are you sure"), 
906                                 tr("Are you sure you wish to encrypt the database?"),
907                                 QMessageBox.StandardButton.Yes, 
908                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
909                         ChangeFileEncryption.execute(dbPath, "NeverNote", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
910                         ChangeFileEncryption.execute(dbPath, "Resources", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
911                         ChangeFileEncryption.execute(dbPath, "Index", encryptCipher, null, Global.cipherPassword.toCharArray(), true);
912                         Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
913                         Global.setResourceDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
914                         Global.setIndexDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
915
916                         QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
917                 }
918         } catch (SQLException e) {
919                         e.printStackTrace();
920                 }       
921     }
922     
923     // Decrypt the database upon shutdown
924     private void decryptOnShutdown() {
925         String dbPath= Global.getFileManager().getDbDirPath("");
926         String dbName = "NeverNote";
927         try {
928                 Statement st = conn.getConnection().createStatement();  
929                 st.execute("shutdown");
930                 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
931                         encryptCipher = "AES";
932                 else
933                         encryptCipher = "XTEA";
934                 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure", 
935                                 "Are you sure you wish to decrypt the database?"),
936                                 QMessageBox.StandardButton.Yes, 
937                                 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
938
939                         ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
940                         Global.setDatabaseUrl("");
941                         Global.setResourceDatabaseUrl("");
942                         Global.setIndexDatabaseUrl("");
943                         QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
944                 }
945                 } catch (SQLException e) {
946                         e.printStackTrace();
947                 }       
948     }
949     /**
950      * Encrypt/Decrypt the local database
951      **/
952     public void doDatabaseEncrypt() {
953         // The database is not currently encrypted
954         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
955                 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
956                                 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
957                                 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
958                                 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
959                                 "Do you wish to proceed?"),
960                                 QMessageBox.StandardButton.Yes, 
961                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
962                                 return;
963                 }
964                 DBEncryptDialog dialog = new DBEncryptDialog();
965                 dialog.exec();
966                 if (dialog.okPressed()) {
967                         Global.cipherPassword = dialog.getPassword();
968                         encryptOnShutdown  = true;
969                         encryptCipher = dialog.getEncryptionMethod();
970                 }
971         } else {
972             DBEncryptDialog dialog = new DBEncryptDialog();
973             dialog.setWindowTitle(tr("Database Decryption"));
974             dialog.hideEncryption();
975             dialog.exec();
976             if (dialog.okPressed()) {
977                 if (!dialog.getPassword().equals(Global.cipherPassword)) {
978                         QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
979                         return;
980                 }
981                 decryptOnShutdown  = true;
982                 encryptCipher = "";
983             }
984         }
985         return;
986     }
987
988         private static void initializeGlobalSettings(String[] args) throws InitializationException {
989                 StartupConfig   startupConfig = new StartupConfig();
990
991         for (String arg : args) {
992             String lower = arg.toLowerCase();
993             if (lower.startsWith("--name="))
994                startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
995             if (lower.startsWith("--home="))
996                startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
997             if (lower.startsWith("--disable-viewing"))
998                startupConfig.setDisableViewing(true);
999             if (lower.startsWith("--sync-only=true"))
1000                 startupConfig.setSyncOnly(true);
1001         }
1002         Global.setup(startupConfig);
1003         
1004     }
1005
1006     // Exit point
1007         @Override
1008         public void closeEvent(QCloseEvent event) {     
1009                 if (Global.minimizeOnClose() && !closeAction) {
1010                         event.ignore();
1011                         hide();
1012                         return;
1013                 }
1014                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
1015                 waitCursor(true);
1016                 
1017                 if (currentNote!= null & browserWindow!=null) {
1018                         if (currentNote.getTitle() != null && browserWindow != null 
1019                                         && !currentNote.getTitle().equals(browserWindow.getTitle()))
1020                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
1021                 }
1022                 saveNote();
1023                 setMessage(tr("Beginning shutdown."));
1024                 
1025                 // Close down external windows
1026                 Collection<ExternalBrowse> windows = externalWindows.values();
1027                 Iterator<ExternalBrowse> iterator = windows.iterator();
1028                 while (iterator.hasNext()) {
1029                         ExternalBrowse browser = iterator.next();
1030                         browser.windowClosing.disconnect();
1031                         browser.close();
1032                 }
1033                 
1034                 
1035                 externalFileEditedSaver();
1036                 if (Global.isConnected && Global.synchronizeOnClose()) {
1037                         setMessage(tr("Performing synchronization before closing."));
1038                         syncRunner.syncNeeded = true;
1039                         syncRunner.addWork("SYNC");
1040                 } else {
1041                         syncRunner.keepRunning = false;
1042                 }
1043                 syncRunner.addWork("STOP");
1044                 setMessage("Closing Program.");
1045                 threadMonitorTimer.stop();
1046
1047                 thumbnailRunner.addWork("STOP");
1048                 indexRunner.addWork("STOP");
1049                 saveNote();
1050                 listManager.stop();
1051                 saveWindowState();
1052
1053                 if (tempFiles != null)
1054                         tempFiles.clear();
1055
1056                 browserWindow.noteSignal.tagsChanged.disconnect();
1057                 browserWindow.noteSignal.titleChanged.disconnect();
1058                 browserWindow.noteSignal.noteChanged.disconnect();
1059                 browserWindow.noteSignal.notebookChanged.disconnect();
1060                 browserWindow.noteSignal.createdDateChanged.disconnect();
1061                 browserWindow.noteSignal.alteredDateChanged.disconnect();
1062                 syncRunner.searchSignal.listChanged.disconnect();
1063                 syncRunner.tagSignal.listChanged.disconnect();
1064         syncRunner.notebookSignal.listChanged.disconnect();
1065         syncRunner.noteIndexSignal.listChanged.disconnect();
1066
1067                 if (isVisible())
1068                         Global.saveWindowVisible("toolBar", toolBar.isVisible());
1069                 saveNoteColumnPositions();
1070                 saveNoteIndexWidth();
1071                 
1072                 int width = notebookTree.columnWidth(0);
1073                 Global.setColumnWidth("notebookTreeName", width);
1074                 width = tagTree.columnWidth(0);
1075                 Global.setColumnWidth("tagTreeName", width);
1076                 
1077                 Global.saveWindowMaximized(isMaximized());
1078                 Global.saveCurrentNoteGuid(currentNoteGuid);
1079                         
1080                 int sortCol = noteTableView.proxyModel.sortColumn();
1081                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1082                 Global.setSortColumn(sortCol);
1083                 Global.setSortOrder(sortOrder);
1084                 
1085                 hide();
1086                 trayIcon.hide();
1087                 Global.keepRunning = false;
1088                 try {
1089                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1090                         if (indexRunner.thread().isAlive())
1091                                 indexRunner.thread().join(50);
1092                         if (!indexRunner.thread().isAlive())
1093                                 logger.log(logger.MEDIUM, "Index thread has stopped");
1094                         else {
1095                                 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1096                                 indexRunner.thread().interrupt();
1097                         }
1098                 } catch (InterruptedException e1) {
1099                         e1.printStackTrace();
1100                 }
1101                 
1102                 if (!syncRunner.thread().isAlive()) {
1103                         logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1104                         if (syncRunner.thread().isAlive()) {
1105                                 System.out.println(tr("Synchronizing.  Please be patient."));
1106                                 for(;syncRunner.thread().isAlive();) {
1107                                         try {
1108                                                 wait(10);
1109                                         } catch (InterruptedException e) {
1110                                                 e.printStackTrace();
1111                                         }
1112                                 }
1113                         }
1114                         logger.log(logger.MEDIUM, "Sync thread has stopped");
1115                 }
1116
1117                 if (encryptOnShutdown) {
1118                         encryptOnShutdown();
1119                 }
1120                 if (decryptOnShutdown) {
1121                         decryptOnShutdown();
1122                 }
1123                 try {
1124                         Global.getFileManager().purgeResDirectory(false);
1125                 } catch (InitializationException e) {
1126                         System.out.println(tr("Empty res directory purge failed"));
1127                         e.printStackTrace();
1128                 }
1129                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1130         }
1131
1132
1133         private void closeNeverNote() {
1134                 closeAction = true;
1135                 close();
1136         }
1137         public void setMessage(String s) {
1138                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1139                 
1140                 if (statusBar != null) {
1141                         statusBar.show();
1142                         logger.log(logger.HIGH, "Message: " +s);
1143                         statusBar.showMessage(s);
1144                         emitLog.add(s);
1145                 
1146                         messageTimer.stop();
1147                         messageTimer.setSingleShot(true);
1148                         messageTimer.start();
1149                 }
1150                         
1151                 
1152                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1153         }
1154         
1155         private void clearMessage() {
1156                 statusBar.clearMessage();
1157                 statusBar.hide();
1158         }
1159                 
1160         private void waitCursor(boolean wait) {
1161                 if (wait) {
1162                         if (QApplication.overrideCursor() == null)
1163                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1164                 }
1165                 else {
1166                         while (QApplication.overrideCursor() != null)
1167                                 QApplication.restoreOverrideCursor();
1168                 }
1169                 listManager.refreshCounters();
1170         }
1171         
1172         private void setupIndexListeners() {
1173 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1174 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1175                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1176                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1177         }
1178         private void setupSyncSignalListeners() {
1179                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1180         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1181         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1182         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1183         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1184         
1185                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1186                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1187                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1188                 
1189                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1190                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1191                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1192                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1193                 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1194                 
1195                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1196         }
1197         
1198         private void setupBrowserSignalListeners() {
1199                 setupBrowserWindowListeners(browserWindow, true);
1200         }
1201
1202         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1203                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1204                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1205             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1206             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1207             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1208             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1209             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1210             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1211             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1212             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1213             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1214             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1215             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1216             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1217         browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1218         browser.unblockApplication.connect(this, "unblockApplication()");
1219             if (master) browser.focusLost.connect(this, "saveNote()");
1220             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1221             browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1222         }
1223
1224         //**************************************************
1225         //* Setup shortcuts
1226         //**************************************************
1227         private void setupShortcut(QShortcut action, String text) {
1228                 if (!Global.shortcutKeys.containsAction(text))
1229                         return;
1230                 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1231         }
1232         
1233         //***************************************************************
1234         //***************************************************************
1235         //* Settings and look & feel
1236         //***************************************************************
1237         //***************************************************************
1238         @SuppressWarnings("unused")
1239         private void settings() {
1240                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1241                 saveNoteColumnPositions();
1242                 saveNoteIndexWidth();
1243                 showColumns();
1244         ConfigDialog settings = new ConfigDialog(this);
1245         String dateFormat = Global.getDateFormat();
1246         String timeFormat = Global.getTimeFormat();
1247         
1248                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1249                 indexTimer.start(indexTime);  // reset indexing timer
1250         
1251         settings.exec();
1252         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1253         indexRunner.indexNoteBody = Global.indexNoteBody();
1254         indexRunner.indexNoteTitle = Global.indexNoteTitle();
1255         indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1256         indexRunner.indexImageRecognition = Global.indexImageRecognition();
1257         if (Global.showTrayIcon() || Global.minimizeOnClose())
1258                 trayIcon.show();
1259         else
1260                 trayIcon.hide();
1261         showColumns();
1262         if (menuBar.showEditorBar.isChecked())
1263                 showEditorButtons(browserWindow);
1264         
1265         // Reset the save timer
1266         if (Global.getAutoSaveInterval() > 0)
1267                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1268         else
1269                 saveTimer.stop();
1270         
1271         
1272         // Set special reloads
1273         if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1274                 conn.executeSql("Delete from LinkedNotebook");
1275                 conn.executeSql("delete from SharedNotebook");
1276                 conn.executeSql("Delete from Notebook where linked=true");
1277                 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1278                 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1279         }
1280
1281         // Reload user data
1282         noteCache.clear();
1283         readOnlyCache.clear();
1284         inkNoteCache.clear();
1285         noteIndexUpdated(true);
1286                 
1287         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1288         }
1289         // Restore things to the way they were
1290         private void restoreWindowState(boolean mainWindow) {
1291                 // We need to name things or this doesn't work.
1292                 setObjectName("NeverNote");
1293         restoreState(Global.restoreState(objectName()));
1294                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1295                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1296                 leftSplitter1.setObjectName("leftSplitter1");   
1297                 
1298                 // Restore the actual positions.
1299                 if (mainWindow)
1300                         restoreGeometry(Global.restoreGeometry(objectName()));
1301         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1302         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1303         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1304        
1305         }
1306         // Save window positions for the next start
1307         private void saveWindowState() {
1308                 Global.saveGeometry(objectName(), saveGeometry());
1309                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1310                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1311                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1312                 Global.saveState(objectName(), saveState());
1313         }    
1314         // Load the style sheet
1315         private void loadStyleSheet() {
1316                 String styleSheetName = "default.qss";
1317                 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1318                                 styleSheetName = "default-cleanlooks.qss";
1319                 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1320                 QFile file = new QFile(fileName);
1321                 
1322                 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1323                 if (!file.exists()) {
1324                         fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1325                         file = new QFile(fileName);
1326                 }
1327                 file.open(OpenModeFlag.ReadOnly);
1328                 String styleSheet = file.readAll().toString();
1329                 file.close();
1330                 setStyleSheet(styleSheet);
1331         }
1332         // Save column positions for the next time
1333         private void saveNoteColumnPositions() {
1334                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1335                 Global.setColumnPosition("noteTableCreationPosition", position);
1336                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1337                 Global.setColumnPosition("noteTableTagPosition", position);
1338                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1339                 Global.setColumnPosition("noteTableNotebookPosition", position);
1340                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1341                 Global.setColumnPosition("noteTableChangedPosition", position);
1342                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1343                 Global.setColumnPosition("noteTableAuthorPosition", position);
1344                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1345                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1346                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1347                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1348                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1349                 Global.setColumnPosition("noteTableTitlePosition", position);
1350                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1351                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1352                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1353                 Global.setColumnPosition("noteTableGuidPosition", position);
1354                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1355                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1356                 position = noteTableView.header.visualIndex(Global.noteTablePinnedPosition);
1357                 Global.setColumnPosition("noteTablePinnedPosition", position);
1358
1359         }
1360         // Save column widths for the next time
1361         private void saveNoteIndexWidth() {
1362                 int width;
1363         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1364         Global.setColumnWidth("noteTableCreationPosition", width);
1365                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1366                 Global.setColumnWidth("noteTableChangedPosition", width);
1367                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1368                 Global.setColumnWidth("noteTableGuidPosition", width);
1369                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1370                 Global.setColumnWidth("noteTableNotebookPosition", width);
1371                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1372                 Global.setColumnWidth("noteTableTagPosition", width);
1373                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1374                 Global.setColumnWidth("noteTableTitlePosition", width);
1375                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1376                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1377                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1378                 Global.setColumnWidth("noteTableAuthorPosition", width);
1379                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1380                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1381                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1382                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1383                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1384                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1385                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1386                 Global.setColumnWidth("noteTableGuidPosition", width);
1387                 width = noteTableView.getColumnWidth(Global.noteTablePinnedPosition);
1388                 Global.setColumnWidth("noteTablePinnedPosition", width);
1389         }
1390         
1391         @SuppressWarnings("unused")
1392         private void toggleSearchWindow() {
1393                 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1394         searchLayout.toggleSearchField();
1395         menuBar.hideSearch.setChecked(searchField.isVisible());
1396         Global.saveWindowVisible("searchField", searchField.isVisible());
1397         logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1398     }   
1399         @SuppressWarnings("unused")
1400         private void toggleQuotaWindow() {
1401                 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1402         searchLayout.toggleQuotaBar();
1403         menuBar.hideQuota.setChecked(quotaBar.isVisible());
1404         Global.saveWindowVisible("quota", quotaBar.isVisible());
1405         logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1406     }   
1407         @SuppressWarnings("unused")
1408         private void toggleZoomWindow() {
1409                 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1410         searchLayout.toggleZoom();
1411         menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1412         Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1413         logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1414     }   
1415         
1416         
1417         
1418     //***************************************************************
1419     //***************************************************************
1420     //** These functions deal with Notebook menu items
1421     //***************************************************************
1422     //***************************************************************
1423     // Setup the tree containing the user's notebooks.
1424     private void initializeNotebookTree() {       
1425         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1426 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1427         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1428         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1429         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1430     }   
1431     // Listener when a notebook is selected
1432         private void notebookTreeSelection() {
1433                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1434                 noteTableView.proxyModel.blocked = true;
1435                 
1436                 clearTrashFilter();
1437                 clearAttributeFilter();
1438                 clearSavedSearchFilter();
1439                 if (Global.mimicEvernoteInterface) {
1440                         clearTagFilter();
1441                         searchField.clear();
1442                 }
1443                 menuBar.noteRestoreAction.setVisible(false);            
1444         menuBar.notebookEditAction.setEnabled(true);
1445         menuBar.notebookDeleteAction.setEnabled(true);
1446         menuBar.notebookPublishAction.setEnabled(true);
1447         menuBar.notebookShareAction.setEnabled(true);
1448         menuBar.notebookIconAction.setEnabled(true);
1449         menuBar.notebookStackAction.setEnabled(true);
1450         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1451         selectedNotebookGUIDs.clear();
1452                 String guid = "";
1453                 String stackName = "";
1454                 if (selections.size() > 0) {
1455                 guid = (selections.get(0).text(2));
1456                 stackName = selections.get(0).text(0);
1457         }
1458                 if (!Global.mimicEvernoteInterface) {
1459                         // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1460                         if (selections.size()==0) {
1461                                 selectedNotebookGUIDs.clear();
1462                                 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1463                                         selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1464                                 }
1465                                 menuBar.notebookEditAction.setEnabled(false);
1466                                 menuBar.notebookDeleteAction.setEnabled(false);
1467                                 menuBar.notebookStackAction.setEnabled(false);
1468                                 menuBar.notebookIconAction.setEnabled(false);
1469                         }
1470                 }
1471         if (!guid.equals("") && !guid.equals("STACK")) {
1472                 selectedNotebookGUIDs.add(guid);
1473                 menuBar.notebookIconAction.setEnabled(true);
1474         } else {
1475                 menuBar.notebookIconAction.setEnabled(true);
1476                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1477                                 Notebook book = listManager.getNotebookIndex().get(j);
1478                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1479                                         selectedNotebookGUIDs.add(book.getGuid());
1480                         }
1481         }
1482         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1483         listManager.loadNotesIndex();
1484         noteIndexUpdated(false);
1485         refreshEvernoteNote(true);
1486         listManager.refreshCounters = true;
1487         listManager.refreshCounters();
1488         if (selectedNotebookGUIDs.size() == 1) {
1489                 int col = conn.getNotebookTable().getSortColumn(selectedNotebookGUIDs.get(0));
1490                 int order = conn.getNotebookTable().getSortOrder(selectedNotebookGUIDs.get(0));
1491                 if (col != -1) {
1492                         noteTableView.proxyModel.blocked = true;
1493                         if (order == 1)
1494                                 noteTableView.sortByColumn(col, Qt.SortOrder.DescendingOrder);
1495                         else
1496                                 noteTableView.sortByColumn(col, Qt.SortOrder.AscendingOrder);
1497                 }
1498         }
1499         noteTableView.proxyModel.blocked = false;
1500                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1501
1502     }
1503     private void clearNotebookFilter() {
1504         notebookTree.blockSignals(true);
1505         notebookTree.clearSelection();
1506                 menuBar.noteRestoreAction.setVisible(false);
1507         menuBar.notebookEditAction.setEnabled(false);
1508         menuBar.notebookDeleteAction.setEnabled(false);
1509         selectedNotebookGUIDs.clear();
1510         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1511         notebookTree.blockSignals(false);
1512     }
1513         // Triggered when the notebook DB has been updated
1514         private void notebookIndexUpdated() {
1515                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1516         
1517                 // Get the possible icons
1518                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1519         notebookTree.setIcons(icons);
1520         
1521         if (selectedNotebookGUIDs == null)
1522                         selectedNotebookGUIDs = new ArrayList<String>();
1523                 List<Notebook> books = conn.getNotebookTable().getAll();
1524                 for (int i=books.size()-1; i>=0; i--) {
1525                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1526                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1527                                         books.remove(i);
1528                                         j=listManager.getArchiveNotebookIndex().size();
1529                                 }
1530                         }
1531                 }
1532                 
1533                 
1534                 listManager.countNotebookResults(listManager.getNoteIndex());
1535                 notebookTree.blockSignals(true);
1536         notebookTree.load(books, listManager.getLocalNotebooks());
1537         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1538                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1539                 if (!found)
1540                         selectedNotebookGUIDs.remove(i);
1541         }
1542         listManager.refreshCounters = true;
1543         listManager.refreshCounters();
1544         notebookTree.blockSignals(false);
1545         
1546                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1547     }
1548     // Show/Hide note information
1549         @SuppressWarnings("unused")
1550         private void toggleNotebookWindow() {
1551                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1552                 searchLayout.toggleNotebook();
1553         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1554         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1555         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1556     }   
1557         // Add a new notebook
1558         @SuppressWarnings("unused")
1559         private void addNotebook() {
1560                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1561                 NotebookEdit edit = new NotebookEdit();
1562                 edit.setNotebooks(listManager.getNotebookIndex());
1563                 edit.exec();
1564         
1565                 if (!edit.okPressed())
1566                         return;
1567         
1568                 Calendar currentTime = new GregorianCalendar();
1569                 Long l = new Long(currentTime.getTimeInMillis());
1570                 String randint = new String(Long.toString(l));
1571         
1572                 Notebook newBook = new Notebook();
1573                 newBook.setUpdateSequenceNum(0);
1574                 newBook.setGuid(randint);
1575                 newBook.setName(edit.getNotebook());
1576                 newBook.setServiceCreated(new Date().getTime());
1577                 newBook.setServiceUpdated(new Date().getTime());
1578                 newBook.setDefaultNotebook(false);
1579                 newBook.setPublished(false);
1580                 
1581                 listManager.getNotebookIndex().add(newBook);
1582                 if (edit.isLocal())
1583                         listManager.getLocalNotebooks().add(newBook.getGuid());
1584                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1585                 notebookIndexUpdated();
1586                 listManager.countNotebookResults(listManager.getNoteIndex());
1587 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1588                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1589         }
1590         // Edit an existing notebook
1591         @SuppressWarnings("unused")
1592         private void stackNotebook() {
1593                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1594                 StackNotebook edit = new StackNotebook();
1595                 
1596                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1597                 QTreeWidgetItem currentSelection;
1598                 for (int i=0; i<selections.size(); i++) {
1599                         currentSelection = selections.get(0);
1600                         String guid = currentSelection.text(2);
1601                         if (guid.equalsIgnoreCase("")) {
1602                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1603                                  return;
1604                         }
1605                         if (guid.equalsIgnoreCase("STACK")) {
1606                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1607                                  return;
1608                         }
1609                 }
1610
1611                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1612
1613                 
1614                 edit.exec();
1615         
1616                 if (!edit.okPressed())
1617                         return;
1618         
1619                 String stack = edit.getStackName();
1620                 
1621                 for (int i=0; i<selections.size(); i++) {
1622                         currentSelection = selections.get(i);
1623                         String guid = currentSelection.text(2);
1624                         listManager.updateNotebookStack(guid, stack);
1625                 }
1626                 notebookIndexUpdated();
1627                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1628         }
1629         // Edit an existing notebook
1630         @SuppressWarnings("unused")
1631         private void editNotebook() {
1632                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1633                 NotebookEdit edit = new NotebookEdit();
1634                 
1635                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1636                 QTreeWidgetItem currentSelection;
1637                 currentSelection = selections.get(0);
1638                 edit.setNotebook(currentSelection.text(0));
1639                 
1640                 String guid = currentSelection.text(2);
1641                 if (!guid.equalsIgnoreCase("STACK")) {
1642                         edit.setTitle(tr("Edit Notebook"));
1643                         edit.setNotebooks(listManager.getNotebookIndex());
1644                         edit.setLocalCheckboxEnabled(false);
1645                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1646                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1647                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1648                                         i=listManager.getNotebookIndex().size();
1649                                 }
1650                         }
1651                 } else {
1652                         edit.setTitle(tr("Edit Stack"));
1653                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1654                         edit.hideLocalCheckbox();
1655                         edit.hideDefaultCheckbox();
1656                 }
1657                 
1658                 edit.exec();
1659         
1660                 if (!edit.okPressed())
1661                         return;
1662         
1663                 
1664                 if (guid.equalsIgnoreCase("STACK")) {
1665                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1666                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1667                                 if (listManager.getNotebookIndex().get(j).getStack() != null && 
1668                                         listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1669                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1670                         }
1671                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1672                         currentSelection.setText(0, edit.getNotebook());
1673                         return;
1674                 }
1675                 
1676                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1677                 currentSelection.setText(0, edit.getNotebook());
1678                 
1679                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1680                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1681                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1682                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1683                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1684                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1685                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1686                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1687                                 }
1688                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1689                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1690                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1691                                         linkedNotebook.setShareName(edit.getNotebook());
1692                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1693                                 }
1694                                 i=listManager.getNotebookIndex().size();
1695                         }
1696                 }
1697                 
1698                 // Build a list of non-closed notebooks
1699                 List<Notebook> nbooks = new ArrayList<Notebook>();
1700                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1701                         boolean found=false;
1702                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1703                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1704                                         found = true;
1705                         }
1706                         if (!found)
1707                                 nbooks.add(listManager.getNotebookIndex().get(i));
1708                 }
1709                 
1710                 
1711                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1712                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1713                 browserWindow.setNotebookList(filteredBooks);
1714                 Iterator<String> set = externalWindows.keySet().iterator();
1715                 while(set.hasNext())
1716                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1717                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1718         }
1719         // Publish a notebook
1720         @SuppressWarnings("unused")
1721         private void publishNotebook() {
1722                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1723                 QTreeWidgetItem currentSelection;
1724                 currentSelection = selections.get(0);
1725                 String guid = currentSelection.text(2);
1726
1727                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1728                         return;
1729                 
1730                 Notebook n = null;
1731                 int position = 0;
1732                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1733                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1734                                 n = listManager.getNotebookIndex().get(i);
1735                                 position = i;
1736                                 i = listManager.getNotebookIndex().size();
1737                         }
1738                 }
1739                 if (n == null)
1740                         return;
1741                 
1742                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1743                 publish.exec();
1744                 
1745                 if (!publish.okClicked()) 
1746                         return;
1747                 
1748                 Publishing p = publish.getPublishing();
1749                 boolean isPublished = !publish.isStopPressed();
1750                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1751                 n.setPublished(isPublished);
1752                 n.setPublishing(p);
1753                 listManager.getNotebookIndex().set(position, n);
1754                 notebookIndexUpdated();
1755         }
1756         // Publish a notebook
1757         @SuppressWarnings("unused")
1758         private void shareNotebook() {
1759                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1760                 QTreeWidgetItem currentSelection;
1761                 currentSelection = selections.get(0);
1762                 String guid = currentSelection.text(2);
1763
1764                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1765                         return;
1766                 
1767                 Notebook n = null;;
1768                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1769                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1770                                 n = listManager.getNotebookIndex().get(i);
1771                                 i = listManager.getNotebookIndex().size();
1772                         }
1773                 }
1774                                 
1775                 String authToken = null;
1776                 if (syncRunner.isConnected)
1777                         authToken = syncRunner.authToken;
1778                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1779                 share.exec();
1780                 
1781         }
1782
1783         // Delete an existing notebook
1784         @SuppressWarnings("unused")
1785         private void deleteNotebook() {
1786                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1787                 boolean stacksFound = false;
1788                 boolean notebooksFound = false;
1789                 boolean assigned = false;
1790                 // Check if any notes have this notebook
1791                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1792         for (int i=0; i<selections.size(); i++) {
1793                 QTreeWidgetItem currentSelection;
1794                 currentSelection = selections.get(i);
1795                 String guid = currentSelection.text(2);
1796                 if (!guid.equalsIgnoreCase("STACK")) {
1797                         notebooksFound = true;
1798                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1799                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1800                                 if (noteGuid.equals(guid)) {
1801                                         assigned = true;
1802                                         j=listManager.getNoteIndex().size();
1803                                         i=selections.size();
1804                                 }
1805                         }
1806                 } else {
1807                         stacksFound = true;
1808                 }
1809         }
1810                 if (assigned) {
1811                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1812                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1813                         return;
1814                 }
1815                 
1816                 if (conn.getNotebookTable().getAll().size() == 1) {
1817                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1818                         return;
1819                 }
1820         
1821         // If all notebooks are clear, verify the delete
1822                 String msg1 = new String(tr("Delete selected notebooks?"));
1823                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1824                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1825                                 " not deleted unless selected?"));
1826                 String msg = "";
1827                 if (stacksFound && notebooksFound)
1828                         msg = msg3;
1829                 if (!stacksFound && notebooksFound)
1830                         msg = msg1;
1831                 if (stacksFound && !notebooksFound)
1832                         msg = msg2;
1833                 if (QMessageBox.question(this, tr("Confirmation"), msg,
1834                         QMessageBox.StandardButton.Yes, 
1835                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1836                         return;
1837                 }
1838                 
1839                 // If confirmed, delete the notebook
1840         for (int i=selections.size()-1; i>=0; i--) {
1841                 QTreeWidgetItem currentSelection;
1842                 currentSelection = selections.get(i);
1843                 String guid = currentSelection.text(2);
1844                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1845                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1846                         listManager.renameStack(currentSelection.text(0), "");
1847                 } else {
1848                         conn.getNotebookTable().expungeNotebook(guid, true);
1849                         listManager.deleteNotebook(guid);
1850                 }
1851         }
1852
1853                 notebookIndexUpdated();
1854 //        notebookTreeSelection();
1855 //        notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1856 //        listManager.countNotebookResults(listManager.getNoteIndex());
1857         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1858         }
1859         // A note's notebook has been updated
1860         @SuppressWarnings("unused")
1861         private void updateNoteNotebook(String guid, String notebookGuid) {
1862                 
1863                 // Update the list manager
1864                 listManager.updateNoteNotebook(guid, notebookGuid);
1865                 listManager.countNotebookResults(listManager.getNoteIndex());
1866 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1867                 
1868                 // Find the name of the notebook
1869                 String notebookName = null;
1870                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1871                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1872                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1873                                 break;
1874                         }
1875                 }
1876                 
1877                 // If we found the name, update the browser window
1878                 if (notebookName != null) {
1879                         updateListNoteNotebook(guid, notebookName);
1880                         if (guid.equals(currentNoteGuid)) {
1881                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1882                                 if (pos >=0)
1883                                         browserWindow.notebookBox.setCurrentIndex(pos);
1884                         }
1885                 }
1886                 
1887                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1888                 if (guid.equals(currentNoteGuid)) {
1889                         if (currentNote != null) {
1890                                 currentNote.setNotebookGuid(notebookGuid);
1891                         }
1892                 }
1893         }
1894         // Open/close notebooks
1895         @SuppressWarnings("unused")
1896         private void closeNotebooks() {
1897                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1898                 na.exec();
1899                 if (!na.okClicked())
1900                         return;
1901                 
1902                 waitCursor(true);
1903                 listManager.getArchiveNotebookIndex().clear();
1904                 
1905                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1906                         String text = na.getClosedBookList().takeItem(i).text();
1907                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1908                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1909                                         Notebook n = listManager.getNotebookIndex().get(j);
1910                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1911                                         listManager.getArchiveNotebookIndex().add(n);
1912                                         j=listManager.getNotebookIndex().size();
1913                                 }
1914                         }
1915                 }
1916                 
1917                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1918                         String text = na.getOpenBookList().takeItem(i).text();
1919                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1920                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1921                                         Notebook n = listManager.getNotebookIndex().get(j);
1922                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1923                                         j=listManager.getNotebookIndex().size();
1924                                 }
1925                         }
1926                 }
1927                 notebookTreeSelection();
1928                 listManager.loadNotesIndex();
1929                 notebookIndexUpdated();
1930                 noteIndexUpdated(false);
1931                 reloadTagTree(true);
1932 //              noteIndexUpdated(false);
1933                 
1934                 // Build a list of non-closed notebooks
1935                 List<Notebook> nbooks = new ArrayList<Notebook>();
1936                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1937                         boolean found=false;
1938                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1939                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1940                                         found = true;
1941                         }
1942                         if (!found)
1943                                 nbooks.add(listManager.getNotebookIndex().get(i));
1944                 }
1945                 
1946                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1947                 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1948                 browserWindow.setNotebookList(filteredBooks);
1949                 
1950                 // Update any external windows
1951                 Iterator<String> set = externalWindows.keySet().iterator();
1952                 while(set.hasNext())
1953                         externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1954                 
1955                 waitCursor(false);
1956         }
1957         // Change the notebook's icon
1958         @SuppressWarnings("unused")
1959         private void setNotebookIcon() {
1960                 boolean stackSelected = false;
1961                 boolean allNotebookSelected = false;
1962                 
1963                 QTreeWidgetItem currentSelection;
1964                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1965                 if (selections.size() == 0)
1966                         return;
1967                 
1968                 currentSelection = selections.get(0);   
1969                 String guid = currentSelection.text(2);
1970                 if (guid.equalsIgnoreCase(""))
1971                         allNotebookSelected = true;
1972                 if (guid.equalsIgnoreCase("STACK"))
1973                         stackSelected = true;
1974
1975                 QIcon currentIcon = currentSelection.icon(0);
1976                 QIcon icon;
1977                 SetIcon dialog;
1978                 
1979                 if (!stackSelected && !allNotebookSelected) {
1980                         icon = conn.getNotebookTable().getIcon(guid);
1981                         if (icon == null) {
1982                                 dialog = new SetIcon(currentIcon, saveLastPath);
1983                                 dialog.setUseDefaultIcon(true);
1984                         } else {
1985                                 dialog = new SetIcon(icon, saveLastPath);
1986                                 dialog.setUseDefaultIcon(false);
1987                         }
1988                 } else {
1989                         if (stackSelected) {
1990                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1991                         } else {
1992                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
1993                         }
1994                         if (icon == null) {
1995                                 dialog = new SetIcon(currentIcon, saveLastPath);
1996                                 dialog.setUseDefaultIcon(true);
1997                         } else {
1998                                 dialog = new SetIcon(icon, saveLastPath);
1999                                 dialog.setUseDefaultIcon(false);
2000                         }
2001                 }
2002                 dialog.exec();
2003                 if (dialog.okPressed()) {
2004                 saveLastPath = dialog.getPath();
2005
2006                         QIcon newIcon = dialog.getIcon();
2007                         if (stackSelected) {
2008                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
2009                                 if (newIcon == null) {
2010                                         newIcon = new QIcon(iconPath+"books2.png");
2011                                 }
2012                                 currentSelection.setIcon(0,newIcon);
2013                                 return;
2014                         }
2015                         if (allNotebookSelected) {
2016                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
2017                                 if (newIcon == null) {
2018                                         newIcon = new QIcon(iconPath+"notebook-green.png");
2019                                 }
2020                                 currentSelection.setIcon(0,newIcon);
2021                                 return;
2022                         }
2023                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
2024                         if (newIcon == null) {
2025                                 boolean isPublished = false;;
2026                                 boolean found = false;
2027                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
2028                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
2029                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
2030                                                 found = true;
2031                                         }
2032                                 }
2033                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
2034                         }
2035                         currentSelection.setIcon(0, newIcon);
2036                 }
2037         
2038         }
2039         
2040         
2041     //***************************************************************
2042     //***************************************************************
2043     //** These functions deal with Tag menu items
2044     //***************************************************************
2045     //***************************************************************
2046         // Add a new notebook
2047         @SuppressWarnings("unused")
2048         private void addTag() {
2049                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
2050                 TagEdit edit = new TagEdit();
2051                 edit.setTagList(listManager.getTagIndex());
2052
2053                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2054                 QTreeWidgetItem currentSelection = null;
2055                 if (selections.size() > 0) {
2056                         currentSelection = selections.get(0);
2057                         edit.setParentTag(currentSelection.text(0));
2058                 }
2059
2060                 edit.exec();
2061         
2062                 if (!edit.okPressed())
2063                         return;
2064         
2065                 Calendar currentTime = new GregorianCalendar();
2066                 Long l = new Long(currentTime.getTimeInMillis());
2067                 String randint = new String(Long.toString(l));
2068         
2069                 Tag newTag = new Tag();
2070                 newTag.setUpdateSequenceNum(0);
2071                 newTag.setGuid(randint);
2072                 newTag.setName(edit.getTag());
2073                 if (edit.getParentTag().isChecked()) {
2074                         newTag.setParentGuid(currentSelection.text(2));
2075                         newTag.setParentGuidIsSet(true);
2076                         currentSelection.setExpanded(true);
2077                 }
2078                 conn.getTagTable().addTag(newTag, true);
2079                 listManager.getTagIndex().add(newTag);
2080                 reloadTagTree(true);
2081                 
2082                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2083         }
2084         @SuppressWarnings("unused")
2085         private void reloadTagTree() {
2086                 reloadTagTree(false);
2087         }
2088         private void reloadTagTree(boolean reload) {
2089                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2090                 tagIndexUpdated(reload);
2091                 boolean filter = false;
2092                 if (reload)
2093                         listManager.countTagResults(listManager.getNoteIndex());
2094                 if (notebookTree.selectedItems().size() > 0 
2095                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2096                                                   filter = true;
2097                 if (tagTree.selectedItems().size() > 0)
2098                         filter = true;
2099                 tagTree.showAllTags(!filter);
2100                 tagIndexUpdated(false);
2101                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2102         }
2103         // Edit an existing tag
2104         @SuppressWarnings("unused")
2105         private void editTag() {
2106                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2107                 TagEdit edit = new TagEdit();
2108                 edit.setTitle("Edit Tag");
2109                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2110                 QTreeWidgetItem currentSelection;
2111                 currentSelection = selections.get(0);
2112                 edit.setTag(currentSelection.text(0));
2113                 edit.setTagList(listManager.getTagIndex());
2114                 edit.exec();
2115         
2116                 if (!edit.okPressed())
2117                         return;
2118         
2119                 String guid = currentSelection.text(2);
2120                 currentSelection.setText(0,edit.getTag());
2121                 
2122                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2123                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2124                                 listManager.getTagIndex().get(i).setName(edit.getTag());
2125                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2126                                 updateListTagName(guid);
2127                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2128                                         browserWindow.setTag(getTagNamesForNote(currentNote));
2129                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2130                                 //return;
2131                         }
2132                 }
2133                 listManager.reloadNoteTagNames(guid, edit.getTag());
2134                 noteIndexUpdated(true);
2135                 refreshEvernoteNote(true);
2136                 browserWindow.setTag(getTagNamesForNote(currentNote));
2137                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2138         }
2139         // Delete an existing tag
2140         @SuppressWarnings("unused")
2141         private void deleteTag() {
2142                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2143                 
2144                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2145                         QMessageBox.StandardButton.Yes, 
2146                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2147                                                         return;
2148                 }
2149                 
2150                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2151         for (int i=selections.size()-1; i>=0; i--) {
2152                 QTreeWidgetItem currentSelection;
2153                 currentSelection = selections.get(i);                   
2154                 removeTagItem(currentSelection.text(2));
2155         }
2156         tagIndexUpdated(true);
2157         tagTreeSelection();
2158         listManager.countTagResults(listManager.getNoteIndex());
2159 //              tagTree.updateCounts(listManager.getTagCounter());
2160         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2161         }
2162         // Remove a tag tree item.  Go recursively down & remove the children too
2163         private void removeTagItem(String guid) {
2164         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
2165                 String parent = listManager.getTagIndex().get(j).getParentGuid();
2166                 if (parent != null && parent.equals(guid)) {            
2167                         //Remove this tag's children
2168                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
2169                 }
2170         }
2171         //Now, remove this tag
2172         removeListTagName(guid);
2173         conn.getTagTable().expungeTag(guid, true);                      
2174         for (int a=0; a<listManager.getTagIndex().size(); a++) {
2175                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2176                         listManager.getTagIndex().remove(a);
2177                         return;
2178                 }
2179         }
2180         }
2181         // Setup the tree containing the user's tags
2182     private void initializeTagTree() {
2183         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2184 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2185 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
2186         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2187         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2188         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2189     }
2190     // Listener when a tag is selected
2191         private void tagTreeSelection() {
2192         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2193                 
2194         clearTrashFilter();
2195         clearAttributeFilter();
2196         clearSavedSearchFilter();
2197         
2198                 menuBar.noteRestoreAction.setVisible(false);
2199                 
2200         List<QTreeWidgetItem> selections = tagTree.selectedItems();
2201         QTreeWidgetItem currentSelection;
2202         selectedTagGUIDs.clear();
2203         for (int i=0; i<selections.size(); i++) {
2204                 currentSelection = selections.get(i);
2205                 selectedTagGUIDs.add(currentSelection.text(2));
2206         }
2207         if (selections.size() > 0) {
2208                 menuBar.tagEditAction.setEnabled(true);
2209                 menuBar.tagDeleteAction.setEnabled(true);
2210                 menuBar.tagIconAction.setEnabled(true);
2211         }
2212         else {
2213                 menuBar.tagEditAction.setEnabled(false);
2214                 menuBar.tagDeleteAction.setEnabled(false);
2215                 menuBar.tagIconAction.setEnabled(true);
2216         }
2217         if (selections.size() > 1)
2218                 menuBar.tagMergeAction.setEnabled(true);
2219         else
2220                 menuBar.tagMergeAction.setEnabled(false);
2221         listManager.setSelectedTags(selectedTagGUIDs);
2222         listManager.loadNotesIndex();
2223         noteIndexUpdated(false);
2224         refreshEvernoteNote(true);
2225         listManager.refreshCounters = true;
2226         listManager.refreshCounters();
2227         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2228     }
2229     // trigger the tag index to be refreshed
2230     @SuppressWarnings("unused")
2231         private void tagIndexUpdated() {
2232         tagIndexUpdated(true);
2233     }
2234     private void tagIndexUpdated(boolean reload) {
2235         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2236                 if (selectedTagGUIDs == null)
2237                         selectedTagGUIDs = new ArrayList<String>();
2238                 if (reload)
2239                         listManager.reloadTagIndex();
2240
2241                 tagTree.blockSignals(true);
2242                 if (reload) {
2243                         tagTree.setIcons(conn.getTagTable().getAllIcons());
2244                         tagTree.load(listManager.getTagIndex());
2245                 }
2246
2247         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2248                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2249                 if (!found)
2250                         selectedTagGUIDs.remove(i);
2251         }
2252         tagTree.blockSignals(false);
2253         
2254                 browserWindow.setTag(getTagNamesForNote(currentNote));
2255         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2256     }   
2257     // Show/Hide note information
2258         @SuppressWarnings("unused")
2259         private void toggleTagWindow() {
2260                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2261         if (tagTree.isVisible())
2262                 tagTree.hide();
2263         else
2264                 tagTree.show();
2265         menuBar.hideTags.setChecked(tagTree.isVisible());
2266         Global.saveWindowVisible("tagTree", tagTree.isVisible());
2267         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2268     }   
2269         // A note's tags have been updated
2270         @SuppressWarnings("unused")
2271         private void updateNoteTags(String guid, List<String> tags) {
2272                 // Save any new tags.  We'll need them later.
2273                 List<String> newTags = new ArrayList<String>();
2274                 for (int i=0; i<tags.size(); i++) {
2275                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
2276                                 newTags.add(tags.get(i));
2277                 }
2278                 
2279                 listManager.saveNoteTags(guid, tags);
2280                 listManager.countTagResults(listManager.getNoteIndex());
2281                 StringBuffer names = new StringBuffer("");
2282                 for (int i=0; i<tags.size(); i++) {
2283                         names = names.append(tags.get(i));
2284                         if (i<tags.size()-1) {
2285                                 names.append(Global.tagDelimeter + " ");
2286                         }
2287                 }
2288                 browserWindow.setTag(names.toString());
2289                 noteDirty = true;
2290                 
2291                 // Now, we need to add any new tags to the tag tree
2292                 for (int i=0; i<newTags.size(); i++) 
2293                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2294         }
2295         // Get a string containing all tag names for a note
2296         private String getTagNamesForNote(Note n) {
2297                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2298                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2299                         return "";
2300                 StringBuffer buffer = new StringBuffer(100);
2301                 Vector<String> v = new Vector<String>();
2302                 List<String> guids = n.getTagGuids();
2303                 
2304                 if (guids == null) 
2305                         return "";
2306                 
2307                 for (int i=0; i<guids.size(); i++) {
2308                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2309                 }
2310                 Comparator<String> comparator = Collections.reverseOrder();
2311                 Collections.sort(v,comparator);
2312                 Collections.reverse(v);
2313                 
2314                 for (int i = 0; i<v.size(); i++) {
2315                         if (i>0) 
2316                                 buffer.append(", ");
2317                         buffer.append(v.get(i));
2318                 }
2319                 
2320                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2321                 return buffer.toString();
2322         }       
2323         // Tags were added via dropping notes from the note list
2324         @SuppressWarnings("unused")
2325         private void tagsAdded(String noteGuid, String tagGuid) {
2326                 String tagName = null;
2327                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2328                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2329                                 tagName = listManager.getTagIndex().get(i).getName();
2330                                 i=listManager.getTagIndex().size();
2331                         }
2332                 }
2333                 if (tagName == null)
2334                         return;
2335                 
2336                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2337                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2338                                 List<String> tagNames = new ArrayList<String>();
2339                                 tagNames.add(new String(tagName));
2340                                 Note n = listManager.getMasterNoteIndex().get(i);
2341                                 for (int j=0; j<n.getTagNames().size(); j++) {
2342                                         tagNames.add(new String(n.getTagNames().get(j)));
2343                                 }
2344                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2345                                 if (n.getGuid().equals(currentNoteGuid)) {
2346                                         Collections.sort(tagNames);
2347                                         String display = "";
2348                                         for (int j=0; j<tagNames.size(); j++) {
2349                                                 display = display+tagNames.get(j);
2350                                                 if (j+2<tagNames.size()) 
2351                                                         display = display+Global.tagDelimeter+" ";
2352                                         }
2353                                         browserWindow.setTag(display);
2354                                 }
2355                                 i=listManager.getMasterNoteIndex().size();
2356                         }
2357                 }
2358                 
2359                 
2360                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2361         }
2362         private void clearTagFilter() {
2363                 tagTree.blockSignals(true);
2364                 tagTree.clearSelection();
2365                 menuBar.noteRestoreAction.setVisible(false);
2366                 menuBar.tagEditAction.setEnabled(false);
2367                 menuBar.tagMergeAction.setEnabled(false);
2368                 menuBar.tagDeleteAction.setEnabled(false);
2369                 menuBar.tagIconAction.setEnabled(false);
2370                 selectedTagGUIDs.clear();
2371         listManager.setSelectedTags(selectedTagGUIDs);
2372         tagTree.blockSignals(false);
2373         }
2374         // Change the icon for a tag
2375         @SuppressWarnings("unused")
2376         private void setTagIcon() {
2377                 QTreeWidgetItem currentSelection;
2378                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2379                 if (selections.size() == 0)
2380                         return;
2381                 
2382                 currentSelection = selections.get(0);   
2383                 String guid = currentSelection.text(2);
2384
2385                 QIcon currentIcon = currentSelection.icon(0);
2386                 QIcon icon = conn.getTagTable().getIcon(guid);
2387                 SetIcon dialog;
2388                 if (icon == null) {
2389                         dialog = new SetIcon(currentIcon, saveLastPath);
2390                         dialog.setUseDefaultIcon(true);
2391                 } else {
2392                         dialog = new SetIcon(icon, saveLastPath);
2393                         dialog.setUseDefaultIcon(false);
2394                 }
2395                 dialog.exec();
2396                 if (dialog.okPressed()) {
2397                 saveLastPath = dialog.getPath();
2398                         QIcon newIcon = dialog.getIcon();
2399                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2400                         if (newIcon == null) 
2401                                 newIcon = new QIcon(iconPath+"tag.png");
2402                         currentSelection.setIcon(0, newIcon);
2403                 }
2404         
2405         }
2406         // Merge tags
2407         @SuppressWarnings("unused")
2408         private void mergeTags() {
2409                 List<Tag> tags = new ArrayList<Tag>();
2410                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2411                 for (int i=0; i<selections.size(); i++) {
2412                         Tag record = new Tag();
2413                         record.setGuid(selections.get(i).text(2));
2414                         record.setName(selections.get(i).text(0));
2415                         tags.add(record);
2416                 }
2417
2418                 TagMerge mergeDialog = new TagMerge(tags);
2419                 mergeDialog.exec();
2420                 if (!mergeDialog.okClicked())
2421                         return;
2422                 String newGuid = mergeDialog.getNewTagGuid();
2423                 
2424                 for (int i=0; i<tags.size(); i++) {
2425                         if (!tags.get(i).getGuid().equals(newGuid)) {
2426                                 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2427                                 for (int j=0; j<noteGuids.size(); j++) {
2428                                         String noteGuid = noteGuids.get(j);
2429                                         conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2430                                         if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2431                                                 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2432                                 }
2433                         }
2434                 }
2435                 listManager.reloadIndexes();
2436         }
2437         
2438     //***************************************************************
2439     //***************************************************************
2440     //** These functions deal with Saved Search menu items
2441     //***************************************************************
2442     //***************************************************************
2443         // Add a new notebook
2444         @SuppressWarnings("unused")
2445         private void addSavedSearch() {
2446                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2447                 SavedSearchEdit edit = new SavedSearchEdit();
2448                 edit.setSearchList(listManager.getSavedSearchIndex());
2449                 edit.exec();
2450         
2451                 if (!edit.okPressed())
2452                         return;
2453         
2454                 Calendar currentTime = new GregorianCalendar();         
2455                 Long l = new Long(currentTime.getTimeInMillis());
2456                 String randint = new String(Long.toString(l));
2457         
2458                 SavedSearch search = new SavedSearch();
2459                 search.setUpdateSequenceNum(0);
2460                 search.setGuid(randint);
2461                 search.setName(edit.getName());
2462                 search.setQuery(edit.getQuery());
2463                 search.setFormat(QueryFormat.USER);
2464                 listManager.getSavedSearchIndex().add(search);
2465                 conn.getSavedSearchTable().addSavedSearch(search, true);
2466                 savedSearchIndexUpdated();
2467                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2468         }
2469         // Edit an existing tag
2470         @SuppressWarnings("unused")
2471         private void editSavedSearch() {
2472                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2473                 SavedSearchEdit edit = new SavedSearchEdit();
2474                 edit.setTitle(tr("Edit Search"));
2475                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2476                 QTreeWidgetItem currentSelection;
2477                 currentSelection = selections.get(0);
2478                 String guid = currentSelection.text(1);
2479                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2480                 edit.setName(currentSelection.text(0));
2481                 edit.setQuery(s.getQuery());
2482                 edit.setSearchList(listManager.getSavedSearchIndex());
2483                 edit.exec();
2484         
2485                 if (!edit.okPressed())
2486                         return;
2487         
2488                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2489                 SavedSearch search = null;
2490                 boolean found = false;
2491                 for (int i=0; i<list.size(); i++) {
2492                         search = list.get(i);
2493                         if (search.getGuid().equals(guid)) {
2494                                 i=list.size();
2495                                 found = true;
2496                         }
2497                 }
2498                 if (!found)
2499                         return;
2500                 search.setName(edit.getName());
2501                 search.setQuery(edit.getQuery());
2502                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2503                 savedSearchIndexUpdated();
2504                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2505         }
2506         // Delete an existing tag
2507         @SuppressWarnings("unused")
2508         private void deleteSavedSearch() {
2509                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2510                 
2511                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2512                         QMessageBox.StandardButton.Yes, 
2513                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2514                                                         return;
2515                 }
2516                 
2517                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2518         for (int i=selections.size()-1; i>=0; i--) {
2519                 QTreeWidgetItem currentSelection;
2520                 currentSelection = selections.get(i);
2521                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2522                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2523                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2524                                 listManager.getSavedSearchIndex().remove(j);
2525                                 j=listManager.getSavedSearchIndex().size()+1;
2526                         }
2527                 }
2528                 selections.remove(i);
2529         }
2530         savedSearchIndexUpdated();
2531         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2532         }
2533     // Setup the tree containing the user's tags
2534     private void initializeSavedSearchTree() {
2535         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2536         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2537         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2538     }
2539     // Listener when a tag is selected
2540     @SuppressWarnings("unused")
2541         private void savedSearchTreeSelection() {
2542         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2543
2544         clearNotebookFilter();
2545         clearTagFilter();
2546         clearTrashFilter();
2547         clearAttributeFilter();
2548         
2549         String currentGuid = selectedSavedSearchGUID;
2550         menuBar.savedSearchEditAction.setEnabled(true);
2551         menuBar.savedSearchDeleteAction.setEnabled(true);
2552         menuBar.savedSearchIconAction.setEnabled(true);
2553         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2554         QTreeWidgetItem currentSelection;
2555         selectedSavedSearchGUID = "";
2556         for (int i=0; i<selections.size(); i++) {
2557                 currentSelection = selections.get(i);
2558                 if (currentSelection.text(1).equals(currentGuid)) {
2559                         currentSelection.setSelected(false);
2560                 } else {
2561                         selectedSavedSearchGUID = currentSelection.text(1);
2562                 }
2563 //              i = selections.size() +1;
2564         }
2565         
2566         // There is the potential for no notebooks to be selected if this 
2567         // happens then we make it look like all notebooks were selecetd.
2568         // If that happens, just select the "all notebooks"
2569         if (selections.size()==0) {
2570                 clearSavedSearchFilter();
2571         }
2572         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2573         
2574         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2575     }
2576     private void clearSavedSearchFilter() {
2577         menuBar.savedSearchEditAction.setEnabled(false);
2578         menuBar.savedSearchDeleteAction.setEnabled(false);
2579         menuBar.savedSearchIconAction.setEnabled(false);
2580         savedSearchTree.blockSignals(true);
2581         savedSearchTree.clearSelection();
2582         savedSearchTree.blockSignals(false);
2583         selectedSavedSearchGUID = "";
2584         searchField.setEditText("");
2585         searchPerformed = false;
2586         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2587     }
2588     // trigger the tag index to be refreshed
2589         private void savedSearchIndexUpdated() { 
2590                 if (selectedSavedSearchGUID == null)
2591                         selectedSavedSearchGUID = new String();
2592                 savedSearchTree.blockSignals(true);
2593                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2594         savedSearchTree.load(listManager.getSavedSearchIndex());
2595         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2596         savedSearchTree.blockSignals(false);
2597     }
2598     // trigger when the saved search selection changes
2599     @SuppressWarnings("unused")
2600         private void updateSavedSearchSelection() {
2601                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2602                 
2603         menuBar.savedSearchEditAction.setEnabled(true);
2604         menuBar.savedSearchDeleteAction.setEnabled(true);
2605         menuBar.savedSearchIconAction.setEnabled(true);
2606         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2607
2608         if (selections.size() > 0) {
2609                 menuBar.savedSearchEditAction.setEnabled(true);
2610                 menuBar.savedSearchDeleteAction.setEnabled(true);
2611                 menuBar.savedSearchIconAction.setEnabled(true);
2612                 selectedSavedSearchGUID = selections.get(0).text(1);
2613                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2614                 searchField.setEditText(s.getQuery());
2615         } else { 
2616                 menuBar.savedSearchEditAction.setEnabled(false);
2617                 menuBar.savedSearchDeleteAction.setEnabled(false);
2618                 menuBar.savedSearchIconAction.setEnabled(false);
2619                 selectedSavedSearchGUID = "";
2620                 searchField.setEditText("");
2621         }
2622         searchFieldChanged();
2623         
2624                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2625
2626         
2627     }
2628     // Show/Hide note information
2629         @SuppressWarnings("unused")
2630         private void toggleSavedSearchWindow() {
2631                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2632         if (savedSearchTree.isVisible())
2633                 savedSearchTree.hide();
2634         else
2635                 savedSearchTree.show();
2636         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2637                                 
2638                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2639         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2640     }
2641         // Change the icon for a saved search
2642         @SuppressWarnings("unused")
2643         private void setSavedSearchIcon() {
2644                 QTreeWidgetItem currentSelection;
2645                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2646                 if (selections.size() == 0)
2647                         return;
2648                 
2649                 currentSelection = selections.get(0);   
2650                 String guid = currentSelection.text(1);
2651
2652                 QIcon currentIcon = currentSelection.icon(0);
2653                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2654                 SetIcon dialog;
2655                 if (icon == null) {
2656                         dialog = new SetIcon(currentIcon, saveLastPath);
2657                         dialog.setUseDefaultIcon(true);
2658                 } else {
2659                         dialog = new SetIcon(icon, saveLastPath);
2660                         dialog.setUseDefaultIcon(false);
2661                 }
2662                 dialog.exec();
2663                 if (dialog.okPressed()) {
2664                 saveLastPath = dialog.getPath();
2665                         QIcon newIcon = dialog.getIcon();
2666                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2667                         if (newIcon == null) 
2668                                 newIcon = new QIcon(iconPath+"search.png");
2669                         currentSelection.setIcon(0, newIcon);
2670                 }
2671         
2672         }
2673         
2674         
2675         
2676         
2677     //***************************************************************
2678     //***************************************************************
2679     //** These functions deal with Help menu & tool menu items
2680     //***************************************************************
2681     //***************************************************************
2682         // Show database status
2683         @SuppressWarnings("unused")
2684         private void databaseStatus() {
2685                 waitCursor(true);
2686                 indexRunner.interrupt = true;
2687                 int dirty = conn.getNoteTable().getDirtyCount();
2688                 int unindexed = conn.getNoteTable().getUnindexedCount();
2689                 DatabaseStatus status = new DatabaseStatus();
2690                 status.setUnsynchronized(dirty);
2691                 status.setUnindexed(unindexed);
2692                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2693                 status.setNotebookCount(listManager.getNotebookIndex().size());
2694                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2695                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2696                 status.setTagCount(listManager.getTagIndex().size());
2697                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2698                 status.setWordCount(conn.getWordsTable().getWordCount());
2699                 waitCursor(false);
2700                 status.exec();
2701         }
2702         // Compact the database
2703         @SuppressWarnings("unused")
2704         private void compactDatabase() {
2705         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2706                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2707                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2708                                 "and NixNote will be unresponsive until it is complete.  Do you wish to continue?"),
2709                                 QMessageBox.StandardButton.Yes, 
2710                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2711                                                         return;
2712                 }
2713                 setMessage("Compacting database.");
2714                 waitCursor(true);
2715                 listManager.compactDatabase();
2716                 waitCursor(false);
2717                 setMessage("Database compact is complete.");            
2718         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2719     }
2720         @SuppressWarnings("unused")
2721         private void accountInformation() {
2722                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2723                 AccountDialog dialog = new AccountDialog();
2724                 dialog.show();
2725                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2726         }
2727         @SuppressWarnings("unused")
2728         private void releaseNotes() {
2729                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2730                 QDialog dialog = new QDialog(this);
2731                 QHBoxLayout layout = new QHBoxLayout();
2732                 QTextEdit textBox = new QTextEdit();
2733                 layout.addWidget(textBox);
2734                 textBox.setReadOnly(true);
2735                 QFile file = new QFile(Global.getFileManager().getProgramDirPath("release.txt"));
2736                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2737                 QIODevice.OpenModeFlag.Text)))
2738                         return;
2739                 textBox.setText(file.readAll().toString());
2740                 file.close();
2741                 dialog.setWindowTitle(tr("Release Notes"));
2742                 dialog.setLayout(layout);
2743                 dialog.show();
2744                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2745         }
2746         // Called when user picks Log from the help menu
2747         @SuppressWarnings("unused")
2748         private void logger() {
2749                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2750                 LogFileDialog dialog = new LogFileDialog(emitLog);
2751                 dialog.exec();
2752                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2753         }
2754         // Menu option "help/about" was selected
2755         @SuppressWarnings("unused")
2756         private void about() {
2757                 logger.log(logger.HIGH, "Entering NeverNote.about");
2758                 QMessageBox.about(this, 
2759                                                 tr("About NixNote"),
2760                                                 tr("<h4><center><b>NixNote</b></center></h4><hr><center>Version ")
2761                                                 +Global.version
2762                                                 //+"1.2.120724"
2763                                                 +tr("<hr>"
2764                                                                 +"Open Source Evernote Client.<br><br>" 
2765                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2766                                                                 +"</center>Evernote is copyright 2001-2012 by Evernote Corporation<br>"
2767                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2768                                                                 +"PDFRenderer is licened under the LGPL<br>"
2769                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2770                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2771                                                                 +"Jazzy is licened under the LGPL<br>"
2772                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2773                                                                 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2774                                                                 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2775                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2776         }
2777         // Hide the entire left hand side
2778         @SuppressWarnings("unused")
2779         private void toggleLeftSide() {
2780                 boolean hidden;
2781                 
2782                 hidden = !menuBar.hideLeftSide.isChecked();
2783                 menuBar.hideLeftSide.setChecked(!hidden);
2784                 
2785                 if (!hidden) 
2786                         leftSplitter1.setHidden(true);
2787                 else
2788                         leftSplitter1.setHidden(false);
2789                 
2790                 Global.saveWindowVisible("leftPanel", hidden);
2791                 
2792         }
2793         public void checkForUpdates() {
2794                 // Send off thread to check for a new version
2795                 versionChecker = new QNetworkAccessManager(this);
2796                 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2797                 QNetworkRequest request = new QNetworkRequest();
2798                 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2799                 versionChecker.get(request);
2800         }
2801         @SuppressWarnings("unused")
2802         private void upgradeFileRead(QNetworkReply reply) {
2803                 if (!reply.isReadable())
2804                         return;
2805                 
2806                 String winVersion = Global.version;
2807                 String osxVersion = Global.version;
2808                 String linuxVersion = Global.version;
2809                 String linux64Version = Global.version;
2810                 String version = Global.version;
2811                 
2812                 // Determine the versions available
2813                 QByteArray data = reply.readLine();
2814                 while (data != null && !reply.atEnd()) {
2815                         String line = data.toString();
2816                         String lineVersion;
2817                         if (line.contains(":")) 
2818                                 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2819                         else
2820                                 lineVersion = "";
2821                         if (line.toLowerCase().contains("windows")) 
2822                                 winVersion = lineVersion;
2823                         else if (line.toLowerCase().contains("os-x")) 
2824                                 osxVersion = lineVersion;
2825                         else if (line.toLowerCase().contains("linux amd64")) 
2826                                 linux64Version = lineVersion;
2827                         else if (line.toLowerCase().contains("linux i386")) 
2828                                 linuxVersion = lineVersion;
2829                         else if (line.toLowerCase().contains("default")) 
2830                                 version = lineVersion;
2831                         
2832                         // Read the next line
2833                         data = reply.readLine();
2834                 }
2835                 
2836                 // Now we need to determine what system we are on.
2837                 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2838                         version = winVersion;
2839                 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2840                         version = osxVersion;
2841                 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2842                         if (System.getProperty("os.arch").contains("amd64") ||
2843                                 System.getProperty("os.arch").contains("x86_64"))
2844                                         version = linux64Version;
2845                         else
2846                                 version = linuxVersion;
2847                 }
2848                 
2849                 
2850                 for (String validVersion : Global.validVersions) {
2851                         if (version.equals(validVersion))
2852                                 return;
2853                 }
2854                 
2855                 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2856                 dialog.exec();
2857                 if (dialog.remindMe())
2858                         Global.setCheckVersionUpgrade(true);
2859                 else
2860                         Global.setCheckVersionUpgrade(false);
2861         }
2862                 
2863         
2864     //***************************************************************
2865     //***************************************************************
2866     //** These functions deal with the Toolbar
2867     //***************************************************************
2868     //*************************************************************** 
2869         @SuppressWarnings("unused")
2870         private void focusSearch() {
2871                 searchField.setFocus();
2872         }
2873
2874         // Text in the search bar has been cleared
2875         private void searchFieldCleared() {
2876                 saveNote();
2877                 
2878                 // This is done because we want to force a reload of
2879                 // images.  Some images we may want to highlight the text.
2880                 readOnlyCache.clear();
2881                 inkNoteCache.clear();
2882                 noteCache.clear();
2883                 QWebSettings.setMaximumPagesInCache(0);
2884                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2885         
2886                 searchField.setEditText("");
2887                 saveNoteColumnPositions();
2888                 saveNoteIndexWidth();
2889                 noteIndexUpdated(true);
2890                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2891                         currentNote = listManager.getNoteIndex().get(0);
2892                         currentNoteGuid = currentNote.getGuid();
2893                 }
2894                 refreshEvernoteNote(true);
2895                 if (currentNote != null)
2896                         loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2897         }
2898         // text in the search bar changed.  We only use this to tell if it was cleared, 
2899         // otherwise we trigger off searchFieldChanged.
2900         @SuppressWarnings("unused")
2901         private void searchFieldTextChanged(String text) {
2902                 QWebSettings.setMaximumPagesInCache(0);
2903                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2904
2905                 if (text.trim().equals("")) {
2906                         searchFieldCleared();
2907                         if (searchPerformed) {
2908
2909                                 // This is done because we want to force a reload of
2910                                 // images.  Some images we may want to highlight the text.
2911                                 noteCache.clear();
2912                                 readOnlyCache.clear();
2913                                 inkNoteCache.clear();
2914                                 
2915                                 listManager.setEnSearch("");
2916                                 listManager.loadNotesIndex();
2917                                 refreshEvernoteNote(true);
2918                                 noteIndexUpdated(false);
2919                                 refreshEvernoteNote(true);
2920                         }
2921                         searchPerformed = false;
2922                 }
2923         }
2924     // Text in the toolbar has changed
2925     private void searchFieldChanged() {
2926         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2927         noteCache.clear();
2928         readOnlyCache.clear();
2929         inkNoteCache.clear();
2930         saveNoteColumnPositions();
2931         saveNoteIndexWidth();
2932         String text = searchField.currentText();
2933         listManager.setEnSearch(text.trim());
2934         listManager.loadNotesIndex();
2935         noteIndexUpdated(false);
2936
2937         refreshEvernoteNote(true);
2938         searchPerformed = true;
2939         waitCursor(false);
2940         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2941     }
2942
2943     // Build the window tool bar
2944     private void setupToolBar() {
2945         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2946         toolBar = addToolBar(tr("Tool Bar"));   
2947         toolBar.setObjectName("toolBar");
2948         menuBar.setupToolBarVisible();
2949         if (!Global.isWindowVisible("toolBar"))
2950                 toolBar.setVisible(false);
2951         else
2952                 toolBar.setVisible(true);
2953
2954 //      toolBar.addWidget(menuBar);
2955 //      menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2956 //      toolBar.addSeparator();
2957         prevButton = toolBar.addAction(tr("Previous"));
2958         QIcon prevIcon = new QIcon(iconPath+"back.png");
2959         prevButton.setIcon(prevIcon);
2960         prevButton.triggered.connect(this, "previousViewedAction()");   
2961         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2962         
2963         nextButton = toolBar.addAction(tr("Next"));
2964         QIcon nextIcon = new QIcon(iconPath+"forward.png");
2965         nextButton.setIcon(nextIcon);
2966         nextButton.triggered.connect(this, "nextViewedAction()");       
2967         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2968         
2969         upButton = toolBar.addAction(tr("Up"));
2970         QIcon upIcon = new QIcon(iconPath+"up.png");
2971         upButton.setIcon(upIcon);
2972         upButton.triggered.connect(this, "upAction()");         
2973         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2974
2975         
2976         downButton = toolBar.addAction(tr("Down"));
2977         QIcon downIcon = new QIcon(iconPath+"down.png");
2978         downButton.setIcon(downIcon);
2979         downButton.triggered.connect(this, "downAction()");
2980         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2981         
2982         synchronizeButton = toolBar.addAction(tr("Synchronize"));
2983         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2984         synchronizeIconAngle = 0;
2985         synchronizeButton.triggered.connect(this, "evernoteSync()");
2986         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2987         
2988         printButton = toolBar.addAction(tr("Print"));
2989         QIcon printIcon = new QIcon(iconPath+"print.png");
2990         printButton.setIcon(printIcon);
2991         printButton.triggered.connect(this, "printNote()");
2992         togglePrintButton(Global.isToolbarButtonVisible("print"));
2993
2994         tagButton = toolBar.addAction(tr("Tag")); 
2995         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2996         tagButton.setIcon(tagIcon);
2997         tagButton.triggered.connect(browserWindow, "modifyTags()");
2998         toggleTagButton(Global.isToolbarButtonVisible("tag"));
2999
3000         attributeButton = toolBar.addAction(tr("Attributes")); 
3001         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
3002         attributeButton.setIcon(attributeIcon);
3003         attributeButton.triggered.connect(this, "toggleNoteInformation()");
3004         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
3005                 
3006         emailButton = toolBar.addAction(tr("Email"));
3007         QIcon emailIcon = new QIcon(iconPath+"email.png");
3008         emailButton.setIcon(emailIcon);
3009         emailButton.triggered.connect(this, "emailNote()");
3010         toggleEmailButton(Global.isToolbarButtonVisible("email"));
3011
3012         deleteButton = toolBar.addAction(tr("Delete"));         
3013         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
3014         deleteButton.setIcon(deleteIcon);
3015         deleteButton.triggered.connect(this, "deleteNote()");
3016         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
3017
3018         newButton = toolBar.addAction(tr("New"));
3019         QIcon newIcon = new QIcon(iconPath+"new.png");
3020         newButton.triggered.connect(this, "addNote()");
3021         newButton.setIcon(newIcon);
3022         toggleNewButton(Global.isToolbarButtonVisible("new"));
3023         
3024         allNotesButton = toolBar.addAction(tr("All Notes"));
3025         QIcon allIcon = new QIcon(iconPath+"books.png");
3026         allNotesButton.triggered.connect(this, "allNotes()");
3027         allNotesButton.setIcon(allIcon);
3028         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
3029         
3030         //toolBar.addSeparator();
3031         //toolBar.addWidget(new QLabel(tr("Quota:")));
3032         //toolBar.addWidget(quotaBar);
3033         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
3034         updateQuotaBar();
3035         //toolBar.addSeparator();
3036         
3037         //toolBar.addWidget(new QLabel(tr("Zoom")));
3038         //toolBar.addWidget(zoomSpinner);
3039         
3040         //toolBar.addWidget(new QLabel("                    "));
3041         //toolBar.addSeparator();
3042         //toolBar.addWidget(new QLabel(tr("  Search:")));
3043         //toolBar.addWidget(searchField);
3044         QSizePolicy sizePolicy = new QSizePolicy();
3045         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
3046         QLabel spacer = new QLabel("");
3047         spacer.setSizePolicy(sizePolicy);
3048         toolBar.addWidget(spacer);
3049         //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
3050
3051         //searchClearButton = toolBar.addAction("Search Clear");
3052         //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
3053         //searchClearButton.setIcon(searchClearIcon);
3054         //searchClearButton.triggered.connect(this, "searchFieldCleared()");
3055         //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
3056
3057         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
3058     }
3059     // Update the sychronize button picture
3060     @Override
3061         public QMenu createPopupMenu() {
3062         QMenu contextMenu = super.createPopupMenu();
3063         
3064         contextMenu.addSeparator();
3065         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
3066         contextMenu.addAction(prevAction);
3067         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
3068
3069         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
3070         contextMenu.addAction(nextAction);
3071         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
3072
3073         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
3074         contextMenu.addAction(upAction);
3075         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
3076
3077         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
3078         contextMenu.addAction(downAction);
3079         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3080
3081         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3082         contextMenu.addAction(synchronizeAction);
3083         synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3084
3085         QAction printAction = addContextAction("print", tr("Print"));
3086         contextMenu.addAction(printAction);
3087         printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3088
3089         QAction tagAction = addContextAction("tag", tr("Tag"));
3090         contextMenu.addAction(tagAction);
3091         tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3092         
3093         QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3094         contextMenu.addAction(attributeAction);
3095         attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3096         
3097         QAction emailAction = addContextAction("email", tr("Email"));
3098         contextMenu.addAction(emailAction);
3099         emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3100
3101         QAction deleteAction = addContextAction("delete", tr("Delete"));
3102         contextMenu.addAction(deleteAction);
3103         deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3104
3105         QAction newAction = addContextAction("new", tr("Add"));
3106         contextMenu.addAction(newAction);
3107         newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3108
3109         QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3110         contextMenu.addAction(allNotesAction);
3111         allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3112         
3113         QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3114         contextMenu.addAction(searchClearAction);
3115         searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3116         
3117         return contextMenu;
3118         
3119     }
3120     private QAction addContextAction(String config, String name) {
3121         QAction newAction = new QAction(this);
3122                 newAction.setText(name);
3123                 newAction.setCheckable(true);
3124                 newAction.setChecked(Global.isToolbarButtonVisible(config));
3125                 return newAction;
3126     }
3127     private void togglePrevArrowButton(Boolean toggle) {
3128                 prevButton.setVisible(toggle);
3129                 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3130     }
3131     private void toggleNextArrowButton(Boolean toggle) {
3132                 nextButton.setVisible(toggle);
3133                 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3134     }
3135     private void toggleUpArrowButton(Boolean toggle) {
3136                 upButton.setVisible(toggle);
3137                 Global.saveToolbarButtonsVisible("upArrow", toggle);
3138     }
3139     private void toggleDownArrowButton(Boolean toggle) {
3140                 downButton.setVisible(toggle);
3141                 Global.saveToolbarButtonsVisible("downArrow", toggle);
3142     }
3143     private void toggleSynchronizeButton(Boolean toggle) {
3144                 synchronizeButton.setVisible(toggle);
3145                 Global.saveToolbarButtonsVisible("synchronize", toggle);
3146     }
3147     private void togglePrintButton(Boolean toggle) {
3148                 printButton.setVisible(toggle);
3149                 Global.saveToolbarButtonsVisible("print", toggle);
3150     }
3151     private void toggleTagButton(Boolean toggle) {
3152                 tagButton.setVisible(toggle);
3153                 Global.saveToolbarButtonsVisible("tag", toggle);
3154     }
3155     private void toggleAttributeButton(Boolean toggle) {
3156                 attributeButton.setVisible(toggle);
3157                 Global.saveToolbarButtonsVisible("attribute", toggle);
3158     }
3159     private void toggleEmailButton(Boolean toggle) {
3160                 emailButton.setVisible(toggle);
3161                 Global.saveToolbarButtonsVisible("email", toggle);
3162     }
3163     private void toggleDeleteButton(Boolean toggle) {
3164                 deleteButton.setVisible(toggle);
3165                 Global.saveToolbarButtonsVisible("delete", toggle);
3166     }
3167     private void toggleNewButton(Boolean toggle) {
3168                 newButton.setVisible(toggle);
3169                 Global.saveToolbarButtonsVisible("new", toggle);
3170     }
3171     private void toggleAllNotesButton(Boolean toggle) {
3172                 allNotesButton.setVisible(toggle);
3173                 Global.saveToolbarButtonsVisible("allNotes", toggle);
3174     }
3175     @SuppressWarnings("unused")
3176         private void toggleSearchClearButton(Boolean toggle) {
3177                 searchClearButton.setVisible(toggle);
3178                 Global.saveToolbarButtonsVisible("searchClear", toggle);
3179     }
3180
3181
3182
3183
3184
3185     @SuppressWarnings("unused")
3186         private void updateSyncButton() {
3187                 
3188         if (syncIcons == null) {
3189                 syncIcons = new ArrayList<QPixmap>();
3190                 double angle = 0.0;
3191                 synchronizeIconAngle = 0;
3192                 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3193                 syncIcons.add(pix);
3194                 for (int i=0; i<=360; i++) {
3195                         QPixmap rotatedPix = new QPixmap(pix.size());
3196                         QPainter p = new QPainter(rotatedPix);
3197                 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3198                 QSize size = pix.size();
3199                 p.translate(size.width()/2, size.height()/2);
3200                 angle = angle+1.0;
3201                 p.rotate(angle);
3202                 p.setBackgroundMode(BGMode.OpaqueMode);
3203                 p.translate(-size.width()/2, -size.height()/2);
3204                 p.drawPixmap(0,0, pix);
3205                 p.end();
3206                 syncIcons.add(rotatedPix);
3207                 }
3208         }
3209
3210         synchronizeIconAngle++;
3211         if (synchronizeIconAngle > 359)
3212                 synchronizeIconAngle=0;
3213         synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3214         
3215     }
3216     // Synchronize with Evernote
3217
3218         private void evernoteSync() {
3219         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3220         if (!Global.isConnected)
3221                 remoteConnect();
3222         if (Global.isConnected)
3223                 synchronizeAnimationTimer.start(5);
3224 //                      synchronizeAnimationTimer.start(200);
3225         syncTimer();
3226         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3227     }
3228     private void updateQuotaBar() {
3229         long limit = Global.getUploadLimit();
3230         long amount = Global.getUploadAmount();
3231         if (amount>0 && limit>0) {
3232                 int percent =(int)(amount*100/limit);
3233                 quotaBar.setValue(percent);
3234         } else 
3235                 quotaBar.setValue(0);
3236     }
3237         // Zoom changed
3238     @SuppressWarnings("unused")
3239         private void zoomChanged() {
3240         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3241     }
3242
3243     //****************************************************************
3244     //****************************************************************
3245     //* System Tray functions
3246     //****************************************************************
3247     //****************************************************************
3248         private void trayToggleVisible() {
3249         if (isVisible()) {
3250                 hide();
3251         } else {
3252                 show();
3253                 if (windowMaximized)
3254                         showMaximized();
3255                 else
3256                         showNormal();
3257                 raise();
3258         }
3259     }
3260     @SuppressWarnings("unused")
3261         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3262         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3263                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3264                 trayToggleVisible();
3265         }
3266     }
3267     
3268     
3269     //***************************************************************
3270     //***************************************************************
3271     //** These functions deal with the trash tree
3272     //***************************************************************
3273     //***************************************************************    
3274     // Setup the tree containing the trash.
3275     @SuppressWarnings("unused")
3276         private void trashTreeSelection() {     
3277         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3278         
3279         clearNotebookFilter();
3280         clearTagFilter();
3281         clearAttributeFilter();
3282         clearSavedSearchFilter();
3283         
3284         String tempGuid = currentNoteGuid;
3285         
3286 //      currentNoteGuid = "";
3287         currentNote = new Note();
3288         selectedNoteGUIDs.clear();
3289         listManager.getSelectedNotebooks().clear();
3290         listManager.getSelectedTags().clear();
3291         listManager.setSelectedSavedSearch("");
3292         browserWindow.clear();
3293     
3294         // toggle the add buttons
3295         newButton.setEnabled(!newButton.isEnabled());
3296         menuBar.noteAdd.setEnabled(newButton.isEnabled());
3297         menuBar.noteAdd.setVisible(true);
3298         
3299         List<QTreeWidgetItem> selections = trashTree.selectedItems();
3300         if (selections.size() == 0) {
3301                 currentNoteGuid = trashNoteGuid;
3302                         trashNoteGuid = tempGuid;
3303                 Global.showDeleted = false;
3304                 menuBar.noteRestoreAction.setEnabled(false);
3305                 menuBar.noteRestoreAction.setVisible(false);
3306         }
3307         else {
3308                 trashNoteGuid = tempGuid;
3309                 currentNoteGuid = trashNoteGuid;
3310                 menuBar.noteRestoreAction.setEnabled(true);
3311                 menuBar.noteRestoreAction.setVisible(true);
3312                 Global.showDeleted = true;
3313         }
3314         listManager.loadNotesIndex();
3315         noteIndexUpdated(false);
3316 ////            browserWindow.setEnabled(newButton.isEnabled());
3317         browserWindow.setReadOnly(!newButton.isEnabled());
3318         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3319     }
3320     // Empty the trash file
3321     @SuppressWarnings("unused")
3322         private void emptyTrash() {
3323 //      browserWindow.clear();
3324         logger.log(logger.EXTREME, "Emptying Trash");
3325         listManager.emptyTrash();
3326         logger.log(logger.EXTREME, "Resetting view after trash empty");
3327         if (trashTree.selectedItems().size() > 0) {
3328                 listManager.getSelectedNotebooks().clear();
3329                 listManager.getSelectedTags().clear();
3330                 listManager.setSelectedSavedSearch("");
3331                 newButton.setEnabled(!newButton.isEnabled());
3332                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3333                 menuBar.noteAdd.setVisible(true);
3334                 browserWindow.clear();
3335                 
3336                 clearTagFilter();
3337                 clearNotebookFilter();
3338                 clearSavedSearchFilter();
3339                 clearAttributeFilter();
3340                         
3341                 Global.showDeleted = false;
3342                 menuBar.noteRestoreAction.setEnabled(false);
3343                 menuBar.noteRestoreAction.setVisible(false);
3344                 
3345                 listManager.loadNotesIndex();
3346                 noteIndexUpdated(false);
3347         }       
3348    }
3349     // Show/Hide trash window
3350         @SuppressWarnings("unused")
3351         private void toggleTrashWindow() {
3352                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3353         if (trashTree.isVisible())
3354                 trashTree.hide();
3355         else
3356                 trashTree.show();
3357         menuBar.hideTrash.setChecked(trashTree.isVisible());
3358         
3359                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3360         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3361     }    
3362         private void clearTrashFilter() {
3363                 Global.showDeleted = false;
3364         newButton.setEnabled(true);
3365         menuBar.noteAdd.setEnabled(true);
3366         menuBar.noteAdd.setVisible(true);
3367                 trashTree.blockSignals(true);
3368                 trashTree.clearSelection();
3369                 trashTree.blockSignals(false);
3370                 
3371         }
3372     
3373    
3374     //***************************************************************
3375     //***************************************************************
3376     //** These functions deal with connection settings
3377     //***************************************************************
3378     //***************************************************************
3379         // SyncRunner had a problem and things are disconnected
3380         @SuppressWarnings("unused")
3381         private void remoteErrorDisconnect() {
3382                 menuBar.connectAction.setText(tr("Connect"));
3383                 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3384                 menuBar.synchronizeAction.setEnabled(false);
3385                 Global.isConnected = false;
3386                 synchronizeAnimationTimer.stop();
3387                 return;
3388         }
3389         // Do a manual connect/disconnect
3390     private void remoteConnect() {
3391         
3392         logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3393
3394         // If we are already connected, we just disconnect
3395         if (Global.isConnected) {
3396                 Global.isConnected = false;
3397                 syncRunner.enDisconnect();
3398                 setupConnectMenuOptions();
3399                 setupOnlineMenu();
3400                 return;
3401         }
3402         
3403         OAuthTokenizer tokenizer = new OAuthTokenizer();
3404         AESEncrypter aes = new AESEncrypter();
3405         try {
3406                         aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("oauth.txt")));
3407                 } catch (FileNotFoundException e) {
3408                         // File not found, so we'll just get empty strings anyway. 
3409                 }
3410         
3411                 
3412                 if (Global.getProxyValue("url").equals("")) {
3413                         System.setProperty("http.proxyHost","") ;
3414                         System.setProperty("http.proxyPort", "") ;
3415                         System.setProperty("https.proxyHost","") ;
3416                         System.setProperty("https.proxyPort", "") ;         
3417                 } else {
3418                         // PROXY
3419                         System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3420                         System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3421                         System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3422                         System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3423  
3424                         if (Global.getProxyValue("userid").equals("")) {
3425                                 Authenticator.setDefault(new Authenticator() {
3426                         @Override
3427                         protected PasswordAuthentication getPasswordAuthentication() {
3428                                 return new
3429                                 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3430                                 }
3431                         });
3432                 }
3433         }
3434
3435                 syncRunner.userStoreUrl = Global.userStoreUrl;
3436                 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3437                 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3438                 
3439                 
3440                 
3441                 String authString = aes.getString();
3442                 if (!authString.equals("")) {
3443                         tokenizer.tokenize(authString);
3444                         syncRunner.authToken = tokenizer.oauth_token;
3445                 syncRunner.enConnect();
3446                 }               
3447
3448                 Global.isConnected = syncRunner.isConnected;
3449                 
3450                 if (!Global.isConnected) {
3451                 OAuthWindow window = new OAuthWindow(logger);
3452                 if (window.error) {
3453                         setMessage(window.errorMessage);
3454                         return;
3455                 }
3456                 window.exec();
3457                 if (window.error) {
3458                         setMessage(window.errorMessage);
3459                         return;
3460                         }
3461                 tokenizer.tokenize(window.response);
3462                 if (tokenizer.oauth_token.equals("")) {
3463                         setMessage(tr("Invalid authorization token received."));
3464                         return;
3465                 }
3466                 aes.setString(window.response);
3467                 try {
3468                                 aes.encrypt(new FileOutputStream(Global.getFileManager().getHomeDirFile("oauth.txt")));
3469                         } catch (FileNotFoundException e) {
3470                                 // TODO Auto-generated catch block
3471                                 e.printStackTrace();
3472                         }
3473                 syncRunner.authToken = tokenizer.oauth_token;
3474                         syncRunner.enConnect();
3475                         Global.isConnected = syncRunner.isConnected;
3476                 }
3477                 Global.username = syncRunner.username;
3478                         
3479                 if (!Global.isConnected)
3480                         return;
3481                 setupOnlineMenu();
3482                 setupConnectMenuOptions();
3483                 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3484
3485
3486     }
3487     private void setupConnectMenuOptions() {
3488         logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3489                 if (!Global.isConnected) {
3490                         menuBar.connectAction.setText(tr("Connect"));
3491                         menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3492                         menuBar.synchronizeAction.setEnabled(false);
3493                 } else {
3494                         menuBar.connectAction.setText(tr("Disconnect"));
3495                         menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3496                         menuBar.synchronizeAction.setEnabled(true);
3497                 }
3498                 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3499     }
3500     
3501     
3502     
3503     //***************************************************************
3504     //***************************************************************
3505     //** These functions deal with the GUI Attribute tree
3506     //***************************************************************
3507     //***************************************************************    
3508     @SuppressWarnings("unused")
3509         private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3510         
3511 //      clearTagFilter();
3512 //      clearNotebookFilter();
3513         clearTrashFilter();
3514 //      clearSavedSearchFilter();
3515
3516         if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3517                 if (item.childCount() > 0) {
3518                         item.setSelected(false);
3519                 } else {
3520                 Global.createdBeforeFilter.reset();
3521                 Global.createdSinceFilter.reset();
3522                 Global.changedBeforeFilter.reset();
3523                 Global.changedSinceFilter.reset();
3524                 Global.containsFilter.reset();
3525                         attributeTreeSelected = item;
3526                         DateAttributeFilterTable f = null;
3527                         f = findDateAttributeFilterTable(item.parent());
3528                         if (f!=null)
3529                                 f.select(item.parent().indexOfChild(item));
3530                         else {
3531                                 Global.containsFilter.select(item.parent().indexOfChild(item));
3532                         }
3533                 }
3534                 listManager.loadNotesIndex();
3535                 noteIndexUpdated(false);
3536                 return;
3537         }
3538                 attributeTreeSelected = null;
3539                 item.setSelected(false);
3540         Global.createdBeforeFilter.reset();
3541         Global.createdSinceFilter.reset();
3542         Global.changedBeforeFilter.reset();
3543         Global.changedSinceFilter.reset();
3544         Global.containsFilter.reset();
3545         listManager.loadNotesIndex();
3546                 noteIndexUpdated(false); 
3547     }
3548     // This determines what attribute filter we need, depending upon the selection
3549     private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3550                 if (w.parent() != null && w.childCount() > 0) {
3551                         QTreeWidgetItem parent = w.parent();
3552                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
3553                                 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3554                                         return Global.createdSinceFilter;
3555                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
3556                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3557                                         return Global.createdBeforeFilter;
3558                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
3559                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3560                                         return Global.changedSinceFilter;
3561                 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
3562                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3563                                                 return Global.changedBeforeFilter;
3564                 }
3565                 return null;
3566     }
3567
3568     // Show/Hide attribute search window
3569         @SuppressWarnings("unused")
3570         private void toggleAttributesWindow() {
3571                 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3572         if (attributeTree.isVisible())
3573                 attributeTree.hide();
3574         else
3575                 attributeTree.show();
3576         menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3577         
3578                 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3579         logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3580     }    
3581         private void clearAttributeFilter() {
3582         Global.createdBeforeFilter.reset();
3583         Global.createdSinceFilter.reset();
3584         Global.changedBeforeFilter.reset();
3585         Global.changedSinceFilter.reset();
3586         Global.containsFilter.reset();
3587         attributeTreeSelected = null;
3588                 attributeTree.blockSignals(true);
3589                 attributeTree.clearSelection();
3590                 attributeTree.blockSignals(false);
3591         }
3592     
3593         
3594     //***************************************************************
3595     //***************************************************************
3596     //** These functions deal with the GUI Note index table
3597     //***************************************************************
3598     //***************************************************************    
3599     // Initialize the note list table
3600         private void initializeNoteTable() {
3601                 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3602                 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3603                 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3604                 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3605         }       
3606     // Show/Hide trash window
3607         @SuppressWarnings("unused")
3608         private void toggleNoteListWindow() {
3609                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3610         if (noteTableView.isVisible())
3611                 noteTableView.hide();
3612         else
3613                 noteTableView.show();
3614         menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3615         
3616                 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3617         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3618     }   
3619         // Handle the event that a user selects a note from the table
3620     @SuppressWarnings("unused")
3621         private void noteTableSelection() {
3622                 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3623
3624                 saveNote();
3625                 
3626                 // If we have more than one selection, then set the merge note action to true.
3627         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3628                 if (selections.size() > 1) 
3629                 menuBar.noteMergeAction.setEnabled(true);
3630                 else
3631                         menuBar.noteMergeAction.setEnabled(false);
3632
3633                 // If the ctrl key is pressed, then they are selecting multiple 
3634                 // entries and we don't want to change the currently viewed note.
3635                 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3636                                 QApplication.mouseButtons().isSet(MouseButton.LeftButton)) 
3637                         return;
3638
3639                 if (historyGuids.size() == 0) {
3640                         historyGuids.add(currentNoteGuid);
3641                         historyPosition = 1;
3642                 }
3643         noteTableView.showColumn(Global.noteTableGuidPosition);
3644         
3645         if (!Global.isColumnVisible("guid"))
3646                 noteTableView.hideColumn(Global.noteTableGuidPosition);
3647         
3648         if (selections.size() > 0) {
3649                 QModelIndex index;
3650                 menuBar.noteDuplicateAction.setEnabled(true);
3651                 menuBar.noteOnlineHistoryAction.setEnabled(true);
3652                 menuBar.noteMergeAction.setEnabled(true);
3653                 selectedNoteGUIDs.clear();
3654                 if (selections.size() != 1 || Global.showDeleted) {
3655                         menuBar.noteDuplicateAction.setEnabled(false);
3656                 }
3657                 if (selections.size() != 1 || !Global.isConnected) {
3658                         menuBar.noteOnlineHistoryAction.setEnabled(false);
3659                 }
3660                 if (selections.size() == 1) {
3661                         menuBar.noteMergeAction.setEnabled(false);
3662                 }
3663                 for (int i=0; i<selections.size(); i++) {
3664                         int row = selections.get(i).row();
3665                         if (row == 0) 
3666                                 upButton.setEnabled(false);
3667                         else
3668                                 upButton.setEnabled(true);
3669                         if (row < listManager.getNoteTableModel().rowCount()-1)
3670                                 downButton.setEnabled(true);
3671                         else
3672                                 downButton.setEnabled(false);
3673                         index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3674                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3675                         currentNoteGuid = (String)ix.values().toArray()[0];
3676                         selectedNoteGUIDs.add(currentNoteGuid);
3677                 }
3678         }
3679         
3680         nextButton.setEnabled(true);
3681                 prevButton.setEnabled(true);
3682         if (!fromHistory) {
3683                 int endPosition = historyGuids.size()-1;
3684                 for (int j=historyPosition; j<=endPosition; j++) {
3685                         historyGuids.remove(historyGuids.size()-1);
3686                 }
3687                 historyGuids.add(currentNoteGuid);
3688                 historyPosition = historyGuids.size();
3689         } 
3690         if (historyPosition <= 1)
3691                 prevButton.setEnabled(false);
3692         if (historyPosition == historyGuids.size())
3693                 nextButton.setEnabled(false);
3694                 
3695         fromHistory = false;
3696         scrollToGuid(currentNoteGuid);
3697         refreshEvernoteNote(true);
3698                 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3699     }    
3700         // Trigger a refresh when the note db has been updated
3701         private void noteIndexUpdated(boolean reload) {
3702                 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3703                 saveNote();
3704         refreshEvernoteNoteList();
3705         logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3706         noteTableView.load(reload);
3707         if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3708                 int pos;
3709                 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3710                         pos = noteTableView.proxyModel.rowCount();
3711                 else 
3712                         pos = 1;
3713                 if (noteTableView.proxyModel.rowCount() == 0)
3714                         pos = 0;
3715                 if (pos>0)      {
3716                         QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3717                         if (i!=null) {
3718                                 currentNoteGuid = (String)i.data();
3719                         }
3720                 }
3721         }               
3722                 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3723                         showColumns();
3724                 scrollToGuid(currentNoteGuid);
3725                 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3726     }
3727         // Called when the list of notes is updated
3728     private void refreshEvernoteNoteList() {
3729         logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3730         browserWindow.setDisabled(false);
3731                 if (selectedNoteGUIDs == null)
3732                         selectedNoteGUIDs = new ArrayList<String>();
3733                 selectedNoteGUIDs.clear();  // clear out old entries
3734                 
3735                 String saveCurrentNoteGuid = new String();
3736                 String tempNoteGuid = new String();
3737                                 
3738                 historyGuids.clear();
3739                 historyPosition = 0;
3740                 prevButton.setEnabled(false);
3741                 nextButton.setEnabled(false);
3742                 
3743                 if (currentNoteGuid == null) 
3744                         currentNoteGuid = new String();
3745                 
3746                 //determine current note guid
3747                 for (Note note : listManager.getNoteIndex()) {
3748                         tempNoteGuid = note.getGuid();
3749                         if (currentNoteGuid.equals(tempNoteGuid)) {
3750                                 saveCurrentNoteGuid = tempNoteGuid;
3751                         }
3752                 }
3753                 
3754                 if (listManager.getNoteIndex().size() == 0) {
3755                         currentNoteGuid = "";
3756                         currentNote = null;
3757                         browserWindow.clear();
3758                         browserWindow.setDisabled(true);
3759                 } 
3760                 
3761                 if (Global.showDeleted && listManager.getNotebookIndex().size() > 0 && saveCurrentNoteGuid.equals("")) {
3762                         currentNoteGuid = listManager.getNoteIndex().get(0).getGuid();
3763                         saveCurrentNoteGuid = currentNoteGuid;
3764                         refreshEvernoteNote(true);
3765                 }
3766                 
3767                 if (!saveCurrentNoteGuid.equals("")) {
3768                         refreshEvernoteNote(false);
3769                 } else {
3770                                 currentNoteGuid = "";
3771                 }
3772                 reloadTagTree(false);
3773
3774                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3775         } 
3776     // Called when the previous arrow button is clicked 
3777     @SuppressWarnings("unused")
3778         private void previousViewedAction() {
3779         if (!prevButton.isEnabled())
3780                 return;
3781         if (historyPosition == 0)
3782                 return;
3783                 historyPosition--;
3784         if (historyPosition <= 0)
3785                 return;
3786         String historyGuid = historyGuids.get(historyPosition-1);
3787         fromHistory = true;
3788         for (int i=0; i<noteTableView.model().rowCount(); i++) {
3789                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
3790                 if (modelIndex != null) {
3791                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3792                         String tableGuid =  (String)ix.values().toArray()[0];
3793                         if (tableGuid.equals(historyGuid)) {
3794                                 noteTableView.selectRow(i);
3795                                 return;
3796                         }       
3797                 }
3798         }
3799     }
3800     @SuppressWarnings("unused")
3801         private void nextViewedAction() {
3802         if (!nextButton.isEnabled())
3803                 return;
3804         String historyGuid = historyGuids.get(historyPosition);
3805         historyPosition++;
3806         fromHistory = true;
3807         for (int i=0; i<noteTableView.model().rowCount(); i++) {
3808                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
3809                 if (modelIndex != null) {
3810                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3811                         String tableGuid =  (String)ix.values().toArray()[0];
3812                         if (tableGuid.equals(historyGuid)) {
3813                                 noteTableView.selectRow(i);
3814                                 return;
3815                         }       
3816                 }
3817         }       
3818     }
3819     // Called when the up arrow is clicked 
3820     @SuppressWarnings("unused")
3821         private void upAction() {
3822         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3823         int row = selections.get(0).row();
3824         if (row > 0) {
3825                 noteTableView.selectRow(row-1);
3826         }
3827     }
3828     // Called when the down arrow is clicked 
3829     @SuppressWarnings("unused")
3830         private void downAction() {
3831         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3832         int row = selections.get(0).row();
3833         int max = listManager.getNoteTableModel().rowCount();
3834         if (row < max-1) {
3835                 noteTableView.selectRow(row+1);
3836         }
3837     }
3838     // Update a tag string for a specific note in the list
3839     @SuppressWarnings("unused")
3840         private void updateListTags(String guid, List<String> tags) {
3841         logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3842         StringBuffer tagBuffer = new StringBuffer();
3843         for (int i=0; i<tags.size(); i++) {
3844                 tagBuffer.append(tags.get(i));
3845                 if (i<tags.size()-1)
3846                         tagBuffer.append(", ");
3847         }
3848         
3849         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3850                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3851                 if (modelIndex != null) {
3852                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3853                         String tableGuid =  (String)ix.values().toArray()[0];
3854                         if (tableGuid.equals(guid)) {
3855                                 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3856                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3857                                 noteTableView.proxyModel.invalidate();
3858                                 return;
3859                         }
3860                 }
3861         }
3862         logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3863     }
3864     // Update a title for a specific note in the list
3865     @SuppressWarnings("unused")
3866         private void updateListAuthor(String guid, String author) {
3867         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3868
3869         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3870                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3871                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3872                 if (modelIndex != null) {
3873                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3874                         String tableGuid =  (String)ix.values().toArray()[0];
3875                         if (tableGuid.equals(guid)) {
3876                                 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3877                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3878                                 noteTableView.proxyModel.invalidate();
3879                                 return;
3880                         }       
3881                 }
3882         }
3883         
3884         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3885     }
3886         private void updateListNoteNotebook(String guid, String notebook) {
3887         logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3888         listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3889         logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3890     }
3891     // Update a title for a specific note in the list
3892     @SuppressWarnings("unused")
3893         private void updateListSourceUrl(String guid, String url) {
3894         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3895
3896         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3897                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3898                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3899                 if (modelIndex != null) {
3900 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3901                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3902                         String tableGuid =  (String)ix.values().toArray()[0];
3903                         if (tableGuid.equals(guid)) {
3904                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3905                                 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3906                                 noteTableView.proxyModel.invalidate();
3907                                 return;
3908                         }       
3909                 }
3910         }
3911         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3912     }
3913         @SuppressWarnings("unused")
3914         private void updateListGuid(String oldGuid, String newGuid) {
3915         logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3916
3917         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3918                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3919                 if (modelIndex != null) {
3920                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3921                         String tableGuid =  (String)ix.values().toArray()[0];
3922                         if (tableGuid.equals(oldGuid)) {
3923                                 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3924                                 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3925                                 return;
3926                         }       
3927                 }
3928         }
3929         logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3930     }
3931         private void updateListTagName(String guid) {
3932         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3933                 
3934                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3935                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3936                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3937
3938                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3939                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3940                                         if (modelIndex != null) {
3941                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3942                                                 String noteGuid = (String)ix.values().toArray()[0];
3943                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3944                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3945                                                         i=listManager.getNoteTableModel().rowCount();
3946                                                 }
3947                                         }
3948                                 }
3949                         }
3950                 }       
3951         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3952     }
3953         private void removeListTagName(String guid) {
3954         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3955                 
3956                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3957                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3958                                 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3959                                         if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3960                                                 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3961                                 }
3962                                 
3963                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3964                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3965                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3966                                         if (modelIndex != null) {
3967                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3968                                                 String noteGuid = (String)ix.values().toArray()[0];
3969                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3970                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3971                                                         i=listManager.getNoteTableModel().rowCount();
3972                                                 }
3973                                         }
3974                                 }
3975                         }
3976                 }       
3977         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3978     }
3979     private void updateListNotebookName(String oldName, String newName) {
3980         logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3981
3982         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3983                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition); 
3984                 if (modelIndex != null) {
3985                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3986                         String tableName =  (String)ix.values().toArray()[0];
3987                         if (tableName.equalsIgnoreCase(oldName)) {
3988                                 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3989                         }
3990                 }
3991         }
3992         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3993     }
3994     @SuppressWarnings("unused")
3995         private void updateListDateCreated(String guid, QDateTime date) {
3996         logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3997
3998         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3999                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4000                 if (modelIndex != null) {
4001                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4002                         String tableGuid =  (String)ix.values().toArray()[0];
4003                         if (tableGuid.equals(guid)) {
4004                                 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4005                                 noteTableView.proxyModel.invalidate();
4006                                 return;
4007                         }
4008                 }
4009         }
4010         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
4011     }
4012     @SuppressWarnings("unused")
4013         private void updateListDateSubject(String guid, QDateTime date) {
4014         logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
4015
4016         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4017                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4018                 if (modelIndex != null) {
4019                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4020                         String tableGuid =  (String)ix.values().toArray()[0];
4021                         if (tableGuid.equals(guid)) {
4022                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4023                                 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4024                                 noteTableView.proxyModel.invalidate();
4025                                 return;
4026                         }
4027                 }
4028         }
4029         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
4030     }
4031         private void updateListDateChanged(String guid, QDateTime date) {
4032         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4033
4034         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4035                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4036                 if (modelIndex != null) {
4037                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4038                         String tableGuid =  (String)ix.values().toArray()[0];
4039                         if (tableGuid.equals(guid)) {
4040                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4041                                 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
4042                                 return;
4043                         }
4044                 }
4045         }
4046         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4047     }
4048     private void updateListDateChanged() {
4049         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
4050         QDateTime date = new QDateTime(QDateTime.currentDateTime());
4051         updateListDateChanged(currentNoteGuid, date);
4052         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
4053     }  
4054     // Redo scroll
4055         private void scrollToCurrentGuid() {
4056         //scrollToGuid(currentNoteGuid);
4057         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
4058         if (selections.size() == 0)
4059                 return;
4060         QModelIndex index = selections.get(0);
4061         int row = selections.get(0).row();
4062         String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
4063         scrollToGuid(guid);
4064     }
4065         // Scroll to the current GUID in tthe list.
4066     // Scroll to a particular index item
4067     private void scrollToGuid(String guid) {
4068         if (currentNote == null || guid == null) 
4069                 return;
4070         if (currentNote.isActive() && Global.showDeleted) {
4071                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4072                         if (!listManager.getNoteIndex().get(i).isActive()) {
4073                                 currentNote = listManager.getNoteIndex().get(i);
4074                                 currentNoteGuid =  currentNote.getGuid();
4075                                 i = listManager.getNoteIndex().size();
4076                         }
4077                 }
4078         }
4079         if (!currentNote.isActive() && !Global.showDeleted) {
4080                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4081                         if (listManager.getNoteIndex().get(i).isActive()) {
4082                                 currentNote = listManager.getNoteIndex().get(i);
4083                                 currentNoteGuid =  currentNote.getGuid();
4084                                 i = listManager.getNoteIndex().size();
4085                         }
4086                 }
4087         }
4088         QModelIndex index; 
4089         for (int i=0; i<noteTableView.model().rowCount(); i++) {
4090                 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
4091                 if (currentNoteGuid.equals(index.data())) {
4092 //                      noteTableView.selectionModel().blockSignals(true);
4093                         noteTableView.selectRow(i);
4094 //                              noteTableView.selectionModel().blockSignals(false);
4095                         noteTableView.scrollTo(index, ScrollHint.EnsureVisible);  // This should work, but it doesn't
4096                                 i=listManager.getNoteTableModel().rowCount();
4097                 }
4098         }
4099         noteTableView.repaint();
4100     }
4101     // Show/Hide columns
4102     private void showColumns() {
4103                 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
4104                 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
4105                 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
4106                 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
4107                 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4108                 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4109                 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4110                 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4111                 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4112                 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4113                 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));         
4114                 noteTableView.setColumnHidden(Global.noteTablePinnedPosition, !Global.isColumnVisible("pinned")); 
4115     }
4116     // Title color has changed
4117     @SuppressWarnings("unused")
4118         private void titleColorChanged(Integer color) {
4119         logger.log(logger.HIGH, "Entering NeverNote.titleColorChanged");
4120
4121         setNoteDirty();
4122         QColor backgroundColor = new QColor();
4123                 QColor foregroundColor = new QColor(QColor.black);
4124                 backgroundColor.setRgb(color);
4125                 
4126                 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4127                         foregroundColor.setRgb(QColor.white.rgb());
4128         
4129                 if (selectedNoteGUIDs.size() == 0)
4130                         selectedNoteGUIDs.add(currentNoteGuid);
4131                 
4132         for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4133                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4134                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4135                         if (modelIndex != null) {
4136                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4137                                 String tableGuid =  (String)ix.values().toArray()[0];
4138                                 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4139                                         for (int k=0; k<Global.noteTableColumnCount; k++) {
4140                                                 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4141                                                 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4142                                                 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4143                                         }
4144                                         i=listManager.getNoteTableModel().rowCount();
4145                                 }
4146                         }
4147                 }
4148         }
4149         logger.log(logger.HIGH, "Leaving NeverNote.titleColorChanged");
4150     }
4151     // A note has been pinned or unpinned
4152         @SuppressWarnings("unused")
4153         private void notePinned() {
4154                 logger.log(logger.EXTREME, "Entering NeverNote.notePinned()");
4155                 setNoteDirty();
4156
4157         for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4158                 NoteMetadata meta = listManager.getNoteMetadata().get(selectedNoteGUIDs.get(j));
4159                 boolean pinned = !meta.isPinned();
4160                 meta.setPinned(pinned);   // Toggle the pinned/unpinned 
4161                 
4162                 // Update the list & table
4163                 listManager.updateNoteMetadata(meta);   
4164                 noteTableView.proxyModel.addGuid(selectedNoteGUIDs.get(j), meta);
4165         }
4166         
4167                 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4168     }
4169     // Wide list was chosen
4170     public void narrowListView() {
4171         saveNoteColumnPositions();
4172         saveNoteIndexWidth();
4173         saveWindowState();
4174                 int sortCol = noteTableView.proxyModel.sortColumn();
4175                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4176                 Global.setSortColumn(sortCol);
4177                 Global.setSortOrder(sortOrder);
4178
4179                 Global.setListView(Global.View_List_Narrow);
4180         
4181         menuBar.wideListView.blockSignals(true);
4182         menuBar.narrowListView.blockSignals(true);
4183         
4184         menuBar.wideListView.setChecked(false);
4185         menuBar.narrowListView.setChecked(true);
4186         
4187         menuBar.wideListView.blockSignals(false);
4188         menuBar.narrowListView.blockSignals(false);
4189         
4190         mainLeftRightSplitter.addWidget(noteTableView);
4191         mainLeftRightSplitter.addWidget(browserWindow);
4192         restoreWindowState(false);
4193         noteTableView.repositionColumns();
4194         noteTableView.resizeColumnWidths();
4195         noteTableView.resizeRowHeights();
4196         
4197         sortCol = Global.getSortColumn();
4198                 sortOrder = Global.getSortOrder();
4199                 noteTableView.proxyModel.blocked = true;
4200                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4201                 noteTableView.proxyModel.blocked = false;
4202
4203                 
4204         showColumns();
4205         noteTableView.load(false);
4206         refreshEvernoteNote(true);
4207         scrollToCurrentGuid();
4208     }
4209     public void wideListView() {
4210                 int sortCol = noteTableView.proxyModel.sortColumn();
4211                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4212                 Global.setSortColumn(sortCol);
4213                 Global.setSortOrder(sortOrder);
4214
4215                 saveWindowState();
4216         saveNoteColumnPositions();
4217         saveNoteIndexWidth();
4218         Global.setListView(Global.View_List_Wide);
4219
4220         menuBar.wideListView.blockSignals(true);
4221         menuBar.narrowListView.blockSignals(true);
4222         
4223         menuBar.wideListView.setChecked(true);
4224         menuBar.narrowListView.setChecked(false);
4225
4226         menuBar.wideListView.blockSignals(false);
4227         menuBar.narrowListView.blockSignals(false);
4228         browserIndexSplitter.setVisible(true);
4229         browserIndexSplitter.addWidget(noteTableView);
4230         browserIndexSplitter.addWidget(browserWindow);
4231         restoreWindowState(false);
4232         noteTableView.repositionColumns();
4233         noteTableView.resizeColumnWidths();
4234         noteTableView.resizeRowHeights();
4235         
4236         sortCol = Global.getSortColumn();
4237                 sortOrder = Global.getSortOrder();
4238                 noteTableView.proxyModel.blocked = true;
4239                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4240                 noteTableView.proxyModel.blocked = false;
4241
4242         showColumns();
4243         noteTableView.load(false);
4244         scrollToCurrentGuid();
4245     }
4246     // Sort order for the notebook has changed   
4247     public void tableSortOrderChanged(Integer column, Integer order) {
4248         
4249         // Find what notebook (if any) is selected.  We ignore stacks & the "All Notebooks".
4250         List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4251         if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4252                 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4253                 String notebook;
4254                 notebook = currentSelectedNotebook.text(2);
4255                 conn.getNotebookTable().setSortOrder(notebook, column, order);
4256         }       
4257     }
4258     
4259     //***************************************************************
4260     @SuppressWarnings("unused")
4261         private void evernoteLinkClick(String syncGuid, String locGuid) {
4262         String guid = null;
4263         if (conn.getNoteTable().guidExists(syncGuid)) {
4264                 guid = syncGuid;
4265         } else {
4266                 // If we didn't find it via the synchronized guid, look under the local guid
4267                 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was 
4268                 // later synchronized (that causes the guid to change so we need to find the new one).
4269                 if (conn.getNoteTable().guidExists(locGuid)) 
4270                         guid = locGuid;
4271                 else
4272                         guid = conn.getNoteTable().findAlternateGuid(locGuid);
4273         }
4274                 if (guid != null) {
4275                         openExternalEditor(guid);
4276                         return;
4277                 }
4278         
4279         //If we've gotten this far, we can't find the note
4280         QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4281                         " seem to find that note."));
4282     }
4283     //***************************************************************
4284     //***************************************************************
4285     //** External editor window functions                    
4286     //***************************************************************
4287     //***************************************************************
4288         private void listDoubleClick() {
4289                 saveNote();
4290         openExternalEditor(currentNoteGuid);
4291     }
4292     private void openExternalEditor(String guid) {
4293         
4294         if (externalWindows.containsKey(guid)) {
4295                 externalWindows.get(guid).raise();
4296                 return;
4297         }
4298         Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4299         // We have a new external editor to create
4300         QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4301         ExternalBrowse newBrowser = new ExternalBrowse(conn);
4302         newBrowser.setWindowIcon(appIcon);
4303         externalWindows.put(guid, newBrowser);
4304         showEditorButtons(newBrowser.getBrowserWindow());
4305         loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4306         setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4307         newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4308         //newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4309         newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4310         newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4311         newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4312         newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4313
4314         browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4315         browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4316         browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4317         
4318         newBrowser.show();
4319     }
4320     @SuppressWarnings({ "rawtypes", "unused" })
4321         private void externalWindowTagsEdited(String guid, List values) {
4322         StringBuffer line = new StringBuffer(100);
4323         for (int i=0; i<values.size(); i++) {
4324                 if (i>0) 
4325                         line.append(Global.tagDelimeter+" ");
4326                 line.append(values.get(i));
4327         }
4328         if (guid.equals(currentNoteGuid)) {
4329                 browserWindow.setTag(line.toString());
4330         }
4331     }
4332     @SuppressWarnings("unused")
4333         private void externalWindowClosing(String guid) {
4334                 externalWindows.remove(guid);
4335     }
4336
4337     
4338     
4339     //***************************************************************
4340     //***************************************************************
4341     //** These functions deal with Note specific things
4342     //***************************************************************
4343     //***************************************************************    
4344         private void setNoteDirty() {
4345                 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4346                 
4347                 // Find if the note is being edited externally.  If it is, update it.
4348                 if (externalWindows.containsKey(currentNoteGuid)) {
4349                         QTextCodec codec = QTextCodec.codecForName("UTF-8");
4350                 QByteArray unicode =  codec.fromUnicode(browserWindow.getContent());
4351                         ExternalBrowse window = externalWindows.get(currentNoteGuid);
4352                 window.getBrowserWindow().setContent(unicode);
4353                 }
4354                 
4355                 // If the note is dirty, then it is unsynchronized by default.
4356                 if (noteDirty) 
4357                         return;
4358                 
4359                 // Set the note as dirty and check if its status is synchronized in the display table
4360                 noteDirty = true;
4361                 if (listManager.getNoteMetadata().containsKey(currentNoteGuid) && 
4362                                 listManager.getNoteMetadata().get(currentNoteGuid).isDirty()) {
4363                                 return;
4364                 }
4365                 
4366                 // If this wasn't already marked as unsynchronized, then we need to update the table
4367                 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4368 //      listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4369         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4370                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4371                 if (modelIndex != null) {
4372                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4373                         String tableGuid =  (String)ix.values().toArray()[0];
4374                         if (tableGuid.equals(currentNoteGuid)) {
4375                                 listManager.getNoteTableModel().proxyModel.setData(i, Global.noteTableSynchronizedPosition, "false");
4376                                 return;
4377                         }
4378                 }
4379         }
4380         
4381                 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4382     }
4383     @SuppressWarnings("unused")
4384         private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4385                 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4386         QByteArray unicode =  codec.fromUnicode(content);
4387         noteCache.remove(guid);
4388                 noteCache.put(guid, unicode.toString());
4389         if (guid.equals(currentNoteGuid)) {
4390                 noteDirty = true;
4391                 browserWindow.setContent(unicode);
4392         } 
4393         if (save) {
4394                 thumbnailRunner.addWork("GENERATE "+ guid);
4395                 saveNote(guid, browser);
4396         }
4397         
4398     }
4399     private void saveNote() {
4400         if (noteDirty) {
4401                 saveNote(currentNoteGuid, browserWindow);
4402                 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4403                 noteDirty = false;
4404         } 
4405     }
4406     private void saveNote(String guid, BrowserWindow window) {
4407                 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4408                 waitCursor(true);
4409                 
4410                 logger.log(logger.EXTREME, "Saving to cache");
4411                 QTextCodec codec = QTextCodec.codecForLocale();
4412 //              QTextDecoder decoder = codec.makeDecoder();
4413                 codec = QTextCodec.codecForName("UTF-8");
4414         QByteArray unicode =  codec.fromUnicode(window.getContent());
4415                 noteCache.put(guid, unicode.toString());
4416                         
4417                 logger.log(logger.EXTREME, "updating list manager");
4418                 listManager.updateNoteContent(guid, window.getContent());
4419                 logger.log(logger.EXTREME, "Updating title");
4420                 listManager.updateNoteTitle(guid, window.getTitle());
4421                 updateListDateChanged();
4422
4423                 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4424                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4425                 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4426                         currentNote = listManager.getNoteIndex().get(i);
4427                         i = listManager.getNoteIndex().size();
4428                 }
4429         }
4430         waitCursor(false);
4431     }
4432     // Get a note from Evernote (and put it in the browser)
4433         private void refreshEvernoteNote(boolean reload) {
4434                 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4435                 
4436                 if (Global.disableViewing) {
4437                         browserWindow.setEnabled(false);
4438                         return;
4439                 }
4440                 inkNote = false;
4441                 readOnly = false;
4442                 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4443                         readOnly = true;
4444                 Global.cryptCounter =0;
4445                 if (readOnly) {
4446                         browserWindow.setReadOnly(true);
4447                 }
4448                 
4449                 if (!reload)
4450                         return;
4451                 
4452                 waitCursor(true);
4453                 browserWindow.loadingData(true);
4454
4455                 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4456                 if (currentNote == null) 
4457                         return;
4458                 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4459         }
4460
4461         private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4462                 NoteFormatter   formatter = new NoteFormatter(logger, conn, tempFiles);
4463                 formatter.setNote(note, Global.pdfPreview());
4464                 formatter.setHighlight(listManager.getEnSearch());
4465                 QByteArray js;
4466                 if (!noteCache.containsKey(guid)) {
4467                         js = new QByteArray();
4468                         // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly 
4469                         js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");               
4470                         js.append("<style type=\"text/css\">.en-crypt-temp { border-collapse:collapse; border-style:solid; border-color:blue; padding:0.0mm 0.0mm 0.0mm 0.0mm; }</style>");
4471                         js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4472                         js.append("<style> img { height:auto; width:auto; max-height:auto; max-width:100%; }</style>");
4473                         if (Global.displayRightToLeft())
4474                                 js.append("<style> body { direction:rtl; }</style>");
4475                         js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4476                         js.append("</head>");
4477                         formatter.setNote(note, Global.pdfPreview());
4478                         js.append(formatter.rebuildNoteHTML());
4479                         js.append("</HTML>");
4480                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4481                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4482                         js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4483 //              if (Global.enableHTMLEntitiesFix) {
4484 //                      browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4485 //              } else
4486                         browser.setContent(js);
4487                         noteCache.put(guid, js.toString());
4488
4489                         if (formatter.resourceError)
4490                                 resourceErrorMessage();
4491                         if (formatter.formatError) {
4492                                 waitCursor(false);
4493                              QMessageBox.information(this, tr("Error"),
4494                                                 tr("NixNote had issues formatting this note." +
4495                                                 " To protect your data this note is being marked as read-only."));      
4496                              waitCursor(true);
4497                         }
4498                         readOnly = formatter.readOnly;
4499                         inkNote = formatter.inkNote;
4500                         if (readOnly)
4501                                 readOnlyCache.put(guid, true);
4502                         if (inkNote)
4503                                 inkNoteCache.put(guid, true);
4504                 } else {
4505                         logger.log(logger.HIGH, "Note content is being pulled from the cache");
4506                         String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4507                         js = new QByteArray(cachedContent);
4508                         browser.setContent(js);
4509                         if (readOnlyCache.containsKey(guid))
4510                                         readOnly = true;
4511                         if (inkNoteCache.containsKey(guid))
4512                                         inkNote = true;
4513                 }
4514                 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4515                         thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4516                 }
4517                 if (readOnly || inkNote || 
4518                                 (note.getAttributes() != null && note.getAttributes().getContentClass() != null && note.getAttributes().getContentClass() != ""))
4519                         browser.getBrowser().page().setContentEditable(false);  // We don't allow editing of ink notes
4520                 else
4521                         browser.getBrowser().page().setContentEditable(true);
4522                 browser.setReadOnly(readOnly);
4523                 deleteButton.setEnabled(!readOnly);
4524                 tagButton.setEnabled(!readOnly);
4525                 menuBar.noteDelete.setEnabled(!readOnly);
4526                 menuBar.noteTags.setEnabled(!readOnly);
4527                 browser.setNote(note);
4528                 
4529                 if (note != null && note.getNotebookGuid() != null && 
4530                                 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4531                         deleteButton.setEnabled(false);
4532                         menuBar.notebookDeleteAction.setEnabled(false);
4533                 } else {
4534                         deleteButton.setEnabled(true);
4535                         menuBar.notebookDeleteAction.setEnabled(true);
4536                 }
4537                 
4538                 // Build a list of non-closed notebooks
4539                 List<Notebook> nbooks = new ArrayList<Notebook>();
4540                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4541                         boolean found=false;
4542                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4543                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) 
4544                                         found = true;
4545                         }
4546                         if (!found)
4547                                 nbooks.add(listManager.getNotebookIndex().get(i));
4548                 }
4549                 
4550                 browser.setTitle(note.getTitle());
4551                 browser.setTag(getTagNamesForNote(note));
4552                 browser.setAuthor(note.getAttributes().getAuthor());
4553
4554                 browser.setAltered(note.getUpdated());
4555                 browser.setCreation(note.getCreated());
4556                 if (note.getAttributes().getSubjectDate() > 0)
4557                         browser.setSubjectDate(note.getAttributes().getSubjectDate());
4558                 else
4559                         browser.setSubjectDate(note.getCreated());
4560                 browser.setUrl(note.getAttributes().getSourceURL());
4561                 
4562                 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4563                 List<Tag> tagList = tagFilter.getValidTags(note);
4564                 browser.setAllTags(tagList);
4565                 
4566                 browser.setCurrentTags(note.getTagNames());
4567                 noteDirty = false;
4568                 scrollToGuid(guid);
4569                 
4570                 browser.loadingData(false);
4571                 if (thumbnailViewer.isActiveWindow())
4572                         thumbnailView();
4573                 
4574                 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4575                 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4576
4577                 waitCursor(false);
4578                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4579         }
4580         // Save a generated thumbnail
4581         private void toggleNoteInformation() {
4582                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4583         browserWindow.toggleInformation();
4584         menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4585         Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4586         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4587     }
4588         // Listener triggered when a print button is pressed
4589     @SuppressWarnings("unused")
4590         private void printNote() {
4591                 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4592
4593         QPrintDialog dialog = new QPrintDialog();
4594         if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4595                 QPrinter printer = dialog.printer();
4596                 browserWindow.getBrowser().print(printer);
4597         }
4598                 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4599
4600     }
4601     // Listener triggered when the email button is pressed
4602     @SuppressWarnings("unused")
4603         private void emailNote() {
4604         logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4605         
4606         if (Desktop.isDesktopSupported()) {
4607             Desktop desktop = Desktop.getDesktop();
4608             
4609             String text2 = browserWindow.getContentsToEmail();
4610             QUrl url = new QUrl("mailto:");
4611             url.addQueryItem("subject", currentNote.getTitle());
4612 //            url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4613             url.addQueryItem("body", text2);
4614             QDesktopServices.openUrl(url);
4615         }
4616 /*            
4617             
4618             if (desktop.isSupported(Desktop.Action.MAIL)) {
4619                 URI uriMailTo = null;
4620                 try {
4621                         //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4622                         String text = browserWindow.getContentsToEmail();
4623                         //text = "<b>" +text +"</b>";
4624                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4625                                                         +"&BODY=" +text, null);
4626                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4627                                                         +"&ATTACHMENT=d:/test.pdf", null);
4628                                         desktop.mail(uriMailTo);
4629                                 } catch (URISyntaxException e) {
4630                                         e.printStackTrace();
4631                                 } catch (IOException e) {
4632                                         e.printStackTrace();
4633                                 }
4634
4635             }
4636
4637         }     
4638  */     
4639         logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4640     }
4641         // Reindex all notes
4642     @SuppressWarnings("unused")
4643         private void fullReindex() {
4644         logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4645         indexRunner.addWork("REINDEXALL");
4646         setMessage(tr("Database will be reindexed."));
4647         logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4648     }
4649     // Listener when a user wants to reindex a specific note
4650     @SuppressWarnings("unused")
4651         private void reindexNote() {
4652         logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4653                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4654                         indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4655                 }
4656                 if (selectedNotebookGUIDs.size() > 1)
4657                         setMessage(tr("Notes will be reindexed."));
4658                 else
4659                         setMessage(tr("Note will be reindexed."));
4660         logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4661     }
4662     // Delete the note
4663     @SuppressWarnings("unused")
4664         private void deleteNote() {
4665         logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4666         if (currentNote == null) 
4667                 return;
4668         if (currentNoteGuid.equals(""))
4669                 return;
4670         String title = null;
4671         if (selectedNoteGUIDs.size() == 1)
4672                 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4673
4674         // If we are deleting non-trash notes
4675         if (currentNote.isActive()) { 
4676                 if (Global.verifyDelete()) {
4677                         String msg;
4678                         if (selectedNoteGUIDs.size() > 1) {
4679                                 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4680                         } else {
4681                                 if (title != null)
4682                                         msg = new String(tr("Delete note \"") +title +"\"?");
4683                                 else                            
4684                                         msg = new String(tr("Delete note selected note?"));
4685                         }
4686                         if (QMessageBox.question(this, tr("Confirmation"), msg,
4687                                         QMessageBox.StandardButton.Yes, 
4688                                         QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4689                                         return;
4690                         }
4691                 }
4692                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
4693                         selectedNoteGUIDs.add(currentNoteGuid);
4694                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4695                         listManager.deleteNote(selectedNoteGUIDs.get(i));
4696                 }
4697         } else { 
4698                 // If we are deleting from the trash.
4699                 if (Global.verifyDelete()) {
4700                         String msg;
4701                         if (selectedNoteGUIDs.size() > 1) {
4702                                 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4703                         } else {
4704                                 if (title != null)
4705                                 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4706                                 else
4707                                         msg = new String(tr("Permanently delete note selected note?"));
4708                         }
4709                         if (QMessageBox.question(this, "Confirmation", msg,
4710                                 QMessageBox.StandardButton.Yes, 
4711                                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4712                                         return;
4713                         }
4714                 }
4715                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
4716                         selectedNoteGUIDs.add(currentNoteGuid);
4717                 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4718                         for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4719                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4720                         if (modelIndex != null) {
4721                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4722                                 String tableGuid =  (String)ix.values().toArray()[0];
4723                                 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4724                                         listManager.getNoteTableModel().removeRow(j);
4725                                         j=-1;
4726                                 }
4727                         }
4728                 }
4729                         listManager.expungeNote(selectedNoteGUIDs.get(i));
4730                 }
4731         }
4732         currentNoteGuid = "";
4733         listManager.loadNotesIndex();
4734         noteIndexUpdated(false);
4735         refreshEvernoteNote(true);
4736         scrollToGuid(currentNoteGuid);
4737         logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4738     }
4739     // Add a new note
4740     @SuppressWarnings("unused")
4741         private void addNote() {
4742         logger.log(logger.HIGH, "Inside NeverNote.addNote");
4743 //      browserWindow.setEnabled(true);
4744         browserWindow.setReadOnly(false);
4745         saveNote();
4746         Calendar currentTime = new GregorianCalendar();
4747         StringBuffer noteString = new StringBuffer(100);
4748         noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4749                 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4750                 "<en-note>\n");
4751         
4752         if (Global.overrideDefaultFont()) {
4753                 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4754                 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4755                 noteString.append("<br clear=\"none\" />\n");
4756                 noteString.append("</span>\n</font>\n");
4757         } else
4758                 noteString.append("<br clear=\"none\" />\n");
4759         noteString.append("</en-note>");
4760         
4761         Long l = new Long(currentTime.getTimeInMillis());
4762         String randint = new String(Long.toString(l));          
4763         
4764         // Find a notebook.  We first look for a selected notebook (the "All Notebooks" one doesn't count).  
4765         // Then we look
4766         // for the first non-archived notebook.  Finally, if nothing else we 
4767         // pick the first notebook in the list.
4768         String notebook = null;
4769         listManager.getNotebookIndex().get(0).getGuid();
4770         List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4771         if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks") && !selectedNotebook.get(0).text(2).equalsIgnoreCase("STACK")) {
4772                 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4773                 notebook = currentSelectedNotebook.text(2);
4774         } else {
4775                 boolean found = false;
4776                 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4777                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4778                         boolean match = false;
4779                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4780                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4781                                         match = true;
4782                                         j = listManager.getArchiveNotebookIndex().size();
4783                                 }
4784                         }
4785                         if (!match)
4786                                 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4787                                 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4788                 }
4789                 // Now we have a list of good notebooks, so we can look for the default
4790                 found = false;
4791                 for (int i=0; i<goodNotebooks.size(); i++) {
4792                         if (goodNotebooks.get(i).isDefaultNotebook()) {
4793                                 notebook = goodNotebooks.get(i).getGuid();
4794                                 found = true;
4795                                 i = goodNotebooks.size();
4796                         }
4797                 }
4798                 
4799                 if (goodNotebooks.size() > 0 && !found)
4800                         notebook = goodNotebooks.get(0).getGuid();
4801      
4802                 if (notebook==null)
4803                         notebook = listManager.getNotebookIndex().get(0).getGuid();             
4804         }
4805         
4806         Note newNote = new Note();
4807         newNote.setUpdateSequenceNum(0);
4808         newNote.setGuid(randint);
4809         newNote.setNotebookGuid(notebook);
4810         newNote.setTitle("Untitled Note");
4811         newNote.setContent(noteString.toString());
4812         newNote.setDeleted(0);
4813         newNote.setCreated(System.currentTimeMillis());
4814         newNote.setUpdated(System.currentTimeMillis());
4815         newNote.setActive(true);
4816         NoteAttributes na = new NoteAttributes();
4817         na.setLatitude(0.0);
4818         na.setLongitude(0.0);
4819         na.setAltitude(0.0);
4820         newNote.setAttributes(new NoteAttributes());
4821                 newNote.setTagGuids(new ArrayList<String>());
4822                 newNote.setTagNames(new ArrayList<String>());
4823         
4824         // If new notes are to be created based upon the selected tags, then we need to assign the tags
4825         if (Global.newNoteWithSelectedTags()) { 
4826                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4827                 QTreeWidgetItem currentSelection;
4828                 for (int i=0; i<selections.size(); i++) {
4829                         currentSelection = selections.get(i);
4830                         newNote.getTagGuids().add(currentSelection.text(2));
4831                         newNote.getTagNames().add(currentSelection.text(0));
4832                 }
4833         }
4834         
4835         conn.getNoteTable().addNote(newNote, true);
4836         NoteMetadata metadata = new NoteMetadata();
4837         metadata.setGuid(newNote.getGuid());
4838         metadata.setDirty(true);
4839         listManager.addNote(newNote, metadata);
4840 //      noteTableView.insertRow(newNote, true, -1);
4841         
4842         currentNote = newNote;
4843         currentNoteGuid = currentNote.getGuid();
4844         noteTableView.clearSelection();
4845         refreshEvernoteNote(true);
4846         listManager.countNotebookResults(listManager.getNoteIndex());
4847         browserWindow.titleLabel.setFocus();
4848         browserWindow.titleLabel.selectAll();
4849 //      notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4850         
4851         // If the window is hidden, then we want to popup this in an external window & 
4852         if (!isVisible())
4853                 listDoubleClick();
4854         waitCursor(false);
4855         logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4856     }
4857     // Restore a note from the trash;
4858     @SuppressWarnings("unused")
4859         private void restoreNote() {
4860         waitCursor(true);
4861                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
4862                         selectedNoteGUIDs.add(currentNoteGuid);
4863                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4864                         listManager.restoreNote(selectedNoteGUIDs.get(i));
4865                 }
4866         currentNoteGuid = "";
4867         listManager.loadNotesIndex();
4868         noteIndexUpdated(false);
4869         waitCursor(false);
4870     }
4871     // Search a note for specific txt
4872     @SuppressWarnings("unused")
4873         private void findText() {
4874         find.show();
4875         find.setFocusOnTextField();
4876     }
4877     @SuppressWarnings("unused")
4878         private void doFindText() {
4879         browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4880         find.setFocus();
4881     }
4882     @SuppressWarnings("unused")
4883         private void updateNoteTitle(String guid, String title) {
4884         listManager.setNoteSynchronized(guid, false);
4885         
4886         // We do this manually because if we've edited the note in an 
4887         // external window we run into the possibility of signal recursion
4888         // looping.
4889         if (guid.equals(currentNoteGuid)) {
4890                 browserWindow.titleLabel.blockSignals(true);
4891                 browserWindow.titleLabel.setText(title);
4892                 browserWindow.titleLabel.blockSignals(false);
4893         }
4894     }
4895     // Signal received that note content has changed.  Normally we just need the guid to remove
4896     // it from the cache.
4897     @SuppressWarnings("unused")
4898         private void invalidateNoteCache(String guid, String content) {
4899         noteCache.remove(guid);
4900                 refreshEvernoteNote(true);
4901     }
4902     // Signal received that a note guid has changed
4903     @SuppressWarnings("unused")
4904         private void noteGuidChanged(String oldGuid, String newGuid) {
4905         if (noteCache.containsKey(oldGuid)) {
4906                 if (!oldGuid.equals(currentNoteGuid)) {
4907                         String cache = noteCache.get(oldGuid);
4908                         noteCache.put(newGuid, cache);
4909                         noteCache.remove(oldGuid);
4910                 } else {
4911                         noteCache.remove(oldGuid);
4912                         noteCache.put(newGuid, browserWindow.getContent());
4913                 }
4914         }
4915   
4916         listManager.updateNoteGuid(oldGuid, newGuid, false);
4917         if (currentNoteGuid.equals(oldGuid)) {
4918                 if (currentNote != null)
4919                         currentNote.setGuid(newGuid);
4920                 currentNoteGuid = newGuid;
4921         }
4922                 
4923         if (externalWindows.containsKey(oldGuid)) {
4924                         ExternalBrowse b = externalWindows.get(oldGuid);
4925                         externalWindows.remove(oldGuid);
4926                         b.getBrowserWindow().getNote().setGuid(newGuid);
4927                         externalWindows.put(newGuid, b);
4928                 }
4929
4930         for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4931                 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4932                         noteTableView.proxyModel.addGuid(newGuid, listManager.getNoteMetadata().get(newGuid));
4933                         i=listManager.getNoteIndex().size();
4934                 }
4935         }
4936         
4937         if (listManager.getNoteTableModel().metaData.containsKey(oldGuid)) {
4938                 NoteMetadata meta = listManager.getNoteTableModel().metaData.get(oldGuid);
4939                 listManager.getNoteTableModel().metaData.put(newGuid, meta);
4940                 listManager.getNoteTableModel().metaData.remove(oldGuid);
4941         }
4942         
4943     }
4944     // Toggle the note editor button bar
4945     private void toggleEditorButtonBar() {
4946         if (browserWindow.buttonsVisible) {
4947                 browserWindow.hideButtons();
4948                 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4949 //              Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4950         } else {
4951                 browserWindow.buttonsVisible = true;
4952                 showEditorButtons(browserWindow);
4953         }
4954         Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4955     }
4956     // Show editor buttons
4957     private void showEditorButtons(BrowserWindow browser) {
4958                 browser.buttonLayout.setVisible(true);
4959                 browser.undoAction.setVisible(false);
4960                 
4961                 browser.undoButton.setVisible(false);
4962
4963                 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4964                 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4965                 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4966                 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4967                 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4968                 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4969                 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4970                 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4971                 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4972                 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4973                 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4974                 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4975                 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4976                 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4977                 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4978                 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4979                 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4980                 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4981                 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4982                 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4983                 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4984                 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4985                 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4986     }
4987     private void duplicateNote(String guid) {
4988                 
4989                 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4990                 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4991                 oldNote.setContent(conn.getNoteTable().getNoteContentNoUTFConversion(guid));
4992                 oldNote.setResources(resList);
4993                 duplicateNote(oldNote);
4994         }
4995         private void duplicateNote(Note oldNote) {
4996                 waitCursor(true);
4997                 // Now that we have a good notebook guid, we need to move the conflicting note
4998                 // to the local notebook
4999                 Calendar currentTime = new GregorianCalendar();
5000                 Long l = new Long(currentTime.getTimeInMillis());
5001                 String newGuid = new String(Long.toString(l));
5002                                         
5003 //              Note newNote = oldNote.deepCopy();
5004                 Note newNote = (Note)Global.deepCopy(oldNote);
5005                 newNote.setUpdateSequenceNum(0);
5006                 newNote.setGuid(newGuid);
5007                 newNote.setDeleted(0);
5008                 newNote.setActive(true);
5009                 
5010                 /*
5011                 List<String> tagNames = new ArrayList<String>();
5012                 List<String> tagGuids = new ArrayList<String>();;
5013                 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
5014                         tagNames.add(oldNote.getTagNames().get(i));
5015                         tagGuids.add(oldNote.getTagGuids().get(i));
5016                 }
5017
5018                 // Sort note Tags to make them look nice
5019                 for (int i=0; i<tagNames.size()-1; i++) {
5020                         if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
5021                                 String n1 = tagNames.get(i);
5022                                 String n2 = tagNames.get(i+1);
5023                                 tagNames.set(i, n2);
5024                                 tagNames.set(i+1, n1);
5025                         }
5026                 }
5027                 newNote.setTagGuids(tagGuids);
5028                 newNote.setTagNames(tagNames);
5029                 
5030                 // Add tag guids to note
5031                 */
5032                 
5033                 // Duplicate resources
5034                 List<Resource> resList = oldNote.getResources();
5035                 if (resList == null)
5036                         resList = new ArrayList<Resource>();
5037                 long prevGuid = 0;
5038                 for (int i=0; i<resList.size(); i++) {
5039                         l = prevGuid;
5040                         while (l == prevGuid) {
5041                                 currentTime = new GregorianCalendar();
5042                                 l = new Long(currentTime.getTimeInMillis());
5043                         }
5044                         prevGuid = l;
5045                         String newResGuid = new String(Long.toString(l));
5046                         resList.get(i).setNoteGuid(newGuid);
5047                         resList.get(i).setGuid(newResGuid);
5048                         resList.get(i).setUpdateSequenceNum(0);
5049                         resList.get(i).setActive(true);
5050                         conn.getNoteTable().noteResourceTable.saveNoteResource(
5051                                         (Resource)Global.deepCopy(resList.get(i)), true);
5052                 }
5053                 newNote.setResources(resList);
5054                 
5055                 // Add note to the database
5056                 conn.getNoteTable().addNote(newNote, true);
5057                 NoteMetadata metaData = new NoteMetadata();
5058                 NoteMetadata oldMeta = listManager.getNoteMetadata().get(oldNote.getGuid());
5059                 metaData.copy(oldMeta);
5060                 metaData.setGuid(newNote.getGuid());
5061                 listManager.addNote(newNote, metaData);
5062                 noteTableView.insertRow(newNote, metaData, true, -1);
5063                 currentNoteGuid = newNote.getGuid();
5064                 currentNote = newNote;
5065                 refreshEvernoteNote(true);
5066                 listManager.countNotebookResults(listManager.getNoteIndex());
5067                 waitCursor(false);
5068         }
5069         // View all notes
5070         @SuppressWarnings("unused")
5071         private void allNotes() {
5072                 clearAttributeFilter();
5073                 clearNotebookFilter();
5074                 clearSavedSearchFilter();
5075                 clearTrashFilter();
5076                 clearTagFilter();
5077                 searchField.clear();
5078                 if (Global.mimicEvernoteInterface) {
5079                         notebookTree.selectGuid("");
5080                 }
5081                 notebookTreeSelection();
5082                 refreshEvernoteNote(true);
5083         }
5084         // Merge notes
5085         @SuppressWarnings("unused")
5086         private void mergeNotes() {
5087                 logger.log(logger.HIGH, "Merging notes");
5088                 waitCursor(true);
5089                 saveNote();
5090                 String masterGuid = null;
5091                 List<String> sources = new ArrayList<String>();
5092                 QModelIndex index;
5093                 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
5094                         int r = noteTableView.selectionModel().selectedRows().get(i).row();
5095                         index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
5096                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5097                 if (i == 0) 
5098                         masterGuid = (String)ix.values().toArray()[0];
5099                 else 
5100                         sources.add((String)ix.values().toArray()[0]);  
5101                 }
5102                 
5103                 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
5104                 logger.log(logger.EXTREME, "Children count: "+sources.size());
5105                 mergeNoteContents(masterGuid, sources);
5106                 currentNoteGuid = masterGuid;
5107                 noteIndexUpdated(false);
5108                 refreshEvernoteNote(true);
5109                 waitCursor(false);
5110         }
5111         private void mergeNoteContents(String targetGuid, List<String> sources) {
5112                 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
5113                 String newContent = target.getContent();
5114                 newContent = newContent.replace("</en-note>", "<br></br>");
5115                 
5116                 for (int i=0; i<sources.size(); i++) {
5117                         Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
5118                         if (source.isSetTitle()) {
5119                                 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
5120                         }
5121                         String sourceContent = source.getContent();
5122                         logger.log(logger.EXTREME, "Merging contents into note");
5123                         logger.log(logger.EXTREME, sourceContent);
5124                         logger.log(logger.EXTREME, "End of content");
5125                         int startOfNote = sourceContent.indexOf("<en-note>");
5126                         sourceContent = sourceContent.substring(startOfNote+9);
5127                         int endOfNote = sourceContent.indexOf("</en-note>");
5128                         sourceContent = sourceContent.substring(0,endOfNote);
5129                         newContent = newContent + sourceContent;
5130                         logger.log(logger.EXTREME, "New note content");
5131                         logger.log(logger.EXTREME, newContent);
5132                         logger.log(logger.EXTREME, "End of content");
5133                         for (int j=0; j<source.getResourcesSize(); j++) {
5134                                 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
5135                                 Resource r = source.getResources().get(j);
5136                                 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
5137                                 
5138                                 Calendar currentTime = new GregorianCalendar();
5139                                 Long l = new Long(currentTime.getTimeInMillis());
5140                                                         
5141                                 long prevGuid = 0;
5142                                 l = prevGuid;
5143                                 while (l == prevGuid) {
5144                                         currentTime = new GregorianCalendar();
5145                                         l = new Long(currentTime.getTimeInMillis());
5146                                 }
5147                                 String newResGuid = new String(Long.toString(l));
5148                                 newRes.setNoteGuid(targetGuid);
5149                                 newRes.setGuid(newResGuid);
5150                                 newRes.setUpdateSequenceNum(0);
5151                                 newRes.setActive(true);
5152                                 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5153                         }
5154                 }
5155                 logger.log(logger.EXTREME, "Updating note");
5156                 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5157                 for (int i=0; i<sources.size(); i++) {
5158                         logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5159                         listManager.deleteNote(sources.get(i));
5160                 }
5161                 logger.log(logger.EXTREME, "Exiting merge note");
5162         }
5163         // A resource within a note has had a guid change 
5164         @SuppressWarnings("unused")
5165         private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5166                 if (oldGuid != null && !oldGuid.equals(newGuid))
5167                         Global.resourceMap.put(oldGuid, newGuid);
5168         }
5169         // View a thumbnail of the note
5170         public void thumbnailView() {
5171                 
5172                 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5173                 QFile thumbnail = new QFile(thumbnailName);
5174                 if (!thumbnail.exists()) {
5175                         
5176                         QImage img = new QImage();
5177                         img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5178                         thumbnailViewer.setThumbnail(img);
5179                 } else
5180                         thumbnailViewer.setThumbnail(thumbnailName);
5181                 if (!thumbnailViewer.isVisible()) 
5182                         thumbnailViewer.showFullScreen();
5183         }
5184         // An error happened while saving a note.  Inform the user
5185         @SuppressWarnings("unused")
5186         private void saveRunnerError(String guid, String msg) {
5187                 if (msg == null) {
5188                         String title = "*Unknown*";
5189                         for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5190                                 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5191                                         title = listManager.getMasterNoteIndex().get(i).getTitle();
5192                                         i=listManager.getMasterNoteIndex().size();
5193                                 }
5194                         }
5195                         msg = tr("An error has happened while saving the note \"") +title+
5196                         tr("\".\n\nThis is probably due to a document that is too complex for NixNote to process.  "+
5197                         "As a result, changes to the note may not be saved properly in the database."+
5198                         "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5199                         "\nbe lost.  Please review the note to recover any critical data before restarting.");
5200                         
5201                         QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5202                 }
5203         }
5204         private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5205                 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5206                 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5207                 // Find an idle preview object
5208                 for (int i=0; i<thumbGenerators.size(); i++) {
5209                         if (thumbGenerators.get(i).mutex.tryLock()) {
5210                                 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5211                                 thumbGenerators.get(i).loadContent(guid, html, zoom);
5212                                 return;
5213                         }
5214                 } 
5215                 if (thumbGenerators.size() >= 1) {
5216                         logger.log(logger.EXTREME, "No available thumbnail generators.  Aborting " +guid);
5217                         return;
5218                 }
5219                 
5220                 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5221                 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5222                 thumbGenerators.add(preview);
5223
5224                 if (preview.mutex.tryLock()) {
5225                         logger.log(logger.EXTREME, "Loading thumbnail for  " +guid);
5226                         preview.loadContent(guid, html, zoom);
5227                 }
5228                 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5229         }
5230         
5231         
5232         
5233         //**********************************************************
5234     //**********************************************************
5235     //* Online user actions
5236     //**********************************************************
5237     //**********************************************************
5238     private void setupOnlineMenu() {
5239         if (!Global.isConnected) {
5240                 menuBar.noteOnlineHistoryAction.setEnabled(false);
5241                 menuBar.selectiveSyncAction.setEnabled(false);
5242                 return;
5243         } else {
5244                 menuBar.noteOnlineHistoryAction.setEnabled(true);
5245                 menuBar.selectiveSyncAction.setEnabled(true);
5246         }
5247     }
5248     @SuppressWarnings("unused")
5249         private void viewNoteHistory() {
5250         if (currentNoteGuid == null || currentNoteGuid.equals("")) 
5251                 return;
5252         if (currentNote.getUpdateSequenceNum() == 0) {
5253                 setMessage(tr("Note has never been synchronized."));
5254                         QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5255                         return;
5256         }
5257         
5258         setMessage(tr("Getting Note History"));
5259         waitCursor(true);
5260         Note currentOnlineNote = null;
5261         versions = null;
5262         try {
5263                 if (Global.isPremium())
5264                         versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5265                 else
5266                         versions = new ArrayList<NoteVersionId>();
5267                 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5268                 } catch (EDAMUserException e) {
5269                         setMessage("EDAMUserException: " +e.getMessage());
5270                         return;
5271                 } catch (EDAMSystemException e) {
5272                         setMessage("EDAMSystemException: " +e.getMessage());
5273                         return;
5274                 } catch (EDAMNotFoundException e) {
5275                         setMessage(tr("Note not found on server."));
5276                         QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5277                         return;
5278                 } catch (TException e) {
5279                         setMessage("EDAMTransactionException: " +e.getMessage());
5280                         return;
5281                 }
5282                 
5283                 // If we've gotten this far, we have a good note.
5284                 if (historyWindow == null) {
5285                         historyWindow = new OnlineNoteHistory(logger, conn);
5286                         historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5287                         historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5288                         historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5289                 } else {
5290                         historyWindow.historyCombo.clear();
5291                 }
5292                 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5293                 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5294                         isDirty = true;
5295                 historyWindow.setCurrent(isDirty);
5296                 
5297                 loadHistoryWindowContent(currentOnlineNote);
5298                 historyWindow.load(versions);
5299                 setMessage(tr("History retrieved"));
5300                 waitCursor(false);
5301                 historyWindow.exec();
5302     }
5303     private Note reloadHistoryWindow(String selection) {
5304         waitCursor(true);
5305                 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5306                 String dateTimeFormat = new String(fmt);
5307                 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5308                 int index = -1;
5309                 int usn = 0;
5310                 
5311                 for (int i=0; i<versions.size(); i++) {
5312                         StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5313                         if (versionDate.toString().equals(selection))
5314                                 index = i;
5315                 }
5316                 
5317                 if (index > -1 || selection.indexOf("Current") > -1) {
5318                         Note historyNote = null;
5319                         try {
5320                                 if (index > -1) {
5321                                         usn = versions.get(index).getUpdateSequenceNum();
5322                                         historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5323                                 } else
5324                                         historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5325                         } catch (EDAMUserException e) {
5326                                 setMessage("EDAMUserException: " +e.getMessage());
5327                                 waitCursor(false);
5328                                 return null;
5329                         } catch (EDAMSystemException e) {
5330                                 setMessage("EDAMSystemException: " +e.getMessage());
5331                                 waitCursor(false);
5332                                 return null;
5333                         } catch (EDAMNotFoundException e) {
5334                                 setMessage("EDAMNotFoundException: " +e.getMessage());
5335                                 waitCursor(false);
5336                                 return null;
5337                         } catch (TException e) {
5338                                 setMessage("EDAMTransactionException: " +e.getMessage());
5339                                 waitCursor(false);
5340                                 return null;
5341                         }
5342                         
5343                         waitCursor(false);
5344                         if (historyNote != null) 
5345                                 historyWindow.setContent(historyNote);
5346                         return historyNote;
5347                 }
5348                 waitCursor(false);
5349                 return null;
5350     }
5351     private void loadHistoryWindowContent(Note note) {
5352         note.setUpdateSequenceNum(0);
5353                 historyWindow.setContent(note); 
5354     }
5355     @SuppressWarnings("unused")
5356         private void restoreHistoryNoteAsNew() {
5357         setMessage(tr("Restoring as new note."));
5358         duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5359         setMessage(tr("Note has been restored as a new note."));
5360     }
5361     @SuppressWarnings("unused")
5362         private void restoreHistoryNote() {
5363         setMessage(tr("Restoring note."));
5364         Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5365         conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5366         n.setActive(true);
5367         n.setDeleted(0);
5368                 for (int i=0; i<n.getResourcesSize(); i++) {
5369                         n.getResources().get(i).setActive(true);
5370                         conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5371                 }
5372                 NoteMetadata metadata = new NoteMetadata();
5373                 metadata.setGuid(n.getGuid());
5374         listManager.addNote(n, metadata);
5375         conn.getNoteTable().addNote(n, true);
5376         refreshEvernoteNote(true);
5377         setMessage(tr("Note has been restored."));
5378     }
5379     @SuppressWarnings("unused")
5380         private void setupSelectiveSync() {
5381         
5382         // Get a list of valid notebooks
5383         List<Notebook> notebooks = null; 
5384         List<Tag> tags = null;
5385         List<LinkedNotebook> linkedNotebooks = null;
5386         try {
5387                         notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5388                         tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5389                         linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5390                 } catch (EDAMUserException e) {
5391                         setMessage("EDAMUserException: " +e.getMessage());
5392                         return;
5393                 } catch (EDAMSystemException e) {
5394                         setMessage("EDAMSystemException: " +e.getMessage());
5395                         return;
5396                 } catch (TException e) {
5397                         setMessage("EDAMTransactionException: " +e.getMessage());
5398                         return;
5399                 } catch (EDAMNotFoundException e) {
5400                         setMessage("EDAMNotFoundException: " +e.getMessage());
5401                         return;
5402                 }
5403         
5404                 // Split up notebooks into synchronized & non-synchronized
5405         List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5406         List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5407         
5408         for (int i=notebooks.size()-1; i>=0; i--) {
5409                 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5410                         if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5411                                 ignoredBooks.add(notebooks.get(i));
5412                                 j=dbIgnoredNotebooks.size();
5413                         }
5414                 }
5415         }
5416         
5417         // split up tags into synchronized & non-synchronized
5418         List<Tag> ignoredTags = new ArrayList<Tag>();
5419         List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5420         
5421         for (int i=tags.size()-1; i>=0; i--) {
5422                 for (int j=0; j<dbIgnoredTags.size(); j++) {
5423                         if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5424                                 ignoredTags.add(tags.get(i));
5425                                 j=dbIgnoredTags.size();
5426                         }
5427                 }
5428         }
5429         
5430         // split up linked notebooks into synchronized & non-synchronized
5431         List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5432         List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5433         for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5434                 String notebookGuid = linkedNotebooks.get(i).getGuid();
5435                 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5436                         if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5437                                 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5438                                 j=dbIgnoredLinkedNotebooks.size();
5439                         }
5440                 }
5441         }
5442         
5443                 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5444                 ignore.exec();
5445                 if (!ignore.okClicked())
5446                         return;
5447                 
5448                 waitCursor(true);
5449                 
5450                 // Clear out old notebooks & add  the new ones
5451                 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5452                 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5453                         conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5454                 }
5455                 
5456                 List<String> newNotebooks = new ArrayList<String>();
5457                 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5458                         String text = ignore.getIgnoredBookList().takeItem(i).text();
5459                         for (int j=0; j<notebooks.size(); j++) {
5460                                 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5461                                         Notebook n = notebooks.get(j);
5462                                         conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5463                                         j=notebooks.size();
5464                                         newNotebooks.add(n.getGuid());
5465                                 }
5466                         }
5467                 }
5468                 
5469                 // Clear out old tags & add new ones
5470                 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5471                 for (int i=0; i<oldIgnoreTags.size(); i++) {
5472                         conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5473                 }
5474                 
5475                 List<String> newTags = new ArrayList<String>();
5476                 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5477                         String text = ignore.getIgnoredTagList().takeItem(i).text();
5478                         for (int j=0; j<tags.size(); j++) {
5479                                 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5480                                         Tag t = tags.get(j);
5481                                         conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5482                                         newTags.add(t.getGuid());
5483                                         j=tags.size();
5484                                 }
5485                         }
5486                 }
5487                 
5488                 // Clear out old tags & add new ones
5489                 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5490                 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5491                         conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5492                 }
5493                 
5494                 List<String> newLinked = new ArrayList<String>();
5495                 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5496                         String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5497                         for (int j=0; j<linkedNotebooks.size(); j++) {
5498                                 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5499                                         LinkedNotebook t = linkedNotebooks.get(j);
5500                                         conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5501                                         newLinked.add(t.getGuid());
5502                                         j=linkedNotebooks.size();
5503                                 }
5504                         }
5505                 }
5506                 
5507                 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5508                 waitCursor(false);
5509                 refreshLists();
5510     }
5511     
5512     
5513         //**********************************************************
5514         //**********************************************************
5515         //* XML Modifying methods
5516         //**********************************************************
5517         //**********************************************************
5518         // An error has happended fetching a resource.  let the user know
5519         private void resourceErrorMessage() {
5520                 if (inkNote)
5521                         return;
5522                 waitCursor(false);
5523                 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5524                 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5525                 "In a perfect world this wouldn't happen, but it has.\n" +
5526                 "It is embarasing when a program like me, designed to save all your\n"+
5527                 "precious data, has a problem finding data.\n\n" +
5528                 "I guess life isn't fair, but I'll survive.  Somehow...\n\n" +
5529                 "In the mean time, I'm not going to let you make changes to this note.\n" +
5530                 "Don't get angry.  I'm doing it to prevent you from messing up\n"+
5531                 "this note on the Evernote servers.  Sorry."+
5532                 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5533                 inkNote = true;
5534                 browserWindow.setReadOnly(true);
5535                 waitCursor(true);
5536         }
5537
5538         
5539         
5540         
5541         //**********************************************************
5542         //**********************************************************
5543         //* Timer functions
5544         //**********************************************************
5545         //**********************************************************
5546         // We should now do a sync with Evernote
5547         private void syncTimer() {
5548                 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5549                 syncRunner.syncNeeded = true;
5550                 syncRunner.disableUploads = Global.disableUploads;
5551                 syncStart();
5552                 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5553         }
5554         private void syncStart() {
5555                 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5556                 saveNote();
5557                 if (!syncRunning && Global.isConnected) {
5558                         syncRunner.setConnected(true);
5559                         syncRunner.setKeepRunning(Global.keepRunning);
5560                         syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5561                         
5562                         if (syncThreadsReady > 0) {
5563                                 thumbnailRunner.interrupt = true;
5564                                 saveNoteIndexWidth();
5565                                 saveNoteColumnPositions();
5566                                 if (syncRunner.addWork("SYNC")) {
5567                                         syncRunning = true;
5568                                         syncRunner.syncNeeded = true;
5569                                         syncThreadsReady--;
5570                                 }                               
5571                         }
5572                 }
5573                 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5574         }
5575         @SuppressWarnings("unused")
5576         private void syncThreadComplete(Boolean refreshNeeded) {
5577                 setMessage(tr("Finalizing Synchronization"));
5578                 syncThreadsReady++;
5579                 syncRunning = false;
5580                 syncRunner.syncNeeded = false;
5581                 synchronizeAnimationTimer.stop();
5582                 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5583                 saveNote();
5584                 if (currentNote == null) {
5585                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5586                 }
5587                 listManager.refreshNoteMetadata();
5588                 noteIndexUpdated(true);
5589                 noteTableView.selectionModel().blockSignals(true);
5590                 scrollToGuid(currentNoteGuid);
5591                 noteTableView.selectionModel().blockSignals(false);
5592                 refreshEvernoteNote(false);
5593                 scrollToGuid(currentNoteGuid);
5594                 waitCursor(false);
5595                 
5596                 // Check to see if there were any shared notebook errors
5597                 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5598                         String guid = syncRunner.errorSharedNotebooks.get(0);
5599                         String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5600                         String localName = listManager.getNotebookNameByGuid(notebookGuid);
5601                         SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5602                         syncDialog.exec();
5603                         if (syncDialog.okPressed()) {
5604                                 if (syncDialog.doNothing.isChecked()) {
5605                                         syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5606                                         evernoteSync();
5607                                 }
5608                                 if (syncDialog.deleteNotebook.isChecked()) {
5609                                         conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5610                                         conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5611                                         conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5612                                         conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5613                                         evernoteSync();
5614                                 }
5615                                 refreshLists();
5616                                 return;
5617                         }
5618                 }
5619                 
5620                 // Finalize the synchronization
5621                 if (!syncRunner.error)
5622                         setMessage(tr("Synchronization Complete"));
5623                 else
5624                         setMessage(tr("Synchronization completed with errors.  Please check the log for details."));
5625                 logger.log(logger.MEDIUM, "Sync complete.");
5626         }   
5627         public void saveUploadAmount(long t) {
5628                 Global.saveUploadAmount(t);
5629         }
5630         public void saveUserInformation(User user) {
5631                 Global.saveUserInformation(user);
5632         }
5633         public void saveEvernoteUpdateCount(int i) {
5634                 Global.saveEvernoteUpdateCount(i);
5635         }
5636         public void refreshLists() {
5637                 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5638                 updateQuotaBar();
5639                 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5640                 tagIndexUpdated(true);
5641                 notebookIndexUpdated();
5642                 savedSearchIndexUpdated();
5643                 listManager.loadNotesIndex();
5644
5645                 noteTableView.selectionModel().blockSignals(true);
5646         noteIndexUpdated(true);
5647                 noteTableView.selectionModel().blockSignals(false);
5648                 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5649         }
5650
5651         
5652         @SuppressWarnings("unused")
5653         private void authTimer() {
5654         Calendar cal = Calendar.getInstance();
5655                 
5656         // If we are not connected let's get out of here
5657         if (!Global.isConnected)
5658                 return;
5659                 
5660                 // If this is the first time through, then we need to set this
5661  //             if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime) 
5662 //                      syncRunner.authRefreshTime = cal.getTimeInMillis();
5663                 
5664 //              long now = new Date().getTime();
5665 //              if (now > Global.authRefreshTime && Global.isConnected) {
5666                         syncRunner.authRefreshNeeded = true;
5667                         syncStart();
5668 //              }
5669         }
5670         @SuppressWarnings("unused")
5671         private void authRefreshComplete(boolean goodSync) {
5672                 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5673                 Global.isConnected = syncRunner.isConnected;
5674                 if (goodSync) {
5675 //                      authTimer.start((int)syncRunner.authTimeRemaining/4);
5676                         authTimer.start(1000*60*15);
5677                         logger.log(logger.LOW, "Authentication token has been renewed");
5678 //                      setMessage("Authentication token has been renewed.");
5679                 } else {
5680                         authTimer.start(1000*60*5);
5681                         logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5682 //                      setMessage("Authentication token renew has failed - retry in 5 minutes.");
5683                 }
5684                 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5685         }
5686         
5687         
5688         @SuppressWarnings("unused")
5689         private synchronized void indexTimer() {
5690                 logger.log(logger.EXTREME, "Index timer activated.  Sync running="+syncRunning);
5691                 if (syncRunning) 
5692                         return;
5693                 if (!indexDisabled && indexRunner.idle) { 
5694                         thumbnailRunner.interrupt = true;
5695                         indexRunner.addWork("SCAN");
5696                 }
5697                 logger.log(logger.EXTREME, "Leaving NixNote index timer");
5698         }
5699
5700         @SuppressWarnings("unused")
5701         private void indexStarted() {
5702                 setMessage(tr("Indexing notes"));
5703         }
5704         @SuppressWarnings("unused")
5705         private void indexComplete() {
5706                 setMessage(tr("Index complete"));
5707         }
5708         @SuppressWarnings("unused")
5709         private synchronized void toggleNoteIndexing() {
5710                 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5711                 indexDisabled = !indexDisabled;
5712                 if (!indexDisabled)
5713                         setMessage(tr("Indexing is now enabled."));
5714                 else
5715                         setMessage(tr("Indexing is now disabled."));
5716                 menuBar.disableIndexing.setChecked(indexDisabled);
5717         logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5718     }  
5719         
5720         @SuppressWarnings("unused")
5721         private void threadMonitorCheck() {
5722                 int MAX=3;
5723                 
5724                 
5725                 boolean alive;
5726                 alive = listManager.threadCheck(Global.tagCounterThreadId);
5727                 if (!alive) {
5728                         tagDeadCount++;
5729                         if (tagDeadCount > MAX && !disableTagThreadCheck) {
5730                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died.  I recommend "+
5731                                 "checking stopping NixNote, saving the logs for later viewing, and restarting.  Sorry."));
5732                                 disableTagThreadCheck = true;
5733                         }
5734                 } else
5735                         tagDeadCount=0;
5736                 
5737                 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5738                 if (!alive) {
5739                         notebookThreadDeadCount++;
5740                         if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5741                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died.  I recommend "+
5742                                         "checking stopping NixNote, saving the logs for later viewing, and restarting.  Sorry."));
5743                                 disableNotebookThreadCheck=true;
5744                         }
5745                 } else
5746                         notebookThreadDeadCount=0;
5747                 
5748                 alive = listManager.threadCheck(Global.trashCounterThreadId);
5749                 if (!alive) {
5750                         trashDeadCount++;
5751                         if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5752                                 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died.  I recommend "+
5753                                         "checking stopping NixNote, saving the logs for later viewing, and restarting.  Sorry."));
5754                                 disableTrashThreadCheck = true;
5755                         }
5756                 } else
5757                         trashDeadCount = 0;
5758
5759                 alive = listManager.threadCheck(Global.saveThreadId);
5760                 if (!alive) {
5761                         saveThreadDeadCount++;
5762                         if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5763                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died.  I recommend "+
5764                                         "checking stopping NixNote, saving the logs for later viewing, and restarting.  Sorry."));
5765                                 disableSaveThreadCheck = true;
5766                         }
5767                 } else
5768                         saveThreadDeadCount=0;
5769
5770                 if (!syncThread.isAlive()) {
5771                         syncThreadDeadCount++;
5772                         if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5773                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died.  I recommend "+
5774                                         "checking stopping NixNote, saving the logs for later viewing, and restarting.  Sorry."));
5775                                 disableSyncThreadCheck = true;
5776                         }
5777                 } else
5778                         syncThreadDeadCount=0;
5779
5780                 if (!indexThread.isAlive()) {
5781                         indexThreadDeadCount++;
5782                         if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5783                                 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died.  I recommend "+
5784                                         "checking stopping NixNote, saving the logs for later viewing, and restarting.  Sorry."));
5785                                 disableIndexThreadCheck = true;
5786                         }
5787                 } else
5788                         indexThreadDeadCount=0;
5789
5790                 
5791         }
5792
5793         private void thumbnailTimer() {
5794                 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5795                         thumbnailRunner.addWork("SCAN");
5796                 }
5797         }
5798         
5799         //**************************************************
5800         //* Backup & Restore
5801         //**************************************************
5802         @SuppressWarnings("unused")
5803         private void databaseBackup() {
5804                 QFileDialog fd = new QFileDialog(this);
5805                 fd.setFileMode(FileMode.AnyFile);
5806                 fd.setConfirmOverwrite(true);
5807                 fd.setWindowTitle(tr("Backup Database"));
5808                 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5809                 fd.setAcceptMode(AcceptMode.AcceptSave);
5810                 if (saveLastPath == null || saveLastPath.equals(""))
5811                         fd.setDirectory(System.getProperty("user.home"));
5812                 else
5813                         fd.setDirectory(saveLastPath);
5814                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5815                         return;
5816                 }
5817                 
5818                 
5819         waitCursor(true);
5820         saveLastPath = fd.selectedFiles().get(0);
5821         saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5822         setMessage(tr("Backing up database"));
5823         saveNote();
5824 //      conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5825         
5826         ExportData noteWriter = new ExportData(conn, true);
5827         String fileName = fd.selectedFiles().get(0);
5828
5829         if (!fileName.endsWith(".nnex"))
5830                 fileName = fileName +".nnex";
5831         noteWriter.exportData(fileName);
5832         setMessage(tr("Database backup completed."));
5833  
5834
5835         waitCursor(false);
5836         }
5837         @SuppressWarnings("unused")
5838         private void databaseRestore() {
5839                 if (QMessageBox.question(this, tr("Confirmation"),
5840                                 tr("This is used to restore a database from backups.\n" +
5841                                 "It is HIGHLY recommened that this only be used to populate\n" +
5842                                 "an empty database.  Restoring into a database that\n already has data" +
5843                                 " can cause problems.\n\nAre you sure you want to continue?"),
5844                                 QMessageBox.StandardButton.Yes, 
5845                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5846                                         return;
5847                                 }
5848                 
5849                 
5850                 QFileDialog fd = new QFileDialog(this);
5851                 fd.setFileMode(FileMode.ExistingFile);
5852                 fd.setConfirmOverwrite(true);
5853                 fd.setWindowTitle(tr("Restore Database"));
5854                 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5855                 fd.setAcceptMode(AcceptMode.AcceptOpen);
5856                 if (saveLastPath == null || saveLastPath.equals(""))
5857                         fd.setDirectory(System.getProperty("user.home"));
5858                 else
5859                         fd.setDirectory(saveLastPath);
5860                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5861                         return;
5862                 }
5863                 
5864                 
5865                 waitCursor(true);
5866         saveLastPath = fd.selectedFiles().get(0);
5867         saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5868
5869                 setMessage(tr("Restoring database"));
5870         ImportData noteReader = new ImportData(conn, true);
5871         noteReader.importData(fd.selectedFiles().get(0));
5872         
5873         if (noteReader.lastError != 0) {
5874                 setMessage(noteReader.getErrorMessage());
5875                 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5876                 waitCursor(false);
5877                 return;
5878         }
5879         
5880         listManager.loadNoteTitleColors();
5881         refreshLists();
5882         refreshEvernoteNote(true);
5883         setMessage(tr("Database has been restored."));
5884         waitCursor(false);
5885         }
5886         @SuppressWarnings("unused")
5887         private void exportNotes() {
5888                 QFileDialog fd = new QFileDialog(this);
5889                 fd.setFileMode(FileMode.AnyFile);
5890                 fd.setConfirmOverwrite(true);
5891                 fd.setWindowTitle(tr("Backup Database"));
5892                 fd.setFilter(tr("NixNote Export (*.nnex);;All Files (*.*)"));
5893                 fd.setAcceptMode(AcceptMode.AcceptSave);
5894                 fd.setDirectory(System.getProperty("user.home"));
5895                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5896                         return;
5897                 }
5898                 
5899                 
5900         waitCursor(true);
5901         setMessage(tr("Exporting Notes"));
5902         saveNote();
5903         
5904                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
5905                         selectedNoteGUIDs.add(currentNoteGuid);
5906                 
5907         ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5908         String fileName = fd.selectedFiles().get(0);
5909
5910         if (!fileName.endsWith(".nnex"))
5911                 fileName = fileName +".nnex";
5912         noteWriter.exportData(fileName);
5913         setMessage(tr("Export completed."));
5914  
5915
5916         waitCursor(false);
5917                 
5918         }
5919         @SuppressWarnings("unused")
5920         private void importNotes() {
5921                 QFileDialog fd = new QFileDialog(this);
5922                 fd.setFileMode(FileMode.ExistingFile);
5923                 fd.setConfirmOverwrite(true);
5924                 fd.setWindowTitle(tr("Import Notes"));
5925                 fd.setFilter(tr("NixNote Export (*.nnex);;Evernote Export (*.enex);;All Files (*.*)"));
5926                 fd.setAcceptMode(AcceptMode.AcceptOpen);
5927                 if (saveLastPath == null || saveLastPath.equals(""))
5928                         fd.setDirectory(System.getProperty("user.home"));
5929                 else
5930                         fd.setDirectory(saveLastPath);
5931                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5932                         return;
5933                 }
5934                 
5935                 
5936         waitCursor(true);
5937         setMessage(tr("Importing Notes"));
5938         saveNote();
5939         
5940                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
5941                         selectedNoteGUIDs.add(currentNoteGuid);
5942                 
5943         String fileName = fd.selectedFiles().get(0);
5944 //      saveLastPath.substring(0,fileName.lastIndexOf("/"));
5945
5946         if (fileName.endsWith(".nnex")) {
5947                 ImportData noteReader = new ImportData(conn, false);
5948                 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0) 
5949                         noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5950                 else
5951                         noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5952   
5953                 noteReader.importData(fileName);
5954         
5955                 if (noteReader.lastError != 0) {
5956                         setMessage(noteReader.getErrorMessage());
5957                         logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5958                         waitCursor(false);
5959                         return;
5960                 }
5961         } else {
5962                 if (fileName.endsWith(".enex")) {
5963                 ImportEnex noteReader = new ImportEnex(conn, false);
5964                         if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0) 
5965                                 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5966                         else
5967                                 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5968   
5969                         waitCursor(false);
5970                         if (QMessageBox.question(this, tr("Confirmation"), 
5971                                         tr("Create new tags from import?"),
5972                                         QMessageBox.StandardButton.Yes, 
5973                                         QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
5974                                                                 noteReader.createNewTags = true;
5975                         } else
5976                                 noteReader.createNewTags = false;
5977                         waitCursor(true);
5978                         noteReader.importData(fileName);
5979         
5980                         if (noteReader.lastError != 0) {
5981                                 setMessage(noteReader.getErrorMessage());
5982                                 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5983                                 waitCursor(false);
5984                                 return;
5985                         }
5986                 }
5987         }
5988         
5989         listManager.loadNoteTitleColors();
5990         refreshLists();
5991         refreshEvernoteNote(false);
5992         setMessage(tr("Notes have been imported."));
5993         waitCursor(false);
5994         
5995         setMessage(tr("Import completed."));
5996  
5997
5998         waitCursor(false);
5999                 
6000         }
6001         
6002         //**************************************************
6003         //* Duplicate a note 
6004         //**************************************************
6005         @SuppressWarnings("unused")
6006         private void duplicateNote() {
6007                 saveNote();
6008                 duplicateNote(currentNoteGuid);
6009         }
6010
6011         //**************************************************
6012         //* Action from when a user clicks Copy As URL
6013         //**************************************************
6014         @SuppressWarnings("unused")
6015         private void copyAsUrlClicked() {
6016                 QClipboard clipboard = QApplication.clipboard();
6017                 QMimeData mime = new QMimeData();
6018                 String url;
6019                 mime.setText(currentNoteGuid);
6020                 List<QUrl> urls = new ArrayList<QUrl>();
6021                 
6022                 // Start building the URL
6023                 User user = Global.getUserInformation();
6024
6025                 // Check that we have everything we need
6026                 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
6027                         SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
6028                         warning.exec();
6029                         if (!warning.neverSynchronize())
6030                                 return;
6031                         else {
6032                                 Global.setBypassSynchronizationWarning(true);
6033                                 user.setShardId("s0");
6034                                 user.setId(0);
6035                         }       
6036                 }
6037
6038                 
6039                 // Start building a list of URLs based upon the selected notes
6040         noteTableView.showColumn(Global.noteTableGuidPosition);
6041         
6042         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
6043         if (!Global.isColumnVisible("guid"))
6044                 noteTableView.hideColumn(Global.noteTableGuidPosition);
6045
6046                 // Check that the note is either synchronized, or in a local notebook
6047                 for (int i=0; i<selections.size(); i++) {
6048                         QModelIndex index;
6049                         int row = selections.get(i).row();
6050                 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6051                 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6052                 String selectedGuid = (String)ix.values().toArray()[0];
6053                 
6054                 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6055                 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
6056                         QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
6057                                         "new notes to a local notebook."));
6058                         return; 
6059                 }
6060                 }
6061
6062                 // Start building the URLs
6063         for (int i=0; i<selections.size(); i++) {
6064                 QModelIndex index;
6065                         int row = selections.get(i).row();
6066                 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
6067                 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
6068                 String selectedGuid = (String)ix.values().toArray()[0];
6069                 mime.setText(selectedGuid);
6070                 
6071                 String lid;
6072                 String gid;
6073                 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
6074                 if (selectedNote.getUpdateSequenceNum() > 0) {
6075                         gid = selectedGuid;
6076                         lid = selectedGuid;
6077                 } else {
6078                         gid = "00000000-0000-0000-0000-000000000000";
6079                         lid = selectedGuid;
6080                 }
6081                 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
6082                                 +gid+"/"+lid +"/");
6083                 urls.add(new QUrl(url));
6084         }
6085                 mime.setUrls(urls);
6086                 clipboard.setMimeData(mime);
6087         }
6088         
6089         
6090         //**************************************************
6091         //* Folder Imports
6092         //**************************************************
6093         public void setupFolderImports() {
6094                 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
6095                 
6096                 if (importKeepWatcher == null)
6097                         importKeepWatcher = new QFileSystemWatcher();
6098                 if (importDeleteWatcher == null) {
6099                         importDeleteWatcher = new QFileSystemWatcher();
6100                         for (int i=0; i<records.size(); i++) {
6101                                 if (!records.get(i).keep)
6102                                         folderImportDelete(records.get(i).folder); 
6103                         }
6104                 }
6105
6106                                 
6107                 
6108 //              importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
6109                 for (int i=0; i<records.size(); i++) {
6110                         logger.log(logger.LOW, "Adding file monitor: " +records.get(i).folder);
6111                         if (records.get(i).keep) 
6112                                 importKeepWatcher.addPath(records.get(i).folder);
6113                         else
6114                                 importDeleteWatcher.addPath(records.get(i).folder);
6115                 }
6116                 
6117                 logger.log(logger.EXTREME, "List of directories being watched (kept)...");
6118                 List<String> monitorDelete = importKeepWatcher.directories();
6119                 for (int i=0; i<monitorDelete.size(); i++) {
6120                         logger.log(logger.EXTREME, monitorDelete.get(i));
6121                 }
6122                 logger.log(logger.EXTREME, "<end of list>");
6123                 logger.log(logger.EXTREME, "List of directories being watched (delete)...");
6124                 monitorDelete = importDeleteWatcher.directories();
6125                 for (int i=0; i<monitorDelete.size(); i++) {
6126                         logger.log(logger.EXTREME, monitorDelete.get(i));
6127                 }
6128                 logger.log(logger.EXTREME, "<end of list>");
6129                 
6130                 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
6131                 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
6132                 
6133                 // Look at the files already there so we don't import them again if a new file is created
6134                 if (importedFiles == null) {
6135                         importedFiles = new ArrayList<String>();
6136                         for (int j=0; j<records.size(); j++) {
6137                                 QDir dir = new QDir(records.get(j).folder);
6138                                 List<QFileInfo> list = dir.entryInfoList();
6139                                 for (int k=0; k<list.size(); k++) {
6140                                         if (list.get(k).isFile())
6141                                                 importedFiles.add(list.get(k).absoluteFilePath());
6142                                 }
6143                         }
6144                 }
6145         }
6146         
6147         // Menu folderImport action triggered
6148         public void folderImport() {
6149                 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
6150                 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
6151                 dialog.exec();
6152                 if (!dialog.okClicked())
6153                         return;
6154                 
6155                 // We have some sort of update.
6156                 if (importKeepWatcher.directories().size() > 0)
6157                         importKeepWatcher.removePaths(importKeepWatcher.directories());
6158                 if (importDeleteWatcher.directories().size() > 0)
6159                         importDeleteWatcher.removePaths(importDeleteWatcher.directories());
6160                 
6161                 conn.getWatchFolderTable().expungeAll();
6162                 // Start building from the table
6163                 for (int i=0; i<dialog.table.rowCount(); i++) {
6164                         QTableWidgetItem item = dialog.table.item(i, 0);
6165                         String dir = item.text();
6166                         item = dialog.table.item(i, 1);
6167                         String notebook = item.text();
6168                         item = dialog.table.item(i, 2);
6169                         boolean keep;
6170                         if (item.text().equalsIgnoreCase("Keep"))
6171                                 keep = true;
6172                         else
6173                                 keep = false;
6174                         
6175                         String guid = conn.getNotebookTable().findNotebookByName(notebook);
6176                         conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
6177                 }
6178                 setupFolderImports();
6179         }
6180         
6181         
6182         public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
6183                 logger.log(logger.LOW, "Inside folderImportKeep");
6184                 String whichOS = System.getProperty("os.name");
6185                 if (whichOS.contains("Windows")) 
6186                         dirName = dirName.replace('/','\\');
6187                 
6188                 FileImporter importer = new FileImporter(logger, conn);
6189                 
6190                 QDir dir = new QDir(dirName);
6191                 List<QFileInfo> list = dir.entryInfoList();
6192                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6193
6194                 for (int i=0; i<list.size(); i++){
6195                         logger.log(logger.LOW, "File found: " +list.get(i).fileName());
6196                         boolean redundant = false;
6197                         // Check if we've already imported this one or if it existed before
6198                         for (int j=0; j<importedFiles.size(); j++) {
6199                                 logger.log(logger.LOW, "redundant file list: " +list.get(i).absoluteFilePath());
6200                                 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6201                                         redundant = true;
6202                         }
6203                         
6204                         logger.log(logger.LOW, "Checking if redundant: " +redundant);
6205                         if (!redundant) {
6206                                 importer.setFileInfo(list.get(i));
6207                                 importer.setFileName(list.get(i).absoluteFilePath());
6208                         
6209                         
6210                                 logger.log(logger.LOW, "File importing is a file: " +list.get(i).isFile());
6211                                 logger.log(logger.LOW, "File importing is a valid: " +importer.isValidType());
6212                                 if (list.get(i).isFile() && importer.isValidType()) {
6213                         
6214                                         if (!importer.importFile()) {
6215                                                 // If we can't get to the file, it is probably locked.  We'll try again later.
6216                                                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
6217                                                 importFilesKeep.add(list.get(i).absoluteFilePath());
6218                                         } else {
6219
6220                                                 Note newNote = importer.getNote();
6221                                                 newNote.setNotebookGuid(notebook);
6222                                                 newNote.setTitle(dir.at(i));
6223                                                 NoteMetadata metadata = new NoteMetadata();
6224                                                 metadata.setDirty(true);
6225                                                 metadata.setGuid(newNote.getGuid());
6226                                                 listManager.addNote(newNote, metadata);
6227                                                 conn.getNoteTable().addNote(newNote, true);
6228                                                 noteTableView.insertRow(newNote, metadata, true, -1);
6229                                                 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6230                                                 listManager.countNotebookResults(listManager.getNoteIndex());
6231                                                 importedFiles.add(list.get(i).absoluteFilePath());
6232                                         }
6233                                 }
6234                         }
6235                 }
6236         
6237         
6238         }
6239         
6240         public void folderImportDelete(String dirName) {
6241                 logger.log(logger.LOW, "Inside folderImportDelete");
6242                 String whichOS = System.getProperty("os.name");
6243                 if (whichOS.contains("Windows")) 
6244                         dirName = dirName.replace('/','\\');
6245                 
6246                 FileImporter importer = new FileImporter(logger, conn);
6247                 QDir dir = new QDir(dirName);
6248                 List<QFileInfo> list = dir.entryInfoList();
6249                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6250                 
6251                 for (int i=0; i<list.size(); i++){
6252                         logger.log(logger.LOW, "File found: " +list.get(i).fileName());
6253                         importer.setFileInfo(list.get(i));
6254                         importer.setFileName(list.get(i).absoluteFilePath());
6255                         
6256                         logger.log(logger.LOW, "File importing is a file: " +list.get(i).isFile());
6257                         logger.log(logger.LOW, "File importing is a valid: " +importer.isValidType());
6258                         if (list.get(i).isFile() && importer.isValidType()) {
6259                 
6260                                 if (!importer.importFile()) {
6261                                         // If we can't get to the file, it is probably locked.  We'll try again later.
6262                                         logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
6263                                         importFilesKeep.add(list.get(i).absoluteFilePath());
6264                                 } else {
6265                 
6266                                         Note newNote = importer.getNote();
6267                                         newNote.setNotebookGuid(notebook);
6268                                         newNote.setTitle(dir.at(i));
6269                                         NoteMetadata metadata = new NoteMetadata();
6270                                         metadata.setDirty(true);
6271                                         metadata.setGuid(newNote.getGuid());
6272                                         listManager.addNote(newNote, metadata);
6273                                         conn.getNoteTable().addNote(newNote, true);
6274                                         noteTableView.insertRow(newNote, metadata, true, -1);
6275                                         listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6276                                         listManager.countNotebookResults(listManager.getNoteIndex());
6277                                         dir.remove(dir.at(i));
6278                                 }
6279                         }
6280                 }
6281         }
6282         
6283         
6284         //**************************************************
6285         //* External events
6286         //**************************************************
6287         private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6288                 logger.log(logger.HIGH, "Entering exernalFileEdited");
6289
6290                 // Strip URL prefix and base dir path
6291                 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6292                 String name = fileName.replace(dPath, "");
6293                 int pos = name.lastIndexOf('.');
6294                 String guid = name;
6295                 if (pos > -1) {
6296                         guid = guid.substring(0,pos);
6297                 }
6298                 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6299                 if (pos > -1) {
6300                         guid = name.substring(0, pos);
6301                 }
6302                 
6303                 QFile file = new QFile(fileName);
6304         if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6305                 // If we can't get to the file, it is probably locked.  We'll try again later.
6306                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
6307                 externalFiles.add(fileName);
6308                 return;
6309                 }
6310                 QByteArray binData = file.readAll();
6311         file.close();
6312         if (binData.size() == 0) {
6313                 // If we can't get to the file, it is probably locked.  We'll try again later.
6314                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
6315                 externalFiles.add(fileName);
6316                 return;
6317         }
6318         
6319         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6320         if (r==null)
6321                 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6322         if (r == null || r.getData() == null || r.getData().getBody() == null)
6323                 return;
6324         String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6325         MessageDigest md = MessageDigest.getInstance("MD5");
6326                 md.update(binData.toByteArray());
6327                 byte[] hash = md.digest();
6328         String newHash = Global.byteArrayToHexString(hash);
6329         if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6330                 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6331         }
6332         if (externalWindows.containsKey(r.getNoteGuid())) {
6333                 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(), 
6334                                 r.getGuid(), oldHash, newHash);
6335         }
6336         conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6337         Data data = r.getData();
6338         data.setBody(binData.toByteArray());
6339         data.setBodyHash(hash);
6340         logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6341         r.setData(data);
6342         conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6343         
6344         if (r.getNoteGuid().equals(currentNoteGuid)) {
6345                         QWebSettings.setMaximumPagesInCache(0);
6346                         QWebSettings.setObjectCacheCapacities(0, 0, 0);
6347                         refreshEvernoteNote(true);
6348                         browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6349         }
6350         
6351         if (externalWindows.containsKey(r.getNoteGuid())) {
6352                 QWebSettings.setMaximumPagesInCache(0);
6353                         QWebSettings.setObjectCacheCapacities(0, 0, 0);
6354                         externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6355                         
6356         }
6357         
6358                 logger.log(logger.HIGH, "Exiting externalFielEdited");
6359         }
6360         // This is a timer event that tries to save any external files that were edited.  This
6361         // is only needed if we couldn't save a file earlier.
6362         public void externalFileEditedSaver() {
6363                 for (int i=externalFiles.size()-1; i>=0; i--) {
6364                         try {
6365                                 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6366                                 externalFileEdited(externalFiles.get(i));
6367                                 externalFiles.remove(i);
6368                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6369                 }
6370                 for (int i=0; i<importFilesKeep.size(); i++) {
6371                         try {
6372                                 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6373                                 folderImportKeep(importFilesKeep.get(i));
6374                                 importFilesKeep.remove(i);
6375                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6376                 }
6377                 for (int i=0; i<importFilesDelete.size(); i++) {
6378                         logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6379                         folderImportDelete(importFilesDelete.get(i));
6380                         importFilesDelete.remove(i);
6381                 }
6382         }
6383         
6384         
6385         
6386         
6387         // If an attachment on the current note was edited, we need to update the current notes's hash
6388         // Update a note content's hash.  This happens if a resource is edited outside of NN
6389         public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6390                 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6391                 int endPos;
6392                 for (;position>-1;) {
6393                         endPos = browser.getContent().indexOf(">", position+1);
6394                         String oldSegment = browser.getContent().substring(position,endPos);
6395                         int hashPos = oldSegment.indexOf("hash=\"");
6396                         int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6397                         String hash = oldSegment.substring(hashPos+6, hashEnd);
6398                         if (hash.equalsIgnoreCase(oldHash)) {
6399                                 String newSegment = oldSegment.replace(oldHash, newHash);
6400                                 String content = browser.getContent().substring(0,position) +
6401                                                  newSegment +
6402                                                  browser.getContent().substring(endPos);
6403                                 browser.setContent(new QByteArray(content));;
6404                         }
6405                         
6406                         position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6407                 }
6408         }
6409
6410
6411         //*************************************************
6412         //* Minimize to tray
6413         //*************************************************
6414         @Override
6415         public void changeEvent(QEvent e) {
6416                 if (e.type() == QEvent.Type.WindowStateChange) {
6417                         if (QSystemTrayIcon.isSystemTrayAvailable()) {
6418                                 if (isMinimized() && (Global.showTrayIcon() || Global.showTrayIcon())) {
6419                                         e.accept();
6420                                         QTimer.singleShot(10, this, "hide()");
6421                                         return;
6422                                 }
6423                                 if (isMaximized())
6424                                         windowMaximized = true;
6425                                 else 
6426                                         windowMaximized = false;
6427                         }
6428                 }
6429         }
6430         
6431         //*************************************************
6432         //* Check database userid & passwords
6433         //*************************************************
6434         private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6435                         Connection connection;
6436                         
6437                         try {
6438                                 Class.forName("org.h2.Driver");
6439                         } catch (ClassNotFoundException e1) {
6440                                 e1.printStackTrace();
6441                                 System.exit(16);
6442                         }
6443
6444                         try {
6445                                 String passwordString = null;
6446                                 if (cypherPassword==null || cypherPassword.trim().equals(""))
6447                                         passwordString = userPassword;
6448                                 else
6449                                         passwordString = cypherPassword+" "+userPassword;
6450                                 connection = DriverManager.getConnection(url,userid,passwordString);
6451                         } catch (SQLException e) {
6452                                 return false;
6453                         }
6454                         try {
6455                                 connection.close();
6456                         } catch (SQLException e) {
6457                                 e.printStackTrace();
6458                         }
6459                         return true;
6460         }
6461
6462         //*************************************************
6463         //* View / Hide source HTML for a note
6464         //*************************************************
6465         public void viewSource() {
6466                 browserWindow.showSource(menuBar.viewSource.isChecked());
6467         }
6468         //*************************************************
6469         // Block the program.  This is used for things  
6470         // like async web calls.
6471         //*************************************************
6472         @SuppressWarnings("unused")
6473         private void blockApplication(BrowserWindow b) {
6474                 // Block all signals
6475                 waitCursor(true);
6476                 blockSignals(true);
6477                 
6478                 blockTimer = new QTimer();
6479                 blockTimer.setSingleShot(true);
6480                 blockTimer.setInterval(15000);
6481                 blockTimer.timeout.connect(this, "unblockApplication()");
6482                 blockingWindow  = b;
6483                 blockTimer.start();
6484         }
6485         
6486         @SuppressWarnings("unused")
6487         private void unblockApplication() {
6488                 waitCursor(false);
6489                 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6490                         QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6491                         blockingWindow.unblockTime = -1;
6492                         blockingWindow.awaitingHttpResponse = false;
6493                 }
6494                 blockingWindow = null;
6495                 blockSignals(false);
6496         }
6497 }