OSDN Git Service

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