OSDN Git Service

53c403569d02c9b41fedd69c8a1115a53e965fe4
[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.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
26 import java.sql.Connection;
27 import java.sql.DriverManager;
28 import java.sql.SQLException;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Calendar;
32 import java.util.Collections;
33 import java.util.Comparator;
34 import java.util.Date;
35 import java.util.GregorianCalendar;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.SortedMap;
39 import java.util.Vector;
40
41 import org.apache.thrift.TException;
42
43 import com.evernote.edam.error.EDAMNotFoundException;
44 import com.evernote.edam.error.EDAMSystemException;
45 import com.evernote.edam.error.EDAMUserException;
46 import com.evernote.edam.notestore.NoteFilter;
47 import com.evernote.edam.notestore.NoteVersionId;
48 import com.evernote.edam.type.Data;
49 import com.evernote.edam.type.Note;
50 import com.evernote.edam.type.NoteAttributes;
51 import com.evernote.edam.type.Notebook;
52 import com.evernote.edam.type.QueryFormat;
53 import com.evernote.edam.type.Resource;
54 import com.evernote.edam.type.SavedSearch;
55 import com.evernote.edam.type.Tag;
56 import com.evernote.edam.type.User;
57 import com.trolltech.qt.QThread;
58 import com.trolltech.qt.core.QByteArray;
59 import com.trolltech.qt.core.QDataStream;
60 import com.trolltech.qt.core.QDateTime;
61 import com.trolltech.qt.core.QDir;
62 import com.trolltech.qt.core.QFile;
63 import com.trolltech.qt.core.QFileInfo;
64 import com.trolltech.qt.core.QFileSystemWatcher;
65 import com.trolltech.qt.core.QIODevice;
66 import com.trolltech.qt.core.QModelIndex;
67 import com.trolltech.qt.core.QSize;
68 import com.trolltech.qt.core.QTemporaryFile;
69 import com.trolltech.qt.core.QTextCodec;
70 import com.trolltech.qt.core.QThreadPool;
71 import com.trolltech.qt.core.QTimer;
72 import com.trolltech.qt.core.QUrl;
73 import com.trolltech.qt.core.Qt;
74 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
75 import com.trolltech.qt.core.Qt.SortOrder;
76 import com.trolltech.qt.core.Qt.WidgetAttribute;
77 import com.trolltech.qt.gui.QAbstractItemView;
78 import com.trolltech.qt.gui.QAction;
79 import com.trolltech.qt.gui.QApplication;
80 import com.trolltech.qt.gui.QCloseEvent;
81 import com.trolltech.qt.gui.QColor;
82 import com.trolltech.qt.gui.QComboBox;
83 import com.trolltech.qt.gui.QCursor;
84 import com.trolltech.qt.gui.QDesktopServices;
85 import com.trolltech.qt.gui.QDialog;
86 import com.trolltech.qt.gui.QFileDialog;
87 import com.trolltech.qt.gui.QGridLayout;
88 import com.trolltech.qt.gui.QHBoxLayout;
89 import com.trolltech.qt.gui.QIcon;
90 import com.trolltech.qt.gui.QImage;
91 import com.trolltech.qt.gui.QLabel;
92 import com.trolltech.qt.gui.QListWidget;
93 import com.trolltech.qt.gui.QMainWindow;
94 import com.trolltech.qt.gui.QMenu;
95 import com.trolltech.qt.gui.QMessageBox;
96 import com.trolltech.qt.gui.QPixmap;
97 import com.trolltech.qt.gui.QPrintDialog;
98 import com.trolltech.qt.gui.QPrinter;
99 import com.trolltech.qt.gui.QProgressBar;
100 import com.trolltech.qt.gui.QSizePolicy;
101 import com.trolltech.qt.gui.QSpinBox;
102 import com.trolltech.qt.gui.QSplashScreen;
103 import com.trolltech.qt.gui.QSplitter;
104 import com.trolltech.qt.gui.QStatusBar;
105 import com.trolltech.qt.gui.QSystemTrayIcon;
106 import com.trolltech.qt.gui.QTableWidgetItem;
107 import com.trolltech.qt.gui.QTextEdit;
108 import com.trolltech.qt.gui.QToolBar;
109 import com.trolltech.qt.gui.QTreeWidgetItem;
110 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
111 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
112 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
113 import com.trolltech.qt.gui.QFileDialog.FileMode;
114 import com.trolltech.qt.gui.QMessageBox.StandardButton;
115 import com.trolltech.qt.gui.QSizePolicy.Policy;
116 import com.trolltech.qt.webkit.QWebSettings;
117 import com.trolltech.qt.webkit.QWebPage.WebAction;
118 import com.trolltech.qt.xml.QDomAttr;
119 import com.trolltech.qt.xml.QDomDocument;
120 import com.trolltech.qt.xml.QDomElement;
121 import com.trolltech.qt.xml.QDomNodeList;
122
123 import cx.fbn.nevernote.config.FileManager;
124 import cx.fbn.nevernote.config.InitializationException;
125 import cx.fbn.nevernote.config.StartupConfig;
126 import cx.fbn.nevernote.dialog.AccountDialog;
127 import cx.fbn.nevernote.dialog.ConfigDialog;
128 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
129 import cx.fbn.nevernote.dialog.DatabaseStatus;
130 import cx.fbn.nevernote.dialog.FindDialog;
131 import cx.fbn.nevernote.dialog.LoginDialog;
132 import cx.fbn.nevernote.dialog.NotebookArchive;
133 import cx.fbn.nevernote.dialog.NotebookEdit;
134 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
135 import cx.fbn.nevernote.dialog.SavedSearchEdit;
136 import cx.fbn.nevernote.dialog.TagEdit;
137 import cx.fbn.nevernote.dialog.ThumbnailViewer;
138 import cx.fbn.nevernote.dialog.WatchFolder;
139 import cx.fbn.nevernote.filters.EnSearch;
140 import cx.fbn.nevernote.gui.AttributeTreeWidget;
141 import cx.fbn.nevernote.gui.BrowserWindow;
142 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
143 import cx.fbn.nevernote.gui.MainMenuBar;
144 import cx.fbn.nevernote.gui.NotebookTreeWidget;
145 import cx.fbn.nevernote.gui.PDFPreview;
146 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
147 import cx.fbn.nevernote.gui.TableView;
148 import cx.fbn.nevernote.gui.TagTreeWidget;
149 import cx.fbn.nevernote.gui.Thumbnailer;
150 import cx.fbn.nevernote.gui.TrashTreeWidget;
151 import cx.fbn.nevernote.signals.DBRunnerSignal;
152 import cx.fbn.nevernote.sql.DatabaseConnection;
153 import cx.fbn.nevernote.sql.runners.WatchFolderRecord;
154 import cx.fbn.nevernote.threads.DBRunner;
155 import cx.fbn.nevernote.threads.IndexRunner;
156 import cx.fbn.nevernote.threads.SyncRunner;
157 import cx.fbn.nevernote.utilities.AESEncrypter;
158 import cx.fbn.nevernote.utilities.ApplicationLogger;
159 import cx.fbn.nevernote.utilities.FileImporter;
160 import cx.fbn.nevernote.utilities.FileUtils;
161 import cx.fbn.nevernote.utilities.ListManager;
162 import cx.fbn.nevernote.utilities.SyncTimes;
163 import cx.fbn.nevernote.xml.ExportData;
164 import cx.fbn.nevernote.xml.ImportData;
165 import cx.fbn.nevernote.xml.XMLInsertHilight;
166
167
168 public class NeverNote extends QMainWindow{
169         
170         QStatusBar                              statusBar;                                      // Application status bar
171         
172         DatabaseConnection              conn;
173         
174         MainMenuBar                             menuBar;                                        // Main menu bar
175         FindDialog                              find;                                           // Text search in note dialog
176         List<String>                    emitLog;                                        // Messages displayed in the status bar;
177         QSystemTrayIcon                 trayIcon;                                       // little tray icon
178         QMenu                                   trayMenu;                                       // System tray menu
179         QAction                                 trayExitAction;                         // Exit the application
180         QAction                                 trayShowAction;                         // toggle the show/hide action          
181         QAction                                 trayAddNoteAction;                      // Add a note from the system tray
182         
183     NotebookTreeWidget          notebookTree;                           // List of notebooks
184     AttributeTreeWidget         attributeTree;                          // List of note attributes
185     TagTreeWidget                       tagTree;                                        // list of user created tags
186     SavedSearchTreeWidget       savedSearchTree;                        // list of saved searches
187     TrashTreeWidget                     trashTree;                                      // Trashcan
188     TableView                           noteTableView;                          //      List of notes (the widget).
189
190     public BrowserWindow        browserWindow;                          // Window containing browser & labels
191     QToolBar                            toolBar;                                        // The tool bar under the menu
192 //    QLineEdit                                 searchField;                            // The search filter bar on the toolbar
193     QComboBox                           searchField;                            // search filter bar on the toolbar;
194     boolean                                     searchPerformed = false;        // Search was done?
195     QProgressBar                        quotaBar;                                       // The current quota usage
196     
197     ApplicationLogger           logger;
198     List<String>                        selectedNotebookGUIDs;          // List of notebook GUIDs
199     List<String>                        selectedTagGUIDs;                       // List of selected tag GUIDs
200     List<String>                        selectedNoteGUIDs;                      // List of selected notes
201     String                                      selectedSavedSearchGUID;        // Currently selected saved searches
202     
203     NoteFilter                          filter;                                         // Note filter
204     String                                      currentNoteGuid;                        // GUID of the current note 
205     Note                                        currentNote;                            // The currently viewed note
206     boolean                                     noteDirty;                                      // Has the note been changed?
207     boolean                             inkNote;                    // if this is an ink note, it is read only
208   
209     QThread                                     dbThread;                                       // Thread to handle DB communication
210     ListManager                         listManager;                                    // DB runnable task
211     
212     List<QTemporaryFile>        tempFiles;                                      // Array of temporary files;
213     
214     QTimer                                      indexTimer;                                     // timer to start the index thread
215     IndexRunner                         indexRunner;                            // thread to index notes
216     QThread                                     indexThread;
217     
218     QTimer                                      syncTimer;                                      // Sync on an interval
219     QTimer                                      syncDelayTimer;                         // Sync delay to free up database
220     SyncRunner                          syncRunner;                                     // thread to do a sync.
221     QThread                                     syncThread;
222     QTimer                                      saveTimer;                                      // Timer to save note contents
223     
224     QTimer                                      authTimer;                                      // Refresh authentication
225     QTimer                                      externalFileSaveTimer;          // Save files altered externally
226     List<String>                        externalFiles;                          // External files to save later
227     List<String>                        importFilesKeep;                        // Auto-import files to save later
228     List<String>                        importFilesDelete;                      // Auto-import files to save later
229     
230     int                                         indexTime;                                      // how often to try and index
231     boolean                                     indexRunning;                           // Is indexing running?
232     boolean                                     indexDisabled;                          // Is indexing disabled?
233     
234     int                                         syncThreadsReady;                       // number of sync threads that are free
235     int                                         syncTime;                                       // Sync interval
236     boolean                                     syncRunning;                            // Is sync running?
237     boolean                                     automaticSync;                          // do sync automatically?
238     QTreeWidgetItem                     attributeTreeSelected;
239
240     QAction                             prevButton;                                     // Go to the previous item viewed
241     QAction                             nextButton;                                     // Go to the next item in the history
242     QAction                             downButton;                                     // Go to the next item in the list
243     QAction                             upButton;                                       // Go to the prev. item in the list;
244     QAction                             synchronizeButton;                      // Synchronize with Evernote
245     List<QIcon>                 synchronizeAnimation;           // Synchronize movie
246     QTimer                              synchronizeAnimationTimer;      // Timer to change animation button
247     int                                 synchronizeFrame;                       // Current frame being viewed
248     QAction                     printButton;                            // Print Button
249     QAction                             tagButton;                                      // Tag edit button
250     QAction                             attributeButton;                        // Attribute information button
251     QAction                     emailButton;                            // Email button
252     QAction                     deleteButton;                           // Delete button
253     QAction                             newButton;                                      // new Note Button;
254     QSpinBox                    zoomSpinner;                            // Zoom zoom
255     QAction                             searchClearButton;                      // Clear the search field
256     
257     QSplitter                   mainLeftRightSplitter;          // main splitter for left/right side
258     QSplitter                   leftSplitter1;                          // first left hand splitter
259     QSplitter                   browserIndexSplitter;           // splitter between note index & note text
260     
261     QFileSystemWatcher  importKeepWatcher;                      // Watch & keep auto-import
262     QFileSystemWatcher  importDeleteWatcher;            // Watch & Delete auto-import
263     List<String>                importedFiles;                          // History of imported files (so we don't import twice)
264     
265     OnlineNoteHistory   historyWindow;                          // online history window 
266     List<NoteVersionId> versions;                                       // history versions
267     
268     QTimer                              threadMonitorTimer;                     // Timer to watch threads.
269     int                                 dbThreadDeadCount=0;            // number of consecutive dead times for the db thread
270     int                                 syncThreadDeadCount=0;          // number of consecutive dead times for the sync thread
271     int                                 indexThreadDeadCount=0;         // number of consecutive dead times for the index thread
272     int                                 notebookThreadDeadCount=0;      // number of consecutive dead times for the notebook thread
273     int                                 tagDeadCount=0;                         // number of consecutive dead times for the tag thread
274     int                                 trashDeadCount=0;                       // number of consecutive dead times for the trash thread
275     int                                 saveThreadDeadCount=0;          // number of consecutive dead times for the save thread
276     
277     HashMap<String, String>             noteCache;                      // Cash of note content 
278     List<String>                historyGuids;                           // GUIDs of previously viewed items
279     int                                 historyPosition;                        // Position within the viewed items
280     boolean                             fromHistory;                            // Is this from the history queue?
281     String                              trashNoteGuid;                          // Guid to restore / set into or out of trash to save position
282     Thumbnailer                 preview;                                        // generate preview image
283     ThumbnailViewer             thumbnailViewer;                        // View preview thumbnail; 
284     
285     String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
286         
287         
288     //***************************************************************
289     //***************************************************************
290     //** Constructor & main entry point
291     //***************************************************************
292     //***************************************************************
293     // Application Constructor  
294         public NeverNote()  {
295                                 
296                 if (!lockApplication()) {
297                         System.exit(0);
298                 }
299                 thread().setPriority(Thread.MAX_PRIORITY);
300                 
301                 logger = new ApplicationLogger("nevernote.log");
302                 logger.log(logger.HIGH, tr("Starting Application"));
303                 conn = new DatabaseConnection(logger, Global.mainThreadId);
304                 conn.dbSetup();
305                 
306                 logger.log(logger.EXTREME, tr("Creating index connection"));    
307                 logger.log(logger.EXTREME, tr("Building DB thread"));
308                 Global.dbRunnerSignal = new DBRunnerSignal();
309                 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
310                         boolean goodCheck = false;
311                         while (!goodCheck) {
312                                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
313                                 dialog.exec();
314                                 if (!dialog.okPressed())
315                                         System.exit(0);
316                                 Global.cipherPassword = dialog.getPassword();
317                                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
318                         }
319                 }
320                 Global.dbRunner = new DBRunner(Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
321                 logger.log(logger.EXTREME, tr("Starting DB thread"));
322                 dbThread = new QThread(Global.dbRunner, "Database Thread");
323                 dbThread.start();
324                 logger.log(logger.EXTREME, tr("DB Thread has started"));
325                 Global.dbRunnerSignal.start.emit();
326                 logger.log(logger.EXTREME, tr("Setting main thread DB connection"));
327                 logger.log(logger.EXTREME, tr("main DB thread setup complete."));
328                 conn.checkDatabaseVersion();
329                 
330                 // Start building the invalid XML tables
331                 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
332                 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
333                 
334                 for (int i=0; i<elements.size(); i++) {
335                         Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
336                 }
337                 
338                 logger.log(logger.EXTREME, tr("Starting GUI build"));
339                 Global.originalPalette = QApplication.palette();
340                 QApplication.setStyle(Global.getStyle());
341                 if (Global.useStandardPalette())
342                         QApplication.setPalette(QApplication.style().standardPalette());
343         setWindowTitle("NeverNote");
344         
345         mainLeftRightSplitter = new QSplitter();
346         setCentralWidget(mainLeftRightSplitter);
347         leftSplitter1 = new QSplitter();
348         leftSplitter1.setOrientation(Qt.Orientation.Vertical);
349                 
350         browserIndexSplitter = new QSplitter();
351         browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
352         
353         //* Setup threads & thread timers
354         int indexRunnerCount = Global.getIndexThreads();
355         indexRunnerCount = 1;
356         QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5);     // increase max thread count
357
358                 logger.log(logger.EXTREME, tr("Building list manager"));
359         listManager = new ListManager(conn, logger, Global.mainThreadId);
360         
361                 logger.log(logger.EXTREME, tr("Building index runners & timers"));
362         indexRunner = new IndexRunner("indexRunner.log");
363                 indexThread = new QThread(indexRunner, "Index Thread");
364                 indexThread.start();
365                 
366         synchronizeAnimationTimer = new QTimer();
367         synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
368         
369                 indexTimer = new QTimer();
370                 indexTime = 1000*60*5;     // look for unindexed every 5 minutes
371 //              indexTime = 1000*5;
372                 indexTimer.start(indexTime);  // Start indexing timer
373                 indexTimer.timeout.connect(this, "indexTimer()");
374                 indexDisabled = false;
375                 indexRunning = false;
376                                 
377                 logger.log(logger.EXTREME, tr("Setting sync thread & timers"));
378                 syncThreadsReady=1;
379                 syncRunner = new SyncRunner("syncRunner.log");
380                 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
381                 syncTimer = new QTimer();
382                 syncTimer.timeout.connect(this, "syncTimer()");
383         syncRunner.status.message.connect(this, "setMessage(String)");
384         syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
385         syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
386         syncRunning = false;    
387                 if (syncTime > 0) {
388                         automaticSync = true;
389                         syncTimer.start(syncTime*60*1000);
390                 } else {
391                         automaticSync = false;
392                         syncTimer.stop();
393                 }
394                 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
395                 syncThread = new QThread(syncRunner, "Synchronization Thread");
396                 syncThread.start();
397                 
398                 
399                 logger.log(logger.EXTREME, tr("Starting authentication timer"));
400                 authTimer = new QTimer();
401                 authTimer.timeout.connect(this, "authTimer()");
402                 authTimer.start(1000*60*15);
403                 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
404                 
405                 logger.log(logger.EXTREME, tr("Setting save note timer"));
406                 saveTimer = new QTimer();
407                 saveTimer.timeout.connect(this, "saveNote()");
408                 if (Global.getAutoSaveInterval() > 0) {
409                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval()); 
410 //                      saveTimer.setInterval(1000*10); // auto save every 20 seconds;
411                         saveTimer.start();
412                 }
413                 
414 //              Global.trace();
415                 logger.log(logger.EXTREME, tr("Starting external file monitor timer"));
416                 externalFileSaveTimer = new QTimer();
417                 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
418                 externalFileSaveTimer.setInterval(1000*5);   // save every 5 seconds;
419                 externalFiles = new ArrayList<String>();
420                 importFilesDelete = new ArrayList<String>();
421                 importFilesKeep = new ArrayList<String>();
422                 externalFileSaveTimer.start();
423                 
424         notebookTree = new NotebookTreeWidget();
425         attributeTree = new AttributeTreeWidget();
426         tagTree = new TagTreeWidget(conn);
427         savedSearchTree = new SavedSearchTreeWidget();
428         trashTree = new TrashTreeWidget();
429         noteTableView = new TableView(logger);
430         
431         QGridLayout leftGrid = new QGridLayout();
432         leftSplitter1.setLayout(leftGrid);
433         leftGrid.addWidget(notebookTree, 1, 1);
434         leftGrid.addWidget(tagTree,2,1);
435         leftGrid.addWidget(attributeTree,3,1);
436         leftGrid.addWidget(savedSearchTree,4,1);
437         leftGrid.addWidget(trashTree, 5, 1);
438         
439         // Setup the browser window
440         noteCache = new HashMap<String,String>();
441         browserWindow = new BrowserWindow(conn);
442
443         browserIndexSplitter.addWidget(noteTableView);
444         browserIndexSplitter.addWidget(browserWindow);
445         
446         mainLeftRightSplitter.addWidget(leftSplitter1);
447         mainLeftRightSplitter.addWidget(browserIndexSplitter);
448
449         searchField = new QComboBox();
450         searchField.setEditable(true);
451         searchField.activatedIndex.connect(this, "searchFieldChanged()");
452         searchField.setDuplicatesEnabled(false);
453         searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
454         
455         quotaBar = new QProgressBar();
456         
457         // Setup the thumbnail viewer
458         thumbnailViewer = new ThumbnailViewer();
459         thumbnailViewer.upArrow.connect(this, "upAction()");
460         thumbnailViewer.downArrow.connect(this, "downAction()");
461         thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
462         thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
463
464         listManager.loadNotesIndex();
465         initializeNotebookTree();
466         initializeTagTree();
467         initializeSavedSearchTree();
468         attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
469         attributeTreeSelected = null;
470         initializeNoteTable();    
471
472                 selectedNoteGUIDs = new ArrayList<String>();
473                 statusBar = new QStatusBar();
474                 setStatusBar(statusBar);
475                 menuBar = new MainMenuBar(this);
476                 emitLog = new ArrayList<String>();
477                 
478                 tagTree.setDeleteAction(menuBar.tagDeleteAction);
479                 tagTree.setEditAction(menuBar.tagEditAction);
480                 tagTree.setAddAction(menuBar.tagAddAction);
481                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
482                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
483                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
484                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
485         
486                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
487                 notebookTree.setEditAction(menuBar.notebookEditAction);
488                 notebookTree.setAddAction(menuBar.notebookAddAction);
489                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
490                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
491                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
492
493                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
494                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
495                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
496                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
497                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
498                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
499                         
500                 noteTableView.setAddAction(menuBar.noteAdd);
501                 noteTableView.setDeleteAction(menuBar.noteDelete);
502                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
503                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
504                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
505                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
506                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
507                 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
508                 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
509                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
510                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
511                 trashTree.load();
512         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
513                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
514                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
515                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
516                 trashTree.updateCounts(listManager.getTrashCount());
517
518                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
519                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
520
521                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
522                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
523                 
524                 if (!Global.isWindowVisible("editorButtonBar"))
525                         toggleEditorButtonBar();
526                 if (!Global.isWindowVisible("leftPanel"))
527                         menuBar.hideLeftSide.setChecked(true);
528                 
529                 setMenuBar(menuBar);
530                 setupToolBar();
531                 find = new FindDialog();
532                 find.getOkButton().clicked.connect(this, "doFindText()");
533                 
534                 // Setup the tray icon menu bar
535                 trayShowAction = new QAction("Show/Hide", this);
536                 trayExitAction = new QAction("Exit", this);
537                 trayAddNoteAction = new QAction("Add Note", this);
538                 
539                 trayExitAction.triggered.connect(this, "close()");
540                 trayAddNoteAction.triggered.connect(this, "addNote()");
541                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
542                 
543                 trayMenu = new QMenu(this);
544                 trayMenu.addAction(trayAddNoteAction);
545                 trayMenu.addAction(trayShowAction);
546                 trayMenu.addAction(trayExitAction);
547                 
548                 
549                 trayIcon = new QSystemTrayIcon(this);
550                 trayIcon.setToolTip("NeverNote");
551                 trayIcon.setContextMenu(trayMenu);
552                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
553
554                 currentNoteGuid="";
555                 currentNoteGuid = Global.getLastViewedNoteGuid();
556         historyGuids = new ArrayList<String>();
557         historyPosition = 0;
558         fromHistory = false;
559                 noteDirty = false;
560                 if (!currentNoteGuid.trim().equals("")) {
561                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
562                 }
563                 
564                 noteIndexUpdated(true);
565                 showColumns();
566                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
567                 if (menuBar.showEditorBar.isChecked())
568                 showEditorButtons();
569                 tagIndexUpdated(true);
570                 savedSearchIndexUpdated();
571                 notebookIndexUpdated();
572                 updateQuotaBar();
573         setupSyncSignalListeners();        
574         setupBrowserSignalListeners();
575         setupIndexListeners();
576               
577         
578         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
579         tagTree.showAllTags(true);
580
581                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
582         setWindowIcon(appIcon);
583         trayIcon.setIcon(appIcon);
584         if (Global.showTrayIcon())
585                 trayIcon.show();
586         else
587                 trayIcon.hide();
588         
589         scrollToGuid(currentNoteGuid);
590         if (Global.automaticLogin()) {
591                 remoteConnect();
592                 if (Global.isConnected)
593                         syncTimer();
594         }
595         setupFolderImports();
596         
597         loadStyleSheet();
598         restoreWindowState();
599         
600         if (Global.mimicEvernoteInterface) {
601                 notebookTree.selectGuid("");
602         }
603         
604         threadMonitorTimer = new QTimer();
605         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
606         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
607         
608         historyGuids.add(currentNoteGuid);
609         historyPosition = 1;
610         
611         int sortCol = Global.getSortColumn();
612                 int sortOrder = Global.getSortOrder();
613                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
614         }
615
616         
617         // Main entry point
618         public static void main(String[] args) {
619                 QApplication.initialize(args);
620                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
621                 QSplashScreen splash = new QSplashScreen(pixmap);
622
623                 try {
624                     initializeGlobalSettings(args);
625                 } catch (InitializationException e) {
626                         QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
627                         return;
628                 }
629
630                 boolean showSplash = Global.isWindowVisible("SplashScreen");
631                 if (showSplash) 
632                         splash.show();
633                 NeverNote application = new NeverNote();
634                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
635                 if (Global.wasWindowMaximized())
636                         application.showMaximized();
637                 else
638                         application.show();
639                 if (showSplash)
640                         splash.finish(application);
641                 QApplication.exec();
642                 System.out.println("Goodbye.");
643                 QApplication.exit();
644         }
645
646         private static void initializeGlobalSettings(String[] args) throws InitializationException {
647                 StartupConfig startupConfig = new StartupConfig();
648
649                 for (String arg : args) {
650                         String lower = arg.toLowerCase();
651                         if (lower.startsWith("--name="))
652                                 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
653                         if (lower.startsWith("--home="))
654                                 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
655                         if (lower.startsWith("--disable-viewing"))
656                                 startupConfig.setDisableViewing(true);
657                 }
658
659                 Global.setup(startupConfig);
660         }
661
662     // Exit point
663         @Override
664         public void closeEvent(QCloseEvent event) {     
665                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
666                 waitCursor(true);
667                 
668                 if (currentNote!= null & browserWindow!=null) {
669                         if (!currentNote.getTitle().equals(browserWindow.getTitle()))
670                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
671                 }
672                 saveNote();
673                 setMessage("Beginning shutdown.");
674
675                 externalFileEditedSaver();
676                 if (Global.isConnected && Global.synchronizeOnClose()) {
677                         setMessage("Performing synchronization before closing.");
678                         syncRunner.addWork("SYNC");
679                 }
680                 setMessage("Closing Program.");
681                 threadMonitorTimer.stop();
682
683                 syncRunner.addWork("STOP");
684                 indexRunner.addWork("STOP");
685                 saveNote();
686                 listManager.stop();
687                 saveWindowState();
688
689                 if (tempFiles != null)
690                         tempFiles.clear();
691
692                 browserWindow.noteSignal.tagsChanged.disconnect();
693                 browserWindow.noteSignal.titleChanged.disconnect();
694                 browserWindow.noteSignal.noteChanged.disconnect();
695                 browserWindow.noteSignal.notebookChanged.disconnect();
696                 browserWindow.noteSignal.createdDateChanged.disconnect();
697                 browserWindow.noteSignal.alteredDateChanged.disconnect();
698                 syncRunner.searchSignal.listChanged.disconnect();
699                 syncRunner.tagSignal.listChanged.disconnect();
700         syncRunner.notebookSignal.listChanged.disconnect();
701         syncRunner.noteIndexSignal.listChanged.disconnect();
702
703
704                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
705                 Global.setColumnPosition("noteTableCreationPosition", position);
706                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
707                 Global.setColumnPosition("noteTableTagPosition", position);
708                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
709                 Global.setColumnPosition("noteTableNotebookPosition", position);
710                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
711                 Global.setColumnPosition("noteTableChangedPosition", position);
712                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
713                 Global.setColumnPosition("noteTableAuthorPosition", position);
714                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
715                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
716                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
717                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
718                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
719                 Global.setColumnPosition("noteTableTitlePosition", position);
720                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
721                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
722                 
723                 saveNoteIndexWidth();
724                 
725                 int width = notebookTree.columnWidth(0);
726                 Global.setColumnWidth("notebookTreeName", width);
727                 width = tagTree.columnWidth(0);
728                 Global.setColumnWidth("tagTreeName", width);
729                 
730                 Global.saveWindowMaximized(isMaximized());
731                 Global.saveCurrentNoteGuid(currentNoteGuid);
732                         
733                 int sortCol = noteTableView.proxyModel.sortColumn();
734                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
735                 Global.setSortColumn(sortCol);
736                 Global.setSortOrder(sortOrder);
737                 
738                 hide();
739                 trayIcon.hide();
740                 Global.keepRunning = false;
741                 try {
742                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
743                         indexRunner.thread().join(50);
744                         logger.log(logger.MEDIUM, "Index thread has stopped");
745                 } catch (InterruptedException e1) {
746                         e1.printStackTrace();
747                 }
748                 if (!syncRunner.isIdle()) {
749                         try {
750                                 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
751                                 syncThread.join();
752                                 logger.log(logger.MEDIUM, "Sync thread has stopped");
753                         } catch (InterruptedException e1) {
754                                 e1.printStackTrace();
755                         }
756                 }
757
758                 logger.log(logger.EXTREME, "Shutting down database");
759                 conn.dbShutdown();
760                 logger.log(logger.EXTREME, "Waiting for DB thread to terminate");
761                 try {
762                         dbThread.join();
763                 } catch (InterruptedException e) {
764                         e.printStackTrace();
765                 }
766                 logger.log(logger.EXTREME, "DB Thread has terminated");
767                 unlockApplication();
768                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
769         }
770
771         public void setMessage(String s) {
772                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
773                 logger.log(logger.HIGH, "Message: " +s);
774                 statusBar.showMessage(s);
775                 emitLog.add(s);
776                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
777         }
778                 
779         private void waitCursor(boolean wait) {
780                 if (wait)
781                         QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
782                 else
783                         QApplication.restoreOverrideCursor();
784         }
785         
786         private void setupIndexListeners() {
787                 indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
788                 indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
789 //                      indexRunner.threadSignal.indexNeeded.connect(listManager, "setIndexNeeded(String, String, Boolean)");
790         }
791         private void setupSyncSignalListeners() {
792                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
793         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
794         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
795         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
796         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
797         
798 //              syncRunner.syncSignal.setSequenceDate.connect(this,"setSequenceDate(long)");
799                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
800 //              syncRunner.syncSignal.setUpdateSequenceNumber.connect(this,"setUpdateSequenceNumber(int)");
801                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
802                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
803                 
804                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
805                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
806                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
807                 
808                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
809         }
810         
811         private void setupBrowserSignalListeners() {
812                 
813                 browserWindow.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
814                 browserWindow.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
815             browserWindow.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
816                 browserWindow.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
817             browserWindow.noteSignal.noteChanged.connect(this, "setNoteDirty()");
818             browserWindow.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
819             browserWindow.noteSignal.titleChanged.connect(this, "updateListTitle(String, String)");
820             browserWindow.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
821             browserWindow.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
822             browserWindow.noteSignal.createdDateChanged.connect(this, "updateListDateCreated(String, QDateTime)");
823             browserWindow.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
824             browserWindow.noteSignal.alteredDateChanged.connect(this, "updateListDateChanged(String, QDateTime)");
825             browserWindow.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
826             browserWindow.noteSignal.subjectDateChanged.connect(this, "updateListDateSubject(String, QDateTime)");
827             browserWindow.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
828             browserWindow.noteSignal.authorChanged.connect(this, "updateListAuthor(String, String)");
829             browserWindow.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
830             browserWindow.noteSignal.sourceUrlChanged.connect(this, "updateListSourceUrl(String, String)");
831             browserWindow.focusLost.connect(this, "saveNote()");
832             browserWindow.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
833 //          browserWindow.resourceSignal.externalFileEdit.connect(this, "saveResourceLater(String, String)");
834         }
835         private boolean lockApplication() {
836                                 
837                 // NFC TODO: who creates this - H2? should it be parameterized with databaseName like in RDatabaseConnection? 
838                 String fileName = Global.getFileManager().getDbDirPath("NeverNote.lock.db");
839 //              QFile.remove(fileName);
840                 if (QFile.exists(fileName)) {
841                         QMessageBox.question(this, "Lock File Detected",
842                                         "While starting I've found a database lock file.\n" +
843                                         "to prevent multiple instances from accessing the database \n"+
844                                         "at the same time.  Please stop any other program, or (if you\n" +
845                                         "are sure nothing else is using the database) remove the file\n" +
846                                         fileName +".");
847                         return false;
848                         
849                 }
850                 return true;
851 /*              String fileName = Global.currentDir +"nevernote.lock";
852
853                 
854                 if (QFile.exists(fileName)) {
855                         if (QMessageBox.question(this, "Confirmation",
856                                 "While starting I've found a lock file.  This file is used to prevent multiple "+
857                                 "instances of this program running at once.  If NeverNote has crashed this " +
858                                 "is just a file that wasn't cleaned up and you can safely, "+
859                                 "continue, but if there is another instance of this running you are " +
860                                 "running the risk of creating problems.\n\n" +
861                                 "Are you sure you want to continue?",
862                                 QMessageBox.StandardButton.Yes, 
863                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
864                                         return false;
865                                 }
866                 }
867                 
868                 QFile file = new QFile(fileName);
869                 file.open(OpenModeFlag.WriteOnly);
870                 file.write(new QByteArray("This file is used to prevent multiple instances " +
871                                 "of NeverNote running more than once.  " +
872                                 "It should be deleted when NeverNote ends"));
873                 file.close();
874                 return true;
875 */
876         }
877         private void unlockApplication() {
878                 // NFC TODO: should this be removed? Looks like H2 now handles the locking, which it will clean up itself. See #lockApplication.
879                 String fileName = Global.getFileManager().getHomeDirPath("nevernote.lock");
880                 if (QFile.exists(fileName)) {
881                         QFile.remove(fileName);
882                 }
883         }
884         
885
886         //***************************************************************
887         //***************************************************************
888         //* Settings and look & feel
889         //***************************************************************
890         //***************************************************************
891         @SuppressWarnings("unused")
892         private void settings() {
893                 logger.log(logger.HIGH, "Entering NeverNote.settings");
894         ConfigDialog settings = new ConfigDialog(this);
895         String dateFormat = Global.getDateFormat();
896         String timeFormat = Global.getTimeFormat();
897         
898         settings.exec();
899         if (Global.showTrayIcon())
900                 trayIcon.show();
901         else
902                 trayIcon.hide();
903         showColumns();
904         if (menuBar.showEditorBar.isChecked())
905                 showEditorButtons();
906         
907         // Reset the save timer
908         if (Global.getAutoSaveInterval() > 0)
909                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
910         else
911                 saveTimer.stop();
912         
913         // This is a hack to force a reload of the index in case the date or time changed.
914 //        if (!dateFormat.equals(Global.getDateFormat()) ||
915 //                      !timeFormat.equals(Global.getTimeFormat())) {
916                 noteCache.clear();
917                 noteIndexUpdated(true);
918 //        }
919         
920         logger.log(logger.HIGH, "Leaving NeverNote.settings");
921         }
922         // Restore things to the way they were
923         private void restoreWindowState() {
924                 // We need to name things or this doesn't work.
925                 setObjectName("NeverNote");
926                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
927                 browserIndexSplitter.setObjectName("browserIndexSplitter");
928                 leftSplitter1.setObjectName("leftSplitter1");   
929                 
930                 // Restore the actual positions.
931                 restoreGeometry(Global.restoreGeometry(objectName()));
932         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
933         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
934         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
935        
936         }
937         // Save window positions for the next start
938         private void saveWindowState() {
939                 Global.saveGeometry(objectName(), saveGeometry());
940                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
941                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
942                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
943         }    
944         // Load the style sheet
945         private void loadStyleSheet() {
946                 String fileName = Global.getFileManager().getQssDirPath("default.qss");
947                 QFile file = new QFile(fileName);
948                 file.open(OpenModeFlag.ReadOnly);
949                 String styleSheet = file.readAll().toString();
950                 file.close();
951                 setStyleSheet(styleSheet);
952         }
953         // Save column widths for the next time
954         private void saveNoteIndexWidth() {
955                 int width;
956         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
957         Global.setColumnWidth("noteTableCreationPosition", width);
958                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
959                 Global.setColumnWidth("noteTableChangedPosition", width);
960                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
961                 Global.setColumnWidth("noteTableGuidPosition", width);
962                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
963                 Global.setColumnWidth("noteTableNotebookPosition", width);
964                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
965                 Global.setColumnWidth("noteTableTagPosition", width);
966                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
967                 Global.setColumnWidth("noteTableTitlePosition", width);
968                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
969                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
970                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
971                 Global.setColumnWidth("noteTableAuthorPosition", width);
972                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
973                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
974                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
975                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
976         }
977         
978         
979     //***************************************************************
980     //***************************************************************
981     //** These functions deal with Notebook menu items
982     //***************************************************************
983     //***************************************************************
984     // Setup the tree containing the user's notebooks.
985     private void initializeNotebookTree() {       
986         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
987         notebookTree.itemSelectionChanged.connect(this, "notebookTreeSelection()");
988         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
989  //     notebookTree.resize(Global.getSize("notebookTree"));
990         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
991     }   
992     // Listener when a notebook is selected
993     @SuppressWarnings("unused")
994         private void notebookTreeSelection() {
995                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
996
997                 clearTrashFilter();
998                 clearAttributeFilter();
999                 clearSavedSearchFilter();
1000                 if (Global.mimicEvernoteInterface) {
1001                         clearTagFilter();
1002                         searchField.clear();
1003                 }
1004                 
1005                 menuBar.noteRestoreAction.setVisible(false);            
1006         menuBar.notebookEditAction.setEnabled(true);
1007         menuBar.notebookDeleteAction.setEnabled(true);
1008         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1009         QTreeWidgetItem currentSelection;
1010         selectedNotebookGUIDs.clear();
1011         if (!Global.mimicEvernoteInterface) {
1012                 for (int i=0; i<selections.size(); i++) {
1013                         currentSelection = selections.get(i);
1014                         selectedNotebookGUIDs.add(currentSelection.text(2));
1015                 }
1016         
1017                 
1018                 // There is the potential for no notebooks to be selected if this 
1019                 // happens then we make it look like all notebooks were selecetd.
1020                 // If that happens, just select the "all notebooks"
1021                 selections = notebookTree.selectedItems();
1022                 if (selections.size()==0) {
1023                         selectedNotebookGUIDs.clear();
1024                         menuBar.notebookEditAction.setEnabled(false);
1025                         menuBar.notebookDeleteAction.setEnabled(false);
1026                 }
1027         } else {
1028                 String guid = "";
1029                 if (selections.size() > 0)
1030                         guid = (selections.get(0).text(2));
1031                 if (!guid.equals(""))
1032                         selectedNotebookGUIDs.add(guid);
1033         }
1034         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1035         listManager.loadNotesIndex();
1036         noteIndexUpdated(false);
1037                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1038
1039     }
1040     private void clearNotebookFilter() {
1041         notebookTree.blockSignals(true);
1042         notebookTree.clearSelection();
1043                 menuBar.noteRestoreAction.setVisible(false);
1044         menuBar.notebookEditAction.setEnabled(false);
1045         menuBar.notebookDeleteAction.setEnabled(false);
1046         selectedNotebookGUIDs.clear();
1047         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1048         notebookTree.blockSignals(false);
1049     }
1050         // Triggered when the notebook DB has been updated
1051         private void notebookIndexUpdated() {
1052                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1053                 if (selectedNotebookGUIDs == null)
1054                         selectedNotebookGUIDs = new ArrayList<String>();
1055                 List<Notebook> books = conn.getNotebookTable().getAll();
1056                 for (int i=books.size()-1; i>=0; i--) {
1057                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1058                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1059                                         books.remove(i);
1060                                         j=listManager.getArchiveNotebookIndex().size();
1061                                 }
1062                         }
1063                 }
1064                 
1065                 
1066                 listManager.countNotebookResults(listManager.getNoteIndex());
1067                 notebookTree.blockSignals(true);
1068         notebookTree.load(books, listManager.getLocalNotebooks());
1069         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1070                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1071                 if (!found)
1072                         selectedNotebookGUIDs.remove(i);
1073         }
1074         notebookTree.blockSignals(false);
1075         
1076                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1077     }
1078     // Show/Hide note information
1079         private void toggleNotebookWindow() {
1080                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1081         if (notebookTree.isVisible())
1082                 notebookTree.hide();
1083         else
1084                 notebookTree.show();
1085         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1086         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1087         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1088     }   
1089         // Add a new notebook
1090         @SuppressWarnings("unused")
1091         private void addNotebook() {
1092                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1093                 NotebookEdit edit = new NotebookEdit();
1094                 edit.setNotebooks(listManager.getNotebookIndex());
1095                 edit.exec();
1096         
1097                 if (!edit.okPressed())
1098                         return;
1099         
1100                 Calendar currentTime = new GregorianCalendar();
1101                 Long l = new Long(currentTime.getTimeInMillis());
1102                 String randint = new String(Long.toString(l));
1103         
1104                 Notebook newBook = new Notebook();
1105                 newBook.setUpdateSequenceNum(0);
1106                 newBook.setGuid(randint);
1107                 newBook.setName(edit.getNotebook());
1108                 newBook.setServiceCreated(new Date().getTime());
1109                 newBook.setServiceUpdated(new Date().getTime());
1110                 newBook.setDefaultNotebook(false);
1111                 newBook.setPublished(false);
1112                 
1113                 listManager.getNotebookIndex().add(newBook);
1114                 if (edit.isLocal())
1115                         listManager.getLocalNotebooks().add(newBook.getGuid());
1116                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1117                 notebookIndexUpdated();
1118                 listManager.countNotebookResults(listManager.getNoteIndex());
1119 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1120                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1121         }
1122         // Edit an existing notebook
1123         @SuppressWarnings("unused")
1124         private void editNotebook() {
1125                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1126                 NotebookEdit edit = new NotebookEdit();
1127                 edit.setTitle("Edit Notebook");
1128                 edit.setLocalCheckboxEnabled(false);
1129                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1130                 QTreeWidgetItem currentSelection;
1131                 currentSelection = selections.get(0);
1132                 edit.setNotebook(currentSelection.text(0));
1133                 edit.setNotebooks(listManager.getNotebookIndex());
1134                 edit.exec();
1135         
1136                 if (!edit.okPressed())
1137                         return;
1138         
1139                 String guid = currentSelection.text(2);
1140                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1141                 currentSelection.setText(0, edit.getNotebook());
1142                 
1143                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1144                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1145                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1146                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1147                                 i=listManager.getNotebookIndex().size();
1148                         }
1149                 }
1150                 
1151                 // Build a list of non-closed notebooks
1152                 List<Notebook> nbooks = new ArrayList<Notebook>();
1153                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1154                         boolean found=false;
1155                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1156                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1157                                         found = true;
1158                         }
1159                         if (!found)
1160                                 nbooks.add(listManager.getNotebookIndex().get(i));
1161                 }
1162                 
1163                 browserWindow.setNotebookList(nbooks);
1164                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1165         }
1166         // Delete an existing notebook
1167         @SuppressWarnings("unused")
1168         private void deleteNotebook() {
1169                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1170                 boolean assigned = false;
1171                 // Check if any notes have this notebook
1172                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1173         for (int i=0; i<selections.size(); i++) {
1174                 QTreeWidgetItem currentSelection;
1175                 currentSelection = selections.get(i);
1176                 String guid = currentSelection.text(2);
1177                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1178                         String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1179                         if (noteGuid.equals(guid)) {
1180                                 assigned = true;
1181                                 j=listManager.getNoteIndex().size();
1182                                 i=selections.size();
1183                         }
1184                 }
1185         }
1186                 if (assigned) {
1187                         QMessageBox.information(this, "Unable to Delete", "Some of the selected notebook(s) contain notes.\n"+
1188                                         "Please delete the notes or move them to another notebook before deleting any notebooks.");
1189                         return;
1190                 }
1191                 
1192                 if (conn.getNotebookTable().getAll().size() == 1) {
1193                         QMessageBox.information(this, "Unable to Delete", "You must have at least one notebook.");
1194                         return;
1195                 }
1196         
1197         // If all notebooks are clear, verify the delete
1198                 if (QMessageBox.question(this, "Confirmation", "Delete the selected notebooks?",
1199                         QMessageBox.StandardButton.Yes, 
1200                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1201                         return;
1202                 }
1203                 
1204                 // If confirmed, delete the notebook
1205         for (int i=selections.size()-1; i>=0; i--) {
1206                 QTreeWidgetItem currentSelection;
1207                 currentSelection = selections.get(i);
1208                 String guid = currentSelection.text(2);
1209                 conn.getNotebookTable().expungeNotebook(guid, true);
1210                 listManager.deleteNotebook(guid);
1211         }
1212 //        for (int i=<dbRunner.getLocalNotebooks().size()-1; i>=0; i--) {
1213  //             if (dbRunner.getLocalNotebooks().get(i).equals(arg0))
1214  //       }
1215         notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1216         listManager.countNotebookResults(listManager.getNoteIndex());
1217 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1218         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1219         }
1220         // A note's notebook has been updated
1221         @SuppressWarnings("unused")
1222         private void updateNoteNotebook(String guid, String notebookGuid) {
1223                 
1224                 // Update the list manager
1225                 listManager.updateNoteNotebook(guid, notebookGuid);
1226                 listManager.countNotebookResults(listManager.getNoteIndex());
1227 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1228                 
1229                 // Find the name of the notebook
1230                 String notebookName = null;
1231                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1232                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1233                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1234                                 i=listManager.getNotebookIndex().size();
1235                         }
1236                 }
1237                 
1238                 // If we found the name, update the browser window
1239                 if (notebookName != null) {
1240                         updateListNoteNotebook(guid, notebookName);
1241                         if (guid.equals(currentNoteGuid)) {
1242                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1243                                 if (pos >=0)
1244                                         browserWindow.notebookBox.setCurrentIndex(pos);
1245                         }
1246                 }
1247                 
1248                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1249                 if (guid.equals(currentNoteGuid)) {
1250                         if (currentNote != null) {
1251                                 currentNote.setNotebookGuid(notebookGuid);
1252                         }
1253                 }
1254         }
1255         // Open/close notebooks
1256         @SuppressWarnings("unused")
1257         private void closeNotebooks() {
1258                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1259                 na.exec();
1260                 if (!na.okClicked())
1261                         return;
1262                 
1263                 waitCursor(true);
1264                 listManager.getArchiveNotebookIndex().clear();
1265                 
1266                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1267                         String text = na.getClosedBookList().takeItem(i).text();
1268                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1269                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1270                                         Notebook n = listManager.getNotebookIndex().get(j);
1271                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1272                                         listManager.getArchiveNotebookIndex().add(n);
1273                                         j=listManager.getNotebookIndex().size();
1274                                 }
1275                         }
1276                 }
1277                 
1278                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1279                         String text = na.getOpenBookList().takeItem(i).text();
1280                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1281                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1282                                         Notebook n = listManager.getNotebookIndex().get(j);
1283                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1284                                         j=listManager.getNotebookIndex().size();
1285                                 }
1286                         }
1287                 }
1288                 
1289                 listManager.loadNotesIndex();
1290                 notebookIndexUpdated();
1291                 noteIndexUpdated(true);
1292 //              noteIndexUpdated(false);
1293                 
1294                 // Build a list of non-closed notebooks
1295                 List<Notebook> nbooks = new ArrayList<Notebook>();
1296                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1297                         boolean found=false;
1298                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1299                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1300                                         found = true;
1301                         }
1302                         if (!found)
1303                                 nbooks.add(listManager.getNotebookIndex().get(i));
1304                 }
1305                 waitCursor(false);
1306                 browserWindow.setNotebookList(nbooks);
1307         }
1308
1309         
1310         
1311         
1312         
1313     //***************************************************************
1314     //***************************************************************
1315     //** These functions deal with Tag menu items
1316     //***************************************************************
1317     //***************************************************************
1318         // Add a new notebook
1319         @SuppressWarnings("unused")
1320         private void addTag() {
1321                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1322                 TagEdit edit = new TagEdit();
1323                 edit.setTagList(listManager.getTagIndex());
1324                 edit.exec();
1325         
1326                 if (!edit.okPressed())
1327                         return;
1328         
1329                 Calendar currentTime = new GregorianCalendar();
1330                 Long l = new Long(currentTime.getTimeInMillis());
1331                 String randint = new String(Long.toString(l));
1332         
1333                 Tag newTag = new Tag();
1334                 newTag.setUpdateSequenceNum(0);
1335                 newTag.setGuid(randint);
1336                 newTag.setName(edit.getTag());
1337                 conn.getTagTable().addTag(newTag, true);
1338                 listManager.getTagIndex().add(newTag);
1339                 reloadTagTree();
1340                 
1341                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1342         }
1343         private void reloadTagTree() {
1344                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1345                 tagIndexUpdated(false);
1346                 boolean filter = false;
1347                 listManager.countTagResults(listManager.getNoteIndex());
1348                 if (notebookTree.selectedItems().size() > 0 
1349                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1350                                                   filter = true;
1351                 if (tagTree.selectedItems().size() > 0)
1352                         filter = true;
1353                 tagTree.showAllTags(!filter);
1354                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1355         }
1356         // Edit an existing tag
1357         @SuppressWarnings("unused")
1358         private void editTag() {
1359                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1360                 TagEdit edit = new TagEdit();
1361                 edit.setTitle("Edit Tag");
1362                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1363                 QTreeWidgetItem currentSelection;
1364                 currentSelection = selections.get(0);
1365                 edit.setTag(currentSelection.text(0));
1366                 edit.setTagList(listManager.getTagIndex());
1367                 edit.exec();
1368         
1369                 if (!edit.okPressed())
1370                         return;
1371         
1372                 String guid = currentSelection.text(2);
1373                 currentSelection.setText(0,edit.getTag());
1374                 
1375                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1376                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1377                                 listManager.getTagIndex().get(i).setName(edit.getTag());
1378                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1379                                 updateListTagName(guid);
1380                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1381                                         browserWindow.setTag(getTagNamesForNote(currentNote));
1382                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1383                                 return;
1384                         }
1385                 }
1386                 browserWindow.setTag(getTagNamesForNote(currentNote));
1387                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1388         }
1389         // Delete an existing tag
1390         @SuppressWarnings("unused")
1391         private void deleteTag() {
1392                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1393                 
1394                 if (QMessageBox.question(this, "Confirmation", "Delete the selected tags?",
1395                         QMessageBox.StandardButton.Yes, 
1396                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1397                                                         return;
1398                 }
1399                 
1400                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1401         for (int i=selections.size()-1; i>=0; i--) {
1402                 QTreeWidgetItem currentSelection;
1403                 currentSelection = selections.get(i);                   
1404                 removeTagItem(currentSelection.text(2));
1405         }
1406         tagIndexUpdated(true);
1407         listManager.countTagResults(listManager.getNoteIndex());
1408 //              tagTree.updateCounts(listManager.getTagCounter());
1409         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1410         }
1411         // Remove a tag tree item.  Go recursively down & remove the children too
1412         private void removeTagItem(String guid) {
1413         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
1414                 String parent = listManager.getTagIndex().get(j).getParentGuid();
1415                 if (parent != null && parent.equals(guid)) {            
1416                         //Remove this tag's children
1417                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
1418                 }
1419         }
1420         //Now, remove this tag
1421         removeListTagName(guid);
1422         conn.getTagTable().expungeTag(guid, true);                      
1423         for (int a=0; a<listManager.getTagIndex().size(); a++) {
1424                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1425                         listManager.getTagIndex().remove(a);
1426                         return;
1427                 }
1428         }
1429         }
1430         // Setup the tree containing the user's tags
1431     private void initializeTagTree() {
1432         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1433         tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1434         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1435         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1436     }
1437     // Listener when a tag is selected
1438     @SuppressWarnings("unused")
1439         private void tagTreeSelection() {
1440         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1441         
1442         List<QTreeWidgetItem> x = tagTree.selectedItems();
1443         for (int i=0; i<x.size(); i++) {
1444         }
1445         
1446         clearTrashFilter();
1447         clearAttributeFilter();
1448         clearSavedSearchFilter();
1449         
1450                 menuBar.noteRestoreAction.setVisible(false);
1451                 
1452         List<QTreeWidgetItem> selections = tagTree.selectedItems();
1453         QTreeWidgetItem currentSelection;
1454         selectedTagGUIDs.clear();
1455         for (int i=0; i<selections.size(); i++) {
1456                 currentSelection = selections.get(i);
1457                 selectedTagGUIDs.add(currentSelection.text(2));
1458         }
1459         if (selections.size() > 0) {
1460                 menuBar.tagEditAction.setEnabled(true);
1461                 menuBar.tagDeleteAction.setEnabled(true);
1462         }
1463         else {
1464                 menuBar.tagEditAction.setEnabled(false);
1465                 menuBar.tagDeleteAction.setEnabled(false);
1466         }
1467         listManager.setSelectedTags(selectedTagGUIDs);
1468         listManager.loadNotesIndex();
1469         noteIndexUpdated(false);
1470         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1471     }
1472     // trigger the tag index to be refreshed
1473     @SuppressWarnings("unused")
1474         private void tagIndexUpdated() {
1475         tagIndexUpdated(true);
1476     }
1477     private void tagIndexUpdated(boolean reload) {
1478         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1479                 if (selectedTagGUIDs == null)
1480                         selectedTagGUIDs = new ArrayList<String>();
1481 //              selectedTagGUIDs.clear();  // clear out old entries
1482
1483                 tagTree.blockSignals(true);
1484                 if (reload)
1485                         tagTree.load(listManager.getTagIndex());
1486         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1487                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1488                 if (!found)
1489                         selectedTagGUIDs.remove(i);
1490         }
1491         tagTree.blockSignals(false);
1492         
1493                 browserWindow.setTag(getTagNamesForNote(currentNote));
1494         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1495     }   
1496     // Show/Hide note information
1497         private void toggleTagWindow() {
1498                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1499         if (tagTree.isVisible())
1500                 tagTree.hide();
1501         else
1502                 tagTree.show();
1503         menuBar.hideTags.setChecked(tagTree.isVisible());
1504         Global.saveWindowVisible("tagTree", tagTree.isVisible());
1505         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1506     }   
1507         // A note's tags have been updated
1508         @SuppressWarnings("unused")
1509         private void updateNoteTags(String guid, List<String> tags) {
1510                 listManager.saveNoteTags(guid, tags);
1511                 listManager.countTagResults(listManager.getNoteIndex());
1512                 StringBuffer names = new StringBuffer("");
1513                 for (int i=0; i<tags.size(); i++) {
1514                         names = names.append(tags.get(i));
1515                         if (i<tags.size()-1) {
1516                                 names.append(Global.tagDelimeter + " ");
1517                         }
1518                 }
1519                 browserWindow.setTag(names.toString());
1520                 noteDirty = true;
1521 //              tagTree.updateCounts(listManager.getTagCounter());
1522         }
1523         // Get a string containing all tag names for a note
1524         private String getTagNamesForNote(Note n) {
1525                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
1526                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
1527                         return "";
1528                 StringBuffer buffer = new StringBuffer(100);
1529                 Vector<String> v = new Vector<String>();
1530                 List<String> guids = n.getTagGuids();
1531                 
1532                 if (guids == null) 
1533                         return "";
1534                 
1535                 for (int i=0; i<guids.size(); i++) {
1536                         v.add(listManager.getTagNameByGuid(guids.get(i)));
1537                 }
1538                 Comparator<String> comparator = Collections.reverseOrder();
1539                 Collections.sort(v,comparator);
1540                 Collections.reverse(v);
1541                 
1542                 for (int i = 0; i<v.size(); i++) {
1543                         if (i>0) 
1544                                 buffer.append(", ");
1545                         buffer.append(v.get(i));
1546                 }
1547                 
1548                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
1549                 return buffer.toString();
1550         }       
1551         // Tags were added via dropping notes from the note list
1552         @SuppressWarnings("unused")
1553         private void tagsAdded(String noteGuid, String tagGuid) {
1554                 String tagName = null;
1555                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1556                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
1557                                 tagName = listManager.getTagIndex().get(i).getName();
1558                                 i=listManager.getTagIndex().size();
1559                         }
1560                 }
1561                 if (tagName == null)
1562                         return;
1563                 
1564                 for (int i=0; i<noteTableView.model.rowCount(); i++) {
1565                         QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
1566                         if (modelIndex != null) {
1567                                 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
1568                                 String titleGuid = (String)ix.values().toArray()[0];
1569                                 if (titleGuid.equals(noteGuid)) {
1570                                         String text = (String)noteTableView.model.data(i, Global.noteTableTagPosition);
1571                                         if (!text.trim().equals(""))
1572                                                 text = text + Global.tagDelimeter + " " +tagName;
1573                                         else
1574                                                 text = tagName;
1575                                         noteTableView.model.setData(i, Global.noteTableTagPosition, text);
1576                                         noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
1577                                         if (noteGuid.equals(currentNoteGuid))
1578                                                 browserWindow.setTag(text);
1579                                         i=noteTableView.model.rowCount();
1580                                 }
1581                         }
1582                 }
1583         }
1584         private void clearTagFilter() {
1585                 tagTree.blockSignals(true);
1586                 tagTree.clearSelection();
1587                 menuBar.noteRestoreAction.setVisible(false);
1588                 menuBar.tagEditAction.setEnabled(false);
1589                 menuBar.tagDeleteAction.setEnabled(false);
1590                 selectedTagGUIDs.clear();
1591         listManager.setSelectedTags(selectedTagGUIDs);
1592         tagTree.blockSignals(false);
1593         }
1594         
1595         
1596     //***************************************************************
1597     //***************************************************************
1598     //** These functions deal with Saved Search menu items
1599     //***************************************************************
1600     //***************************************************************
1601         // Add a new notebook
1602         @SuppressWarnings("unused")
1603         private void addSavedSearch() {
1604                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
1605                 SavedSearchEdit edit = new SavedSearchEdit();
1606                 edit.setSearchList(listManager.getSavedSearchIndex());
1607                 edit.exec();
1608         
1609                 if (!edit.okPressed())
1610                         return;
1611         
1612                 Calendar currentTime = new GregorianCalendar();         
1613                 Long l = new Long(currentTime.getTimeInMillis());
1614                 String randint = new String(Long.toString(l));
1615         
1616                 SavedSearch search = new SavedSearch();
1617                 search.setUpdateSequenceNum(0);
1618                 search.setGuid(randint);
1619                 search.setName(edit.getName());
1620                 search.setQuery(edit.getQuery());
1621                 search.setFormat(QueryFormat.USER);
1622                 listManager.getSavedSearchIndex().add(search);
1623                 conn.getSavedSearchTable().addSavedSearch(search, true);
1624                 savedSearchIndexUpdated();
1625                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
1626         }
1627         // Edit an existing tag
1628         @SuppressWarnings("unused")
1629         private void editSavedSearch() {
1630                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
1631                 SavedSearchEdit edit = new SavedSearchEdit();
1632                 edit.setTitle("Edit Search");
1633                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1634                 QTreeWidgetItem currentSelection;
1635                 currentSelection = selections.get(0);
1636                 String guid = currentSelection.text(1);
1637                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
1638                 edit.setName(currentSelection.text(0));
1639                 edit.setQuery(s.getQuery());
1640                 edit.setSearchList(listManager.getSavedSearchIndex());
1641                 edit.exec();
1642         
1643                 if (!edit.okPressed())
1644                         return;
1645         
1646                 List<SavedSearch> list = listManager.getSavedSearchIndex();
1647                 SavedSearch search = null;
1648                 boolean found = false;
1649                 for (int i=0; i<list.size(); i++) {
1650                         search = list.get(i);
1651                         if (search.getGuid().equals(guid)) {
1652                                 i=list.size();
1653                                 found = true;
1654                         }
1655                 }
1656                 if (!found)
1657                         return;
1658                 search.setName(edit.getName());
1659                 search.setQuery(edit.getQuery());
1660                 conn.getSavedSearchTable().updateSavedSearch(search, true);
1661                 savedSearchIndexUpdated();
1662                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
1663         }
1664         // Delete an existing tag
1665         @SuppressWarnings("unused")
1666         private void deleteSavedSearch() {
1667                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
1668                 
1669                 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
1670                         QMessageBox.StandardButton.Yes, 
1671                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1672                                                         return;
1673                 }
1674                 
1675                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1676         for (int i=selections.size()-1; i>=0; i--) {
1677                 QTreeWidgetItem currentSelection;
1678                 currentSelection = selections.get(i);
1679                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
1680                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
1681                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
1682                                 listManager.getSavedSearchIndex().remove(j);
1683                                 j=listManager.getSavedSearchIndex().size()+1;
1684                         }
1685                 }
1686                 selections.remove(i);
1687         }
1688         savedSearchIndexUpdated();
1689         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
1690         }
1691     // Setup the tree containing the user's tags
1692     private void initializeSavedSearchTree() {
1693         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
1694         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
1695         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
1696     }
1697     // Listener when a tag is selected
1698     @SuppressWarnings("unused")
1699         private void savedSearchTreeSelection() {
1700         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
1701
1702         clearNotebookFilter();
1703         clearTagFilter();
1704         clearTrashFilter();
1705         clearAttributeFilter();
1706         
1707         String currentGuid = selectedSavedSearchGUID;
1708         menuBar.savedSearchEditAction.setEnabled(true);
1709         menuBar.savedSearchDeleteAction.setEnabled(true);
1710         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1711         QTreeWidgetItem currentSelection;
1712         selectedSavedSearchGUID = "";
1713         for (int i=0; i<selections.size(); i++) {
1714                 currentSelection = selections.get(i);
1715                 if (currentSelection.text(1).equals(currentGuid)) {
1716                         currentSelection.setSelected(false);
1717                 } else {
1718                         selectedSavedSearchGUID = currentSelection.text(1);
1719                 }
1720 //              i = selections.size() +1;
1721         }
1722         
1723         // There is the potential for no notebooks to be selected if this 
1724         // happens then we make it look like all notebooks were selecetd.
1725         // If that happens, just select the "all notebooks"
1726         if (selections.size()==0) {
1727                 clearSavedSearchFilter();
1728         }
1729         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1730         
1731         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
1732     }
1733     private void clearSavedSearchFilter() {
1734         menuBar.savedSearchEditAction.setEnabled(false);
1735         menuBar.savedSearchDeleteAction.setEnabled(false);
1736         savedSearchTree.blockSignals(true);
1737         savedSearchTree.clearSelection();
1738         savedSearchTree.blockSignals(false);
1739         selectedSavedSearchGUID = "";
1740         searchField.setEditText("");
1741         searchPerformed = false;
1742         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1743     }
1744     // trigger the tag index to be refreshed
1745         private void savedSearchIndexUpdated() { 
1746                 if (selectedSavedSearchGUID == null)
1747                         selectedSavedSearchGUID = new String();
1748                 savedSearchTree.blockSignals(true);
1749         savedSearchTree.load(listManager.getSavedSearchIndex());
1750         savedSearchTree.selectGuid(selectedSavedSearchGUID);
1751         savedSearchTree.blockSignals(false);
1752     }
1753     // trigger when the saved search selection changes
1754     @SuppressWarnings("unused")
1755         private void updateSavedSearchSelection() {
1756                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
1757                 
1758         menuBar.savedSearchEditAction.setEnabled(true);
1759         menuBar.savedSearchDeleteAction.setEnabled(true);
1760         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1761
1762         if (selections.size() > 0) {
1763                 menuBar.savedSearchEditAction.setEnabled(true);
1764                 menuBar.savedSearchDeleteAction.setEnabled(true);
1765                 selectedSavedSearchGUID = selections.get(0).text(1);
1766                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
1767                 searchField.setEditText(s.getQuery());
1768         } else { 
1769                 menuBar.savedSearchEditAction.setEnabled(false);
1770                 menuBar.savedSearchDeleteAction.setEnabled(false);
1771                 selectedSavedSearchGUID = "";
1772                 searchField.setEditText("");
1773         }
1774         searchFieldChanged();
1775         
1776                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
1777
1778         
1779     }
1780     // Show/Hide note information
1781         private void toggleSavedSearchWindow() {
1782                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
1783         if (savedSearchTree.isVisible())
1784                 savedSearchTree.hide();
1785         else
1786                 savedSearchTree.show();
1787         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
1788                                 
1789                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
1790         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
1791     }
1792         
1793         
1794         
1795         
1796     //***************************************************************
1797     //***************************************************************
1798     //** These functions deal with Help menu & tool menu items
1799     //***************************************************************
1800     //***************************************************************
1801         // Show database status
1802         @SuppressWarnings("unused")
1803         private void databaseStatus() {
1804                 waitCursor(true);
1805                 int dirty = conn.getNoteTable().getDirtyCount();
1806                 int unindexed = conn.getNoteTable().getUnindexedCount();
1807                 DatabaseStatus status = new DatabaseStatus();
1808                 status.setUnsynchronized(dirty);
1809                 status.setUnindexed(unindexed);
1810                 status.setNoteCount(conn.getNoteTable().getNoteCount());
1811                 status.setNotebookCount(listManager.getNotebookIndex().size());
1812                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
1813                 status.setTagCount(listManager.getTagIndex().size());
1814                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
1815                 status.setWordCount(conn.getWordsTable().getWordCount());
1816                 waitCursor(false);
1817                 status.exec();
1818         }
1819         // Compact the database
1820         @SuppressWarnings("unused")
1821         private void compactDatabase() {
1822         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
1823                 if (QMessageBox.question(this, "Confirmation", "This will free unused space in the database, "+
1824                                 "but please be aware that depending upon the size of your database this can be time consuming " +
1825                                 "and NeverNote will be unresponsive until it is complete.  Do you wish to continue?",
1826                                 QMessageBox.StandardButton.Yes, 
1827                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
1828                                                         return;
1829                 }
1830                 setMessage("Compacting database.");
1831                 waitCursor(true);
1832                 listManager.compactDatabase();
1833                 waitCursor(false);
1834                 setMessage("Database compact is complete.");            
1835         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
1836     }
1837         @SuppressWarnings("unused")
1838         private void accountInformation() {
1839                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
1840                 AccountDialog dialog = new AccountDialog();
1841                 dialog.show();
1842                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
1843         }
1844         @SuppressWarnings("unused")
1845         private void releaseNotes() {
1846                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
1847                 QDialog dialog = new QDialog(this);
1848                 QHBoxLayout layout = new QHBoxLayout();
1849                 QTextEdit textBox = new QTextEdit();
1850                 layout.addWidget(textBox);
1851                 textBox.setReadOnly(true);
1852                 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
1853                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
1854                 QIODevice.OpenModeFlag.Text)))
1855                         return;
1856                 textBox.setText(file.readAll().toString());
1857                 file.close();
1858                 dialog.setWindowTitle("Release Notes");
1859                 dialog.setLayout(layout);
1860                 dialog.show();
1861                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
1862         }
1863         // Called when user picks Log from the help menu
1864         @SuppressWarnings("unused")
1865         private void logger() {
1866                 logger.log(logger.HIGH, "Entering NeverNote.logger");
1867                 QDialog dialog = new QDialog(this);
1868                 QHBoxLayout layout = new QHBoxLayout();
1869                 QListWidget textBox = new QListWidget();
1870                 layout.addWidget(textBox);
1871                 textBox.addItems(emitLog);
1872                 
1873                 dialog.setLayout(layout);
1874                 dialog.setWindowTitle("Mesasge Log");
1875                 dialog.show();
1876                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
1877         }
1878         // Menu option "help/about" was selected
1879         @SuppressWarnings("unused")
1880         private void about() {
1881                 logger.log(logger.HIGH, "Entering NeverNote.about");
1882                 QMessageBox.about(this, 
1883                                                 tr("About NeverNote"),
1884                                                 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version "+Global.version+"<hr></center>Evernote"
1885                                                                 +" Generic client.<br><br>" 
1886                                                                 +"Licensed under GPL v2.  <br><hr><br>"
1887                                                                 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
1888                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
1889                                                                 +"PDFRenderer is licened under the LGPL<br>"
1890                                                                 +"Jazzy is licened under the LGPL<br>"
1891                                                                 +"Java is a registered trademark of Sun Microsystems.<br><hr>"));       
1892                 logger.log(logger.HIGH, "Leaving NeverNote.about");
1893         }
1894         // Hide the entire left hand side
1895         @SuppressWarnings("unused")
1896         private void toggleLeftSide() {
1897                 boolean hidden;
1898                 
1899                 hidden = !menuBar.hideLeftSide.isChecked();
1900                 menuBar.hideLeftSide.setChecked(!hidden);
1901                 
1902                 if (notebookTree.isVisible() != hidden)
1903                         toggleNotebookWindow();
1904                 if (savedSearchTree.isVisible() != hidden)
1905                         toggleSavedSearchWindow();
1906                 if (tagTree.isVisible() != hidden)
1907                         toggleTagWindow();
1908                 if (attributeTree.isVisible() != hidden)
1909                         toggleAttributesWindow();
1910                 if (trashTree.isVisible() != hidden)
1911                         toggleTrashWindow();
1912                 
1913                 Global.saveWindowVisible("leftPanel", hidden);
1914                 
1915         }
1916                         
1917         
1918     //***************************************************************
1919     //***************************************************************
1920     //** These functions deal with the Toolbar
1921     //***************************************************************
1922     //***************************************************************  
1923         // Text in the search bar has been cleared
1924         private void searchFieldCleared() {
1925                 searchField.setEditText("");
1926                 saveNoteIndexWidth();
1927         }
1928         // text in the search bar changed.  We only use this to tell if it was cleared, 
1929         // otherwise we trigger off searchFieldChanged.
1930         @SuppressWarnings("unused")
1931         private void searchFieldTextChanged(String text) {
1932                 if (text.trim().equals("")) {
1933                         searchFieldCleared();
1934                         if (searchPerformed) {
1935                                 noteCache.clear();
1936                                 listManager.setEnSearch("");
1937 /////                           listManager.clearNoteIndexSearch();
1938                                 //noteIndexUpdated(true);
1939                                 listManager.loadNotesIndex();
1940                                 refreshEvernoteNote(true);
1941                                 noteIndexUpdated(false);
1942                         }
1943                         searchPerformed = false;
1944                 }
1945         }
1946     // Text in the toolbar has changed
1947     private void searchFieldChanged() {
1948         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
1949         noteCache.clear();
1950         saveNoteIndexWidth();
1951         String text = searchField.currentText();
1952         listManager.setEnSearch(text.trim());
1953         listManager.loadNotesIndex();
1954 //--->>>        noteIndexUpdated(true);
1955         noteIndexUpdated(false);
1956         refreshEvernoteNote(true);
1957         searchPerformed = true;
1958         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
1959     }
1960     // Build the window tool bar
1961     private void setupToolBar() {
1962         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
1963         toolBar = addToolBar(tr("toolBar"));    
1964
1965         prevButton = toolBar.addAction("Previous");
1966         QIcon prevIcon = new QIcon(iconPath+"back.png");
1967         prevButton.setIcon(prevIcon);
1968         prevButton.triggered.connect(this, "previousViewedAction()");   
1969         
1970         nextButton = toolBar.addAction("Next");
1971         QIcon nextIcon = new QIcon(iconPath+"forward.png");
1972         nextButton.setIcon(nextIcon);
1973         nextButton.triggered.connect(this, "nextViewedAction()");       
1974         
1975         upButton = toolBar.addAction("Up");
1976         QIcon upIcon = new QIcon(iconPath+"up.png");
1977         upButton.setIcon(upIcon);
1978         upButton.triggered.connect(this, "upAction()");         
1979         
1980         downButton = toolBar.addAction("Down");
1981         QIcon downIcon = new QIcon(iconPath+"down.png");
1982         downButton.setIcon(downIcon);
1983         downButton.triggered.connect(this, "downAction()");
1984         
1985         synchronizeButton = toolBar.addAction("Synchronize");
1986         synchronizeAnimation = new ArrayList<QIcon>();
1987         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-0.png"));
1988         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-1.png"));
1989         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-2.png"));
1990         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-3.png"));
1991         synchronizeButton.setIcon(synchronizeAnimation.get(0));
1992         synchronizeFrame = 0;
1993         synchronizeButton.triggered.connect(this, "evernoteSync()");
1994         
1995         printButton = toolBar.addAction("Print");
1996         QIcon printIcon = new QIcon(iconPath+"print.png");
1997         printButton.setIcon(printIcon);
1998         printButton.triggered.connect(this, "printNote()");
1999         
2000         tagButton = toolBar.addAction("Tag"); 
2001         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2002         tagButton.setIcon(tagIcon);
2003         tagButton.triggered.connect(browserWindow, "modifyTags()");
2004         
2005         attributeButton = toolBar.addAction("Attributes"); 
2006         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2007         attributeButton.setIcon(attributeIcon);
2008         attributeButton.triggered.connect(this, "toggleNoteInformation()");
2009                 
2010         emailButton = toolBar.addAction("Email");
2011         QIcon emailIcon = new QIcon(iconPath+"email.png");
2012         emailButton.setIcon(emailIcon);
2013         emailButton.triggered.connect(this, "emailNote()");
2014         
2015         deleteButton = toolBar.addAction("Delete");     
2016         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2017         deleteButton.setIcon(deleteIcon);
2018         deleteButton.triggered.connect(this, "deleteNote()");
2019                 
2020         newButton = toolBar.addAction("New");
2021         QIcon newIcon = new QIcon(iconPath+"new.png");
2022         newButton.triggered.connect(this, "addNote()");
2023         newButton.setIcon(newIcon);
2024         toolBar.addSeparator();
2025         toolBar.addWidget(new QLabel("Quota:"));
2026         toolBar.addWidget(quotaBar);
2027         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2028         updateQuotaBar();
2029         
2030         // Setup the zoom
2031         zoomSpinner = new QSpinBox();
2032         zoomSpinner.setMinimum(10);
2033         zoomSpinner.setMaximum(1000);
2034         zoomSpinner.setAccelerated(true);
2035         zoomSpinner.setSingleStep(10);
2036         zoomSpinner.setValue(100);
2037         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2038         toolBar.addWidget(new QLabel("Zoom"));
2039         toolBar.addWidget(zoomSpinner);
2040         
2041         //toolBar.addWidget(new QLabel("                    "));
2042         toolBar.addSeparator();
2043         toolBar.addWidget(new QLabel("  Search:"));
2044         toolBar.addWidget(searchField);
2045         QSizePolicy sizePolicy = new QSizePolicy();
2046         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2047         searchField.setSizePolicy(sizePolicy);
2048         searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2049
2050         searchClearButton = toolBar.addAction("Search Clear");
2051         QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2052         searchClearButton.setIcon(searchClearIcon);
2053         searchClearButton.triggered.connect(this, "searchFieldCleared()");
2054         
2055         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2056     }
2057     // Update the sychronize button picture
2058     @SuppressWarnings("unused")
2059         private void updateSyncButton() {
2060         synchronizeFrame++;
2061         if (synchronizeFrame == 4) 
2062                 synchronizeFrame = 0;
2063         synchronizeButton.setIcon(synchronizeAnimation.get(synchronizeFrame));
2064     }
2065     // Synchronize with Evernote
2066         @SuppressWarnings("unused")
2067         private void evernoteSync() {
2068         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2069         if (!Global.isConnected)
2070                 remoteConnect();
2071         if (Global.isConnected)
2072                 synchronizeAnimationTimer.start(200);
2073         syncTimer();
2074         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2075     }
2076     private void updateQuotaBar() {
2077         long limit = Global.getUploadLimit();
2078         long amount = Global.getUploadAmount();
2079         if (amount>0 && limit>0) {
2080                 int percent =(int)(amount*100/limit);
2081                 quotaBar.setValue(percent);
2082         } else 
2083                 quotaBar.setValue(0);
2084     }
2085         // Zoom changed
2086     @SuppressWarnings("unused")
2087         private void zoomChanged() {
2088         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2089     }
2090
2091     //****************************************************************
2092     //****************************************************************
2093     //* System Tray functions
2094     //****************************************************************
2095     //****************************************************************
2096         private void trayToggleVisible() {
2097         if (isVisible()) {
2098                 hide();
2099         } else {
2100                 show();
2101                 raise();
2102         }
2103     }
2104     @SuppressWarnings("unused")
2105         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2106         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2107                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2108                 trayToggleVisible();
2109         }
2110     }
2111     
2112     
2113     //***************************************************************
2114     //***************************************************************
2115     //** These functions deal with the trash tree
2116     //***************************************************************
2117     //***************************************************************    
2118     // Setup the tree containing the trash.
2119     @SuppressWarnings("unused")
2120         private void trashTreeSelection() {     
2121         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2122         
2123         clearNotebookFilter();
2124         clearTagFilter();
2125         clearAttributeFilter();
2126         clearSavedSearchFilter();
2127         
2128         String tempGuid = currentNoteGuid;
2129         
2130 //      currentNoteGuid = "";
2131         currentNote = new Note();
2132         selectedNoteGUIDs.clear();
2133         listManager.getSelectedNotebooks().clear();
2134         listManager.getSelectedTags().clear();
2135         listManager.setSelectedSavedSearch("");
2136         browserWindow.clear();
2137     
2138         // toggle the add buttons
2139         newButton.setEnabled(!newButton.isEnabled());
2140         menuBar.noteAdd.setEnabled(newButton.isEnabled());
2141         menuBar.noteAdd.setVisible(true);
2142         
2143         List<QTreeWidgetItem> selections = trashTree.selectedItems();
2144         if (selections.size() == 0) {
2145                 currentNoteGuid = trashNoteGuid;
2146                         trashNoteGuid = tempGuid;
2147                 Global.showDeleted = false;
2148                 menuBar.noteRestoreAction.setEnabled(false);
2149                 menuBar.noteRestoreAction.setVisible(false);
2150         }
2151         else {
2152                 currentNoteGuid = trashNoteGuid;
2153                         trashNoteGuid = tempGuid;
2154                 menuBar.noteRestoreAction.setEnabled(true);
2155                 menuBar.noteRestoreAction.setVisible(true);
2156                 Global.showDeleted = true;
2157         }
2158         listManager.loadNotesIndex();
2159         noteIndexUpdated(false);
2160 ////            browserWindow.setEnabled(newButton.isEnabled());
2161         browserWindow.setReadOnly(!newButton.isEnabled());
2162         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2163     }
2164     // Empty the trash file
2165     @SuppressWarnings("unused")
2166         private void emptyTrash() {
2167 //      browserWindow.clear();
2168         listManager.emptyTrash();
2169         if (trashTree.selectedItems().size() > 0) {
2170                 listManager.getSelectedNotebooks().clear();
2171                 listManager.getSelectedTags().clear();
2172                 listManager.setSelectedSavedSearch("");
2173                 newButton.setEnabled(!newButton.isEnabled());
2174                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2175                 menuBar.noteAdd.setVisible(true);
2176                 browserWindow.clear();
2177                 
2178                 clearTagFilter();
2179                 clearNotebookFilter();
2180                 clearSavedSearchFilter();
2181                 clearAttributeFilter();
2182                         
2183                 Global.showDeleted = false;
2184                 menuBar.noteRestoreAction.setEnabled(false);
2185                 menuBar.noteRestoreAction.setVisible(false);
2186                 
2187                 listManager.loadNotesIndex();
2188 //--->>>                noteIndexUpdated(true);
2189                 noteIndexUpdated(false);
2190         }       
2191    }
2192     // Show/Hide trash window
2193         private void toggleTrashWindow() {
2194                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2195         if (trashTree.isVisible())
2196                 trashTree.hide();
2197         else
2198                 trashTree.show();
2199         menuBar.hideTrash.setChecked(trashTree.isVisible());
2200         
2201                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2202         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2203     }    
2204         private void clearTrashFilter() {
2205                 Global.showDeleted = false;
2206         newButton.setEnabled(true);
2207         menuBar.noteAdd.setEnabled(true);
2208         menuBar.noteAdd.setVisible(true);
2209                 trashTree.blockSignals(true);
2210                 trashTree.clearSelection();
2211                 trashTree.blockSignals(false);
2212                 
2213         }
2214     
2215    
2216     //***************************************************************
2217     //***************************************************************
2218     //** These functions deal with connection settings
2219     //***************************************************************
2220     //***************************************************************
2221         // SyncRunner had a problem and things are disconnected
2222         @SuppressWarnings("unused")
2223         private void remoteErrorDisconnect() {
2224                 menuBar.connectAction.setText("Connect");
2225                 menuBar.connectAction.setToolTip("Connect to Evernote");
2226                 menuBar.synchronizeAction.setEnabled(false);
2227                 synchronizeAnimationTimer.stop();
2228                 return;
2229         }
2230         // Do a manual connect/disconnect
2231     private void remoteConnect() {
2232         logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2233
2234         if (Global.isConnected) {
2235                 Global.isConnected = false;
2236                 syncRunner.enDisconnect();
2237                 setupConnectMenuOptions();
2238                 setupOnlineMenu();
2239                 return;
2240         }
2241         
2242         AESEncrypter aes = new AESEncrypter();
2243         try {
2244                         aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
2245                 } catch (FileNotFoundException e) {
2246                         // File not found, so we'll just get empty strings anyway. 
2247                 }
2248                 String userid = aes.getUserid();
2249                 String password = aes.getPassword();
2250                 if (!userid.equals("") && !password.equals("")) {
2251                 Global.username = userid;
2252                 Global.password = password;
2253                 }               
2254
2255         // Show the login dialog box
2256                 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
2257                         LoginDialog login = new LoginDialog();
2258                         login.exec();
2259                 
2260                         if (!login.okPressed()) {
2261                                 return;
2262                         }
2263         
2264                         Global.username = login.getUserid();
2265                         Global.password = login.getPassword();
2266                 }
2267                 syncRunner.username = Global.username;
2268                 syncRunner.password = Global.password;
2269                 syncRunner.userStoreUrl = Global.userStoreUrl;
2270                 syncRunner.noteStoreUrl = Global.noteStoreUrl;
2271                 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
2272                 syncRunner.enConnect();
2273                 Global.isConnected = syncRunner.isConnected;
2274                 setupOnlineMenu();
2275                 setupConnectMenuOptions();
2276                 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
2277     }
2278     private void setupConnectMenuOptions() {
2279         logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
2280                 if (!Global.isConnected) {
2281                         menuBar.connectAction.setText("Connect");
2282                         menuBar.connectAction.setToolTip("Connect to Evernote");
2283                         menuBar.synchronizeAction.setEnabled(false);
2284                 } else {
2285                         menuBar.connectAction.setText("Disconnect");
2286                         menuBar.connectAction.setToolTip("Disconnect from Evernote");
2287                         menuBar.synchronizeAction.setEnabled(true);
2288                 }
2289                 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
2290     }
2291     
2292     
2293     
2294     //***************************************************************
2295     //***************************************************************
2296     //** These functions deal with the GUI Attribute tree
2297     //***************************************************************
2298     //***************************************************************    
2299     @SuppressWarnings("unused")
2300         private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
2301         
2302         clearTagFilter();
2303         clearNotebookFilter();
2304         clearTrashFilter();
2305         clearSavedSearchFilter();
2306
2307         if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
2308                 if (item.childCount() > 0) {
2309                         item.setSelected(false);
2310                 } else {
2311                 Global.createdBeforeFilter.reset();
2312                 Global.createdSinceFilter.reset();
2313                 Global.changedBeforeFilter.reset();
2314                 Global.changedSinceFilter.reset();
2315                 Global.containsFilter.reset();
2316                         attributeTreeSelected = item;
2317                         DateAttributeFilterTable f = null;
2318                         f = findDateAttributeFilterTable(item.parent());
2319                         if (f!=null)
2320                                 f.select(item.text(0));
2321                         else {
2322                                 String text = item.text(0);
2323                                 Global.containsFilter.select(text);
2324                         }
2325                 }
2326                 listManager.loadNotesIndex();
2327                 noteIndexUpdated(false);
2328                 return;
2329         }
2330                 attributeTreeSelected = null;
2331                 item.setSelected(false);
2332         Global.createdBeforeFilter.reset();
2333         Global.createdSinceFilter.reset();
2334         Global.changedBeforeFilter.reset();
2335         Global.changedSinceFilter.reset();
2336         Global.containsFilter.reset();
2337         listManager.loadNotesIndex();
2338                 noteIndexUpdated(false); 
2339     }
2340     // This determines what attribute filter we need, depending upon the selection
2341     private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
2342                 if (w.parent() != null && w.childCount() > 0) {
2343                         QTreeWidgetItem parent = w.parent();
2344                         if (parent.text(0).equalsIgnoreCase("created") && 
2345                                 w.text(0).equalsIgnoreCase("since"))
2346                                         return Global.createdSinceFilter;
2347                         if (parent.text(0).equalsIgnoreCase("created") && 
2348                         w.text(0).equalsIgnoreCase("before"))
2349                                         return Global.createdBeforeFilter;
2350                         if (parent.text(0).equalsIgnoreCase("last modified") && 
2351                         w.text(0).equalsIgnoreCase("since"))
2352                                         return Global.changedSinceFilter;
2353                 if (parent.text(0).equalsIgnoreCase("last modified") && 
2354                         w.text(0).equalsIgnoreCase("before"))
2355                                                 return Global.changedBeforeFilter;
2356                 }
2357                 return null;
2358     }
2359     // Show/Hide attribute search window
2360         private void toggleAttributesWindow() {
2361                 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
2362         if (attributeTree.isVisible())
2363                 attributeTree.hide();
2364         else
2365                 attributeTree.show();
2366         menuBar.hideAttributes.setChecked(attributeTree.isVisible());
2367         
2368                 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
2369         logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
2370     }    
2371         private void clearAttributeFilter() {
2372         Global.createdBeforeFilter.reset();
2373         Global.createdSinceFilter.reset();
2374         Global.changedBeforeFilter.reset();
2375         Global.changedSinceFilter.reset();
2376         Global.containsFilter.reset();
2377         attributeTreeSelected = null;
2378                 attributeTree.blockSignals(true);
2379                 attributeTree.clearSelection();
2380                 attributeTree.blockSignals(false);
2381         }
2382     
2383         
2384     //***************************************************************
2385     //***************************************************************
2386     //** These functions deal with the GUI Note index table
2387     //***************************************************************
2388     //***************************************************************    
2389     // Initialize the note list table
2390         private void initializeNoteTable() {
2391                 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
2392                 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
2393                 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
2394                 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
2395         }       
2396     // Show/Hide trash window
2397         @SuppressWarnings("unused")
2398         private void toggleNoteListWindow() {
2399                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
2400         if (noteTableView.isVisible())
2401                 noteTableView.hide();
2402         else
2403                 noteTableView.show();
2404         menuBar.hideNoteList.setChecked(noteTableView.isVisible());
2405         
2406                 Global.saveWindowVisible("noteList", noteTableView.isVisible());
2407         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
2408     }   
2409         // Handle the event that a user selects a note from the table
2410     @SuppressWarnings("unused")
2411         private void noteTableSelection() {
2412                 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
2413                 saveNote();
2414                 if (historyGuids.size() == 0) {
2415                         historyGuids.add(currentNoteGuid);
2416                         historyPosition = 1;
2417                 }
2418         noteTableView.showColumn(Global.noteTableGuidPosition);
2419         
2420         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2421         noteTableView.hideColumn(Global.noteTableGuidPosition);
2422         
2423         if (selections.size() > 0) {
2424                 QModelIndex index;
2425                 menuBar.noteDuplicateAction.setEnabled(true);
2426                 menuBar.noteOnlineHistoryAction.setEnabled(true);
2427                 menuBar.noteMergeAction.setEnabled(true);
2428                 selectedNoteGUIDs.clear();
2429                 if (selections.size() != 1 || Global.showDeleted) {
2430                         menuBar.noteDuplicateAction.setEnabled(false);
2431                 }
2432                 if (selections.size() != 1 || !Global.isConnected) {
2433                         menuBar.noteOnlineHistoryAction.setEnabled(false);
2434                 }
2435                 if (selections.size() == 1) {
2436                         menuBar.noteMergeAction.setEnabled(false);
2437                 }
2438                 for (int i=0; i<selections.size(); i++) {
2439                         int row = selections.get(i).row();
2440                         if (row == 0) 
2441                                 upButton.setEnabled(false);
2442                         else
2443                                 upButton.setEnabled(true);
2444                         if (row < noteTableView.model.rowCount()-1)
2445                                 downButton.setEnabled(true);
2446                         else
2447                                 downButton.setEnabled(false);
2448                         index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
2449                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
2450                         currentNoteGuid = (String)ix.values().toArray()[0];
2451                         selectedNoteGUIDs.add(currentNoteGuid);
2452                 }
2453         }
2454         
2455         nextButton.setEnabled(true);
2456                 prevButton.setEnabled(true);
2457         if (!fromHistory) {
2458                 int endPosition = historyGuids.size()-1;
2459                 for (int j=historyPosition; j<=endPosition; j++) {
2460                         historyGuids.remove(historyGuids.size()-1);
2461                 }
2462                 historyGuids.add(currentNoteGuid);
2463                 historyPosition = historyGuids.size();
2464         } 
2465         if (historyPosition <= 1)
2466                 prevButton.setEnabled(false);
2467         if (historyPosition == historyGuids.size())
2468                 nextButton.setEnabled(false);
2469                 
2470         fromHistory = false;
2471         scrollToGuid(currentNoteGuid);
2472         refreshEvernoteNote(true);
2473                 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
2474     }    
2475         // Trigger a refresh when the note db has been updated
2476         private void noteIndexUpdated(boolean reload) {
2477                 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
2478                 Global.traceReset();  
2479                 saveNote();
2480         refreshEvernoteNoteList();
2481         logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
2482         noteTableView.load(listManager, reload);
2483         scrollToGuid(currentNoteGuid);
2484                 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
2485     }
2486         // Called when the list of notes is updated
2487     private void refreshEvernoteNoteList() {
2488         logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
2489         browserWindow.setDisabled(false);
2490                 if (selectedNoteGUIDs == null)
2491                         selectedNoteGUIDs = new ArrayList<String>();
2492                 selectedNoteGUIDs.clear();  // clear out old entries
2493                 
2494                 String saveCurrentNoteGuid = new String();
2495                 String tempNoteGuid = new String();
2496                                 
2497                 historyGuids.clear();
2498                 historyPosition = 0;
2499                 prevButton.setEnabled(false);
2500                 nextButton.setEnabled(false);
2501                 
2502                 if (currentNoteGuid == null) 
2503                         currentNoteGuid = new String();
2504                 
2505                 for (Note note : listManager.getNoteIndex()) {
2506                         tempNoteGuid = note.getGuid();
2507                         if (currentNoteGuid.equals(tempNoteGuid)) {
2508                                 saveCurrentNoteGuid = new String(tempNoteGuid);
2509                         }
2510                 }
2511                 
2512                 if (listManager.getNoteIndex().size() == 0) {
2513                         currentNoteGuid = "";
2514                         currentNote = null;
2515                         browserWindow.clear();
2516                         browserWindow.setDisabled(true);
2517                 } 
2518                 
2519                 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() >0) {
2520                         currentNoteGuid = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1).getGuid();
2521                         currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
2522                         refreshEvernoteNote(true);
2523                 } else {
2524                         refreshEvernoteNote(false);
2525                 }
2526                 reloadTagTree();
2527
2528                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
2529         } 
2530     // Called when the previous arrow button is clicked 
2531     @SuppressWarnings("unused")
2532         private void previousViewedAction() {
2533         if (!prevButton.isEnabled())
2534                 return;
2535         if (historyPosition == 0)
2536                 return;
2537                 historyPosition--;
2538         if (historyPosition <= 0)
2539                 return;
2540         String historyGuid = historyGuids.get(historyPosition-1);
2541         fromHistory = true;
2542         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2543                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
2544                 if (modelIndex != null) {
2545                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2546                         String tableGuid =  (String)ix.values().toArray()[0];
2547                         if (tableGuid.equals(historyGuid)) {
2548                                 noteTableView.selectRow(i);
2549                                 return;
2550                         }       
2551                 }
2552         }
2553     }
2554     @SuppressWarnings("unused")
2555         private void nextViewedAction() {
2556         if (!nextButton.isEnabled())
2557                 return;
2558         String historyGuid = historyGuids.get(historyPosition);
2559         historyPosition++;
2560         fromHistory = true;
2561         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2562                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
2563                 if (modelIndex != null) {
2564                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2565                         String tableGuid =  (String)ix.values().toArray()[0];
2566                         if (tableGuid.equals(historyGuid)) {
2567                                 noteTableView.selectRow(i);
2568                                 return;
2569                         }       
2570                 }
2571         }       
2572     }
2573     // Called when the up arrow is clicked 
2574     @SuppressWarnings("unused")
2575         private void upAction() {
2576         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2577         int row = selections.get(0).row();
2578         if (row > 0) {
2579                 noteTableView.selectRow(row-1);
2580         }
2581     }
2582     // Called when the down arrow is clicked 
2583     @SuppressWarnings("unused")
2584         private void downAction() {
2585         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2586         int row = selections.get(0).row();
2587         int max = noteTableView.model.rowCount();
2588         if (row < max-1) {
2589                 noteTableView.selectRow(row+1);
2590         }
2591     }
2592     // Update a tag string for a specific note in the list
2593     @SuppressWarnings("unused")
2594         private void updateListTags(String guid, List<String> tags) {
2595         logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
2596         StringBuffer tagBuffer = new StringBuffer();
2597         for (int i=0; i<tags.size(); i++) {
2598                 tagBuffer.append(tags.get(i));
2599                 if (i<tags.size()-1)
2600                         tagBuffer.append(", ");
2601         }
2602         
2603         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2604                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2605                 if (modelIndex != null) {
2606                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2607                         String tableGuid =  (String)ix.values().toArray()[0];
2608                         if (tableGuid.equals(guid)) {
2609                                 noteTableView.model.setData(i, Global.noteTableTagPosition,tagBuffer.toString());
2610                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2611                                 return;
2612                         }
2613                 }
2614         }
2615         logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
2616     }
2617     // Update a title for a specific note in the list
2618     @SuppressWarnings("unused")
2619         private void updateListTitle(String guid, String title) {
2620         logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2621
2622         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2623                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2624                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2625                 if (modelIndex != null) {
2626 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2627                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2628                         String tableGuid =  (String)ix.values().toArray()[0];
2629                         if (tableGuid.equals(guid)) {
2630                                 noteTableView.model.setData(i, Global.noteTableTitlePosition,title);
2631                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2632                                 return;
2633                         }       
2634                 }
2635         }
2636         logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2637     }
2638     // Update a title for a specific note in the list
2639     @SuppressWarnings("unused")
2640         private void updateListAuthor(String guid, String author) {
2641         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2642
2643         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2644                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2645                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2646                 if (modelIndex != null) {
2647 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2648                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2649                         String tableGuid =  (String)ix.values().toArray()[0];
2650                         if (tableGuid.equals(guid)) {
2651                                 noteTableView.model.setData(i, Global.noteTableAuthorPosition,author);
2652                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2653                                 return;
2654                         }       
2655                 }
2656         }
2657         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2658     }
2659         private void updateListNoteNotebook(String guid, String notebook) {
2660         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2661
2662         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2663                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2664                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2665                 if (modelIndex != null) {
2666 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2667                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2668                         String tableGuid =  (String)ix.values().toArray()[0];
2669                         if (tableGuid.equals(guid)) {
2670                                 noteTableView.model.setData(i, Global.noteTableNotebookPosition,notebook);
2671                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2672                                 return;
2673                         }       
2674                 }
2675         }
2676         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2677     }
2678     // Update a title for a specific note in the list
2679     @SuppressWarnings("unused")
2680         private void updateListSourceUrl(String guid, String url) {
2681         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2682
2683         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2684                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2685                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2686                 if (modelIndex != null) {
2687 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2688                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2689                         String tableGuid =  (String)ix.values().toArray()[0];
2690                         if (tableGuid.equals(guid)) {
2691                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2692                                 noteTableView.model.setData(i, Global.noteTableSourceUrlPosition,url);
2693                                 return;
2694                         }       
2695                 }
2696         }
2697         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2698     }
2699         private void updateListGuid(String oldGuid, String newGuid) {
2700         logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2701
2702         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2703                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2704                 if (modelIndex != null) {
2705                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2706                         String tableGuid =  (String)ix.values().toArray()[0];
2707                         if (tableGuid.equals(oldGuid)) {
2708                                 noteTableView.model.setData(i, Global.noteTableGuidPosition,newGuid);
2709                                 //noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2710                                 return;
2711                         }       
2712                 }
2713         }
2714         logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2715     }
2716         private void updateListTagName(String guid) {
2717         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2718                 
2719                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2720                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2721                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2722
2723                                 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2724                                         QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2725                                         if (modelIndex != null) {
2726                                                 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2727                                                 String noteGuid = (String)ix.values().toArray()[0];
2728                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2729                                                         noteTableView.model.setData(i, Global.noteTableTagPosition, newName);
2730                                                         //noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2731                                                         i=noteTableView.model.rowCount();
2732                                                 }
2733                                         }
2734                                 }
2735                         }
2736                 }       
2737         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2738     }
2739         private void removeListTagName(String guid) {
2740         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2741                 
2742                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2743                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2744                                 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
2745                                         if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
2746                                                 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
2747                                 }
2748                                 
2749                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2750                                 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2751                                         QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2752                                         if (modelIndex != null) {
2753                                                 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2754                                                 String noteGuid = (String)ix.values().toArray()[0];
2755                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2756                                                         noteTableView.model.setData(i, Global.noteTableTagPosition, newName);
2757 //                                                      noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2758                                                         i=noteTableView.model.rowCount();
2759                                                 }
2760                                         }
2761                                 }
2762                         }
2763                 }       
2764         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2765     }
2766     private void updateListNotebookName(String oldName, String newName) {
2767         logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
2768
2769         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2770                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableNotebookPosition); 
2771                 if (modelIndex != null) {
2772                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2773                         String tableName =  (String)ix.values().toArray()[0];
2774                         if (tableName.equalsIgnoreCase(oldName)) {
2775 //                              noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2776                                 noteTableView.model.setData(i, Global.noteTableNotebookPosition, newName);
2777                         }
2778                 }
2779         }
2780         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
2781     }
2782     @SuppressWarnings("unused")
2783         private void updateListDateCreated(String guid, QDateTime date) {
2784         logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
2785
2786         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2787                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2788                 if (modelIndex != null) {
2789                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2790                         String tableGuid =  (String)ix.values().toArray()[0];
2791                         if (tableGuid.equals(guid)) {
2792                                 noteTableView.model.setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2793                                 return;
2794                         }
2795                 }
2796         }
2797         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2798     }
2799     @SuppressWarnings("unused")
2800         private void updateListDateSubject(String guid, QDateTime date) {
2801         logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
2802
2803         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2804                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2805                 if (modelIndex != null) {
2806                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2807                         String tableGuid =  (String)ix.values().toArray()[0];
2808                         if (tableGuid.equals(guid)) {
2809                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2810                                 noteTableView.model.setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2811                                 return;
2812                         }
2813                 }
2814         }
2815         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2816     }
2817     @SuppressWarnings("unused")
2818         private void updateListDateChanged(String guid, QDateTime date) {
2819         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2820
2821         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2822                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2823                 if (modelIndex != null) {
2824                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2825                         String tableGuid =  (String)ix.values().toArray()[0];
2826                         if (tableGuid.equals(guid)) {
2827                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2828                                 noteTableView.model.setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2829                                 return;
2830                         }
2831                 }
2832         }
2833         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2834     }
2835     private void updateListDateChanged() {
2836         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2837         QDateTime date = new QDateTime(QDateTime.currentDateTime());
2838         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2839                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2840                 if (modelIndex != null) {
2841                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2842                         String tableGuid =  (String)ix.values().toArray()[0];
2843                         if (tableGuid.equals(currentNoteGuid)) {
2844                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2845                                 noteTableView.model.setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2846                                 return;
2847                         }
2848                 }
2849         }
2850         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2851     }  
2852     // Redo scroll
2853     @SuppressWarnings("unused")
2854         private void scrollToCurrentGuid() {
2855         //scrollToGuid(currentNoteGuid);
2856         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2857         if (selections.size() == 0)
2858                 return;
2859         QModelIndex index = selections.get(0);
2860         int row = selections.get(0).row();
2861         String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
2862         scrollToGuid(guid);
2863     }
2864     // Scroll to a particular index item
2865     private void scrollToGuid(String guid) {
2866         if (currentNote == null || guid == null) 
2867                 return;
2868         if (currentNote.isActive() && Global.showDeleted) {
2869                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2870                         if (!listManager.getNoteIndex().get(i).isActive()) {
2871                                 currentNote = listManager.getNoteIndex().get(i);
2872                                 currentNoteGuid =  currentNote.getGuid();
2873                                 i = listManager.getNoteIndex().size();
2874                         }
2875                 }
2876         }
2877         
2878         if (!currentNote.isActive() && !Global.showDeleted) {
2879                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2880                         if (listManager.getNoteIndex().get(i).isActive()) {
2881                                 currentNote = listManager.getNoteIndex().get(i);
2882                                 currentNoteGuid =  currentNote.getGuid();
2883                                 i = listManager.getNoteIndex().size();
2884                         }
2885                 }
2886         }
2887         
2888         QModelIndex index; 
2889         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2890                 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
2891                 if (currentNoteGuid.equals(index.data())) {
2892 //                      noteTableView.setCurrentIndex(index);
2893                         noteTableView.selectRow(i);
2894                         noteTableView.scrollTo(index, ScrollHint.EnsureVisible);  // This should work, but it doesn't
2895                                 i=noteTableView.model.rowCount();
2896                 }
2897         }
2898     }
2899     // Show/Hide columns
2900     private void showColumns() {
2901                 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
2902                 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
2903                 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
2904                 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
2905                 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
2906                 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
2907                 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
2908                 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
2909     }
2910     // Open a separate window
2911     @SuppressWarnings("unused")
2912         private void listDoubleClick() {
2913
2914     }
2915     // Title color has changed
2916     @SuppressWarnings("unused")
2917         private void titleColorChanged(Integer color) {
2918         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2919
2920         QColor backgroundColor = new QColor();
2921                 QColor foregroundColor = new QColor(QColor.black);
2922                 backgroundColor.setRgb(color);
2923                 
2924                 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
2925                         foregroundColor.setRgb(QColor.white.rgb());
2926         
2927                 if (selectedNoteGUIDs.size() == 0)
2928                         selectedNoteGUIDs.add(currentNoteGuid);
2929                 
2930         for (int j=0; j<selectedNoteGUIDs.size(); j++) {
2931                 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2932                         QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2933                         if (modelIndex != null) {
2934                                 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2935                                 String tableGuid =  (String)ix.values().toArray()[0];
2936                                 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
2937                                         for (int k=0; k<Global.noteTableColumnCount; k++) {
2938                                                 noteTableView.model.setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
2939                                                 noteTableView.model.setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
2940                                                 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
2941                                         }
2942                                         i=noteTableView.model.rowCount();
2943                                 }
2944                         }
2945                 }
2946         }
2947         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2948     }
2949     
2950     
2951     //***************************************************************
2952     //***************************************************************
2953     //** These functions deal with Note specific things
2954     //***************************************************************
2955     //***************************************************************    
2956     @SuppressWarnings("unused")
2957         private void setNoteDirty() {
2958                 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
2959         noteDirty = true;
2960
2961         listManager.getUnsynchronizedNotes().add(currentNoteGuid);
2962         for (int i=0; i<noteTableView.model.rowCount(); i++) {
2963                 QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
2964                 if (modelIndex != null) {
2965                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2966                         String tableGuid =  (String)ix.values().toArray()[0];
2967                         if (tableGuid.equals(currentNoteGuid)) {
2968                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2969                                 return;
2970                         }
2971                 }
2972         }
2973                 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
2974     }
2975     private void saveNote() {
2976                 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
2977         if (noteDirty) {
2978                         logger.log(logger.EXTREME, "Note is dirty.");
2979                 waitCursor(true);
2980                 
2981                         preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
2982                         preview.finished.connect(this, "saveThumbnail(String)");
2983                         preview.setContent(browserWindow.getContent());
2984                 
2985                         logger.log(logger.EXTREME, "Saving to cache");
2986                         QTextCodec codec = QTextCodec.codecForLocale();
2987 //              QTextDecoder decoder = codec.makeDecoder();
2988                         codec = QTextCodec.codecForName("UTF-8");
2989                 QByteArray unicode =  codec.fromUnicode(browserWindow.getContent());
2990                 noteCache.put(currentNoteGuid, unicode.toString());
2991                         
2992                 logger.log(logger.EXTREME, "updating list manager");
2993                 listManager.updateNoteContent(currentNoteGuid, browserWindow.getContent());
2994                         logger.log(logger.EXTREME, "Updating title");
2995                 listManager.updateNoteTitle(currentNoteGuid, browserWindow.getTitle());
2996                 updateListDateChanged();
2997
2998                         logger.log(logger.EXTREME, "Looking through note index for refreshed note");
2999                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3000                         if (listManager.getNoteIndex().get(i).getGuid().equals(currentNoteGuid)) {
3001                                 currentNote = listManager.getNoteIndex().get(i);
3002                                 i = listManager.getNoteIndex().size();
3003                         }
3004                 }
3005                 noteDirty = false;
3006                 waitCursor(false);
3007         }
3008     }
3009     // Get a note from Evernote (and put it in the browser)
3010         private void refreshEvernoteNote(boolean reload) {
3011                 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
3012                 if (Global.getDisableViewing()) {
3013                         browserWindow.setEnabled(false);
3014                         return;
3015                 }
3016                 inkNote = false;
3017                 if (!Global.showDeleted)
3018                         browserWindow.setReadOnly(false);
3019                 Global.cryptCounter =0;
3020                 if (currentNoteGuid.equals("")) {
3021                         browserWindow.setReadOnly(true);
3022                         return;
3023                 }
3024                 if (!reload)
3025                         return;
3026                 
3027                 waitCursor(true);
3028                 browserWindow.loadingData(true);
3029
3030                 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
3031                 if (currentNote == null) 
3032                         return;
3033
3034                 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3035                         QByteArray js = new QByteArray();
3036                         // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly 
3037                         js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");               
3038                         js.append("<style type=\"text/css\">en-crypt-temp { border-style:solid; border-color:blue; padding:0.5mm 0.5mm 0.5mm 0.5mm; }</style>");
3039                         js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
3040                         js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
3041                         js.append("</head>");
3042                         js.append(rebuildNoteHTML(currentNoteGuid, currentNote.getContent()));
3043                         js.append("</HTML>");
3044                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
3045                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
3046                         js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
3047                         browserWindow.getBrowser().setContent(js);
3048                         noteCache.put(currentNoteGuid, js.toString());
3049                         if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3050                                 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
3051                                 preview.finished.connect(this, "saveThumbnail(String)");
3052                                 preview.setContent(js.toString());
3053                         }
3054                 } else {
3055                         logger.log(logger.HIGH, "Note content is being pulled from the cache");
3056                         String cachedContent = modifyCachedTodoTags(noteCache.get(currentNoteGuid));
3057                         browserWindow.getBrowser().setContent(new QByteArray(cachedContent));
3058                 }
3059                 
3060                 browserWindow.getBrowser().page().setContentEditable(!inkNote);  // We don't allow editing of ink notes
3061                 browserWindow.setNote(currentNote);
3062                 
3063                 // Build a list of non-closed notebooks
3064                 List<Notebook> nbooks = new ArrayList<Notebook>();
3065                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3066                         boolean found=false;
3067                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3068                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) 
3069                                         found = true;
3070                         }
3071                         if (!found)
3072                                 nbooks.add(listManager.getNotebookIndex().get(i));
3073                 }
3074                 
3075                 browserWindow.setNotebookList(nbooks);
3076                 browserWindow.setTitle(currentNote.getTitle());
3077                 browserWindow.setTag(getTagNamesForNote(currentNote));
3078                 browserWindow.setAuthor(currentNote.getAttributes().getAuthor());
3079                 
3080                 browserWindow.setAltered(currentNote.getUpdated());
3081                 browserWindow.setCreation(currentNote.getCreated());
3082                 if (currentNote.getAttributes().getSubjectDate() > 0)
3083                         browserWindow.setSubjectDate(currentNote.getAttributes().getSubjectDate());
3084                 else
3085                         browserWindow.setSubjectDate(currentNote.getCreated());
3086                 browserWindow.setUrl(currentNote.getAttributes().getSourceURL());
3087                 browserWindow.setAllTags(listManager.getTagIndex());
3088                 browserWindow.setCurrentTags(currentNote.getTagNames());
3089                 noteDirty = false;
3090                 scrollToGuid(currentNoteGuid);
3091                 
3092                 browserWindow.loadingData(false);
3093                 if (thumbnailViewer.isActiveWindow())
3094                         thumbnailView();
3095                 waitCursor(false);
3096                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
3097         }
3098         // Save a generated thumbnail
3099         @SuppressWarnings("unused")
3100         private void saveThumbnail(String guid) {
3101                 QFile tFile = new QFile(Global.getFileManager().getResDirPath("thumbnail-" + guid + ".png"));
3102                 tFile.open(OpenModeFlag.ReadOnly);
3103                 QByteArray imgBytes = tFile.readAll();
3104                 tFile.close();
3105                 conn.getNoteTable().setThumbnail(guid, imgBytes);
3106                 conn.getNoteTable().setThumbnailNeeded(guid, false);
3107                 thumbnailViewer.setThumbnail(QImage.fromData(imgBytes));
3108                 if (thumbnailViewer.isVisible()) 
3109                         thumbnailViewer.showFullScreen();
3110                 
3111                 /*              
3112                 QByteArray img2 = new QByteArray(conn.getNoteTable().getThumbnail(guid));
3113                 QFile file = new QFile(Global.currentDir+"res/aaaa.png");
3114                 file.open(OpenModeFlag.WriteOnly);
3115                 file.write(img2);
3116                 file.close(); 
3117                 */
3118         }
3119     // Show/Hide note information
3120         @SuppressWarnings("unused")
3121         private void toggleNoteInformation() {
3122                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
3123         browserWindow.toggleInformation();
3124         menuBar.noteAttributes.setChecked(browserWindow.isExtended());
3125         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
3126     }
3127         // Listener triggered when a print button is pressed
3128     @SuppressWarnings("unused")
3129         private void printNote() {
3130                 logger.log(logger.HIGH, "Entering NeverNote.printNote");
3131
3132         QPrintDialog dialog = new QPrintDialog();
3133         if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
3134                 QPrinter printer = dialog.printer();
3135                 browserWindow.getBrowser().print(printer);
3136         }
3137                 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
3138
3139     }
3140     // Listener triggered when the email button is pressed
3141     @SuppressWarnings("unused")
3142         private void emailNote() {
3143         logger.log(logger.HIGH, "Entering NeverNote.emailNote");
3144         
3145         if (Desktop.isDesktopSupported()) {
3146             Desktop desktop = Desktop.getDesktop();
3147             
3148             String text2 = browserWindow.getContentsToEmail();
3149             QUrl url = new QUrl("mailto:");
3150             url.addQueryItem("subject", currentNote.getTitle());
3151             url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
3152             QDesktopServices.openUrl(url);
3153         }
3154 /*            
3155             
3156             if (desktop.isSupported(Desktop.Action.MAIL)) {
3157                 URI uriMailTo = null;
3158                 try {
3159                         //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
3160                         String text = browserWindow.getContentsToEmail();
3161                         //text = "<b>" +text +"</b>";
3162                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3163                                                         +"&BODY=" +text, null);
3164                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3165                                                         +"&ATTACHMENT=d:/test.pdf", null);
3166                                         desktop.mail(uriMailTo);
3167                                 } catch (URISyntaxException e) {
3168                                         e.printStackTrace();
3169                                 } catch (IOException e) {
3170                                         e.printStackTrace();
3171                                 }
3172
3173             }
3174
3175         }     
3176  */     
3177         logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
3178     }
3179         // Reindex all notes
3180     @SuppressWarnings("unused")
3181         private void fullReindex() {
3182         logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
3183         // If we are deleting non-trash notes
3184         if (currentNote.getDeleted() == 0) { 
3185                 if (QMessageBox.question(this, "Confirmation", "This will cause all notes & attachments to be reindexed, "+
3186                                 "but please be aware that depending upon the size of your database updating all these records " +
3187                                 "can be time consuming and NeverNote will be unresponsive until it is complete.  Do you wish to continue?",
3188                                 QMessageBox.StandardButton.Yes, 
3189                                         QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3190                                                                 return;
3191                 }
3192         }
3193         waitCursor(true);
3194         setMessage("Marking notes for reindex.");
3195         conn.getNoteTable().reindexAllNotes();
3196         conn.getNoteTable().noteResourceTable.reindexAll(); 
3197         setMessage("Database will be reindexed.");
3198         waitCursor(false);
3199         logger.log(logger.HIGH, "Leaving NeverNote.fullRefresh");
3200     }
3201     // Listener when a user wants to reindex a specific note
3202     @SuppressWarnings("unused")
3203         private void reindexNote() {
3204         logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
3205                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3206                         conn.getNoteTable().setIndexNeeded(selectedNoteGUIDs.get(i), true);
3207                 }
3208                 if (selectedNotebookGUIDs.size() > 1)
3209                         setMessage("Notes will be reindexed.");
3210                 else
3211                         setMessage("Note will be reindexed.");
3212         logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
3213     }
3214     // Delete the note
3215     @SuppressWarnings("unused")
3216         private void deleteNote() {
3217         logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
3218         if (currentNote == null) 
3219                 return;
3220         if (currentNoteGuid.equals(""))
3221                 return;
3222         
3223         // If we are deleting non-trash notes
3224         if (currentNote.isActive()) { 
3225                 if (Global.verifyDelete()) {
3226                         if (QMessageBox.question(this, "Confirmation", "Delete selected note(s)?",
3227                                         QMessageBox.StandardButton.Yes, 
3228                                         QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3229                                         return;
3230                         }
3231                 }
3232                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
3233                         selectedNoteGUIDs.add(currentNoteGuid);
3234                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3235                         listManager.deleteNote(selectedNoteGUIDs.get(i));
3236                 }
3237         } else { 
3238                 // If we are deleting from the trash.
3239                 if (Global.verifyDelete()) {
3240                         if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
3241                                 QMessageBox.StandardButton.Yes, 
3242                                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
3243                                         return;
3244                         }
3245                 }
3246                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
3247                         selectedNoteGUIDs.add(currentNoteGuid);
3248                 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
3249                         for (int j=noteTableView.model.rowCount()-1; j>=0; j--) {
3250                         QModelIndex modelIndex =  noteTableView.model.index(j, Global.noteTableGuidPosition);
3251                         if (modelIndex != null) {
3252                                 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
3253                                 String tableGuid =  (String)ix.values().toArray()[0];
3254                                 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
3255                                         noteTableView.model.removeRow(j);
3256                                         j=-1;
3257                                 }
3258                         }
3259                 }
3260                         listManager.expungeNote(selectedNoteGUIDs.get(i));
3261                 }
3262         }
3263         currentNoteGuid = "";
3264         listManager.loadNotesIndex();
3265         noteIndexUpdated(false);
3266         refreshEvernoteNote(true);
3267         scrollToGuid(currentNoteGuid);
3268         logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
3269     }
3270     // Add a new note
3271     @SuppressWarnings("unused")
3272         private void addNote() {
3273         logger.log(logger.HIGH, "Inside NeverNote.addNote");
3274 //      browserWindow.setEnabled(true);
3275         browserWindow.setReadOnly(false);
3276         saveNote();
3277         Calendar currentTime = new GregorianCalendar();
3278         String noteString = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
3279                 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
3280                 "<en-note>\n<br clear=\"none\" /></en-note>");
3281         
3282         Long l = new Long(currentTime.getTimeInMillis());
3283         String randint = new String(Long.toString(l));
3284         
3285         // Find a notebook.  We first look for a selected notebook (the "All Notebooks" one doesn't count).  
3286         // Then we look
3287         // for the first non-archived notebook.  Finally, if nothing else we 
3288         // pick the first notebook in the list.
3289         String notebook = null;
3290         listManager.getNotebookIndex().get(0).getGuid();
3291         List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
3292         if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
3293                 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
3294                 notebook = currentSelectedNotebook.text(2);
3295         } else {
3296                 boolean found = false;
3297                 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
3298                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3299                         boolean match = false;
3300                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3301                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
3302                                         match = true;
3303                                         j = listManager.getArchiveNotebookIndex().size();
3304                                 }
3305                         }
3306                         if (!match)
3307                                 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
3308                 }
3309                 // Now we have a list of good notebooks, so we can look for the default
3310                 found = false;
3311                 for (int i=0; i<goodNotebooks.size(); i++) {
3312                         if (goodNotebooks.get(i).isDefaultNotebook()) {
3313                                 notebook = goodNotebooks.get(i).getGuid();
3314                                 found = true;
3315                                 i = goodNotebooks.size();
3316                         }
3317                 }
3318                 
3319                 if (goodNotebooks.size() > 0 && !found)
3320                         notebook = goodNotebooks.get(0).getGuid();
3321      
3322                 if (notebook==null)
3323                         notebook = listManager.getNotebookIndex().get(0).getGuid();             
3324         }
3325         
3326         Note newNote = new Note();
3327         newNote.setUpdateSequenceNum(0);
3328         newNote.setGuid(randint);
3329         newNote.setNotebookGuid(notebook);
3330         newNote.setTitle("");
3331         newNote.setContent(noteString);
3332         newNote.setDeleted(0);
3333         newNote.setCreated(System.currentTimeMillis());
3334         newNote.setUpdated(System.currentTimeMillis());
3335         newNote.setActive(true);
3336         NoteAttributes na = new NoteAttributes();
3337         na.setLatitude(0.0);
3338         na.setLongitude(0.0);
3339         na.setAltitude(0.0);
3340         newNote.setAttributes(new NoteAttributes());
3341         conn.getNoteTable().addNote(newNote, true);
3342         listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3343         noteTableView.insertRow(listManager, newNote, true, -1);
3344         
3345         currentNote = newNote;
3346         currentNoteGuid = currentNote.getGuid();
3347         listManager.addNote(newNote);
3348         refreshEvernoteNote(true);
3349         listManager.countNotebookResults(listManager.getNoteIndex());
3350         browserWindow.titleLabel.setFocus();
3351         browserWindow.titleLabel.selectAll();
3352 //      notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
3353         logger.log(logger.HIGH, "Leaving NeverNote.addNote");
3354     }
3355     // Restore a note from the trash;
3356     @SuppressWarnings("unused")
3357         private void restoreNote() {
3358         waitCursor(true);
3359                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
3360                         selectedNoteGUIDs.add(currentNoteGuid);
3361                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3362                         listManager.restoreNote(selectedNoteGUIDs.get(i));
3363                 }
3364         currentNoteGuid = "";
3365         listManager.loadNotesIndex();
3366         noteIndexUpdated(false);
3367         waitCursor(false);
3368     }
3369     // Search a note for specific txt
3370     @SuppressWarnings("unused")
3371         private void findText() {
3372         find.show();
3373         find.setFocusOnTextField();
3374     }
3375     @SuppressWarnings("unused")
3376         private void doFindText() {
3377         browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
3378         find.setFocus();
3379     }
3380     // Signal received that note content has changed.  Normally we just need the guid to remove
3381     // it from the cache.
3382     @SuppressWarnings("unused")
3383         private void invalidateNoteCache(String guid, String content) {
3384         String v = noteCache.remove(guid);
3385         if (content != null) {
3386                 v = noteCache.put(guid, content);
3387         }
3388     }
3389     // Signal received that a note guid has changed
3390     @SuppressWarnings("unused")
3391         private void noteGuidChanged(String oldGuid, String newGuid) {
3392         if (noteCache.containsKey(oldGuid)) {
3393                 String cache = noteCache.get(oldGuid);
3394                 noteCache.put(newGuid, cache);
3395                 noteCache.remove(oldGuid);
3396         }
3397         listManager.updateNoteGuid(oldGuid, newGuid, false);
3398         if (currentNoteGuid.equals(oldGuid)) {
3399                 if (currentNote != null)
3400                         currentNote.setGuid(newGuid);
3401                 currentNoteGuid = newGuid;
3402         }
3403         for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3404                 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
3405                         noteTableView.proxyModel.addGuid(newGuid);
3406                         i=listManager.getNoteIndex().size();
3407                 }
3408         }
3409                 updateListGuid(oldGuid, newGuid);
3410     }
3411     // Toggle the note editor button bar
3412     private void toggleEditorButtonBar() {
3413         if (browserWindow.buttonsVisible) {
3414                 browserWindow.hideButtons();
3415                 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
3416 //              Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3417         } else {
3418                 browserWindow.buttonsVisible = true;
3419                 showEditorButtons();
3420         }
3421         Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3422     }
3423     // Show editor buttons
3424     private void showEditorButtons() {
3425                 browserWindow.undoButton.setVisible(false);
3426                 browserWindow.redoButton.setVisible(false);
3427                 browserWindow.cutButton.setVisible(false);
3428                 browserWindow.copyButton.setVisible(false);
3429                 browserWindow.pasteButton.setVisible(false);
3430                 browserWindow.strikethroughButton.setVisible(false);
3431                 browserWindow.underlineButton.setVisible(false);
3432                 browserWindow.boldButton.setVisible(false);
3433                 browserWindow.italicButton.setVisible(false);
3434                 browserWindow.hlineButton.setVisible(false);
3435                 browserWindow.indentButton.setVisible(false);
3436                 browserWindow.outdentButton.setVisible(false);
3437                 browserWindow.fontList.setVisible(false);
3438                 browserWindow.fontSize.setVisible(false);
3439                 browserWindow.fontColor.setVisible(false);
3440                 browserWindow.fontHilight.setVisible(false);
3441                 browserWindow.leftAlignButton.setVisible(false);
3442                 browserWindow.centerAlignButton.setVisible(false);
3443                 browserWindow.rightAlignButton.setVisible(false);
3444                 browserWindow.indentButton.setVisible(false);
3445                 browserWindow.outdentButton.setVisible(false);
3446
3447                 browserWindow.undoButton.setVisible(Global.isEditorButtonVisible("undo"));
3448                 browserWindow.redoButton.setVisible(Global.isEditorButtonVisible("redo"));
3449                 browserWindow.cutButton.setVisible(Global.isEditorButtonVisible("cut"));
3450                 browserWindow.copyButton.setVisible(Global.isEditorButtonVisible("copy"));
3451                 browserWindow.pasteButton.setVisible(Global.isEditorButtonVisible("paste"));
3452                 browserWindow.strikethroughButton.setVisible(Global.isEditorButtonVisible("strikethrough"));
3453                 browserWindow.underlineButton.setVisible(Global.isEditorButtonVisible("underline"));
3454                 browserWindow.boldButton.setVisible(Global.isEditorButtonVisible("bold"));
3455                 browserWindow.italicButton.setVisible(Global.isEditorButtonVisible("italic"));
3456                 browserWindow.hlineButton.setVisible(Global.isEditorButtonVisible("hline"));
3457                 browserWindow.indentButton.setVisible(Global.isEditorButtonVisible("indent"));
3458                 browserWindow.outdentButton.setVisible(Global.isEditorButtonVisible("outdent"));
3459                 browserWindow.bulletListButton.setVisible(Global.isEditorButtonVisible("bulletList"));
3460                 browserWindow.numberListButton.setVisible(Global.isEditorButtonVisible("numberList"));
3461                 browserWindow.fontList.setVisible(Global.isEditorButtonVisible("font"));
3462                 browserWindow.fontSize.setVisible(Global.isEditorButtonVisible("fontSize"));
3463                 browserWindow.fontColor.setVisible(Global.isEditorButtonVisible("fontColor"));
3464                 browserWindow.fontHilight.setVisible(Global.isEditorButtonVisible("fontHilight"));
3465                 browserWindow.leftAlignButton.setVisible(Global.isEditorButtonVisible("alignLeft"));
3466                 browserWindow.centerAlignButton.setVisible(Global.isEditorButtonVisible("alignCenter"));
3467                 browserWindow.rightAlignButton.setVisible(Global.isEditorButtonVisible("alignRight"));
3468     }
3469     private void duplicateNote(String guid) {
3470                 
3471                 Calendar currentTime = new GregorianCalendar();
3472                 Long l = new Long(currentTime.getTimeInMillis());
3473                 String newGuid = new String(Long.toString(l));
3474                                         
3475                 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
3476                 Note newNote = oldNote.deepCopy();
3477                 newNote.setGuid(newGuid);
3478                 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
3479                 oldNote.setResources(resList);
3480                 duplicateNote(oldNote);
3481         }
3482         private void duplicateNote(Note oldNote) {
3483                 waitCursor(true);
3484                 // Now that we have a good notebook guid, we need to move the conflicting note
3485                 // to the local notebook
3486                 Calendar currentTime = new GregorianCalendar();
3487                 Long l = new Long(currentTime.getTimeInMillis());
3488                 String newGuid = new String(Long.toString(l));
3489                                         
3490                 Note newNote = oldNote.deepCopy();
3491                 newNote.setUpdateSequenceNum(0);
3492                 newNote.setGuid(newGuid);
3493                 newNote.setDeleted(0);
3494                 newNote.setActive(true);
3495                 List<Resource> resList = oldNote.getResources();
3496                 if (resList == null)
3497                         resList = new ArrayList<Resource>();
3498                 long prevGuid = 0;
3499                 for (int i=0; i<resList.size(); i++) {
3500                         l = prevGuid;
3501                         while (l == prevGuid) {
3502                                 currentTime = new GregorianCalendar();
3503                                 l = new Long(currentTime.getTimeInMillis());
3504                         }
3505                         prevGuid = l;
3506                         String newResGuid = new String(Long.toString(l));
3507                         resList.get(i).setNoteGuid(newGuid);
3508                         resList.get(i).setGuid(newResGuid);
3509                         resList.get(i).setUpdateSequenceNum(0);
3510                         resList.get(i).setActive(true);
3511                         conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
3512                 }
3513                 newNote.setResources(resList);
3514                 listManager.addNote(newNote);
3515                 conn.getNoteTable().addNote(newNote, true);
3516                 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3517                 noteTableView.insertRow(listManager, newNote, true, -1);
3518                 listManager.countNotebookResults(listManager.getNoteIndex());
3519                 waitCursor(false);
3520         }
3521         // Merge notes
3522         @SuppressWarnings("unused")
3523         private void mergeNotes() {
3524                 logger.log(logger.HIGH, "Merging notes");
3525                 waitCursor(true);
3526                 saveNote();
3527                 String masterGuid = null;
3528                 List<String> sources = new ArrayList<String>();
3529                 QModelIndex index;
3530                 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
3531                         int r = noteTableView.selectionModel().selectedRows().get(i).row();
3532                         index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
3533                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3534                 if (i == 0) 
3535                         masterGuid = (String)ix.values().toArray()[0];
3536                 else 
3537                         sources.add((String)ix.values().toArray()[0]);  
3538                 }
3539                 
3540                 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
3541                 logger.log(logger.EXTREME, "Children count: "+sources.size());
3542                 mergeNoteContents(masterGuid, sources);
3543                 currentNoteGuid = masterGuid;
3544                 noteIndexUpdated(false);
3545                 refreshEvernoteNote(true);
3546                 waitCursor(false);
3547         }
3548         private void mergeNoteContents(String targetGuid, List<String> sources) {
3549                 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
3550                 String newContent = target.getContent();
3551                 newContent = newContent.replace("</en-note>", "<br></br>");
3552                 
3553                 for (int i=0; i<sources.size(); i++) {
3554                         Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
3555                         if (source.isSetTitle()) {
3556                                 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
3557                         }
3558                         String sourceContent = source.getContent();
3559                         logger.log(logger.EXTREME, "Merging contents into note");
3560                         logger.log(logger.EXTREME, sourceContent);
3561                         logger.log(logger.EXTREME, "End of content");
3562                         int startOfNote = sourceContent.indexOf("<en-note>");
3563                         sourceContent = sourceContent.substring(startOfNote+9);
3564                         int endOfNote = sourceContent.indexOf("</en-note>");
3565                         sourceContent = sourceContent.substring(0,endOfNote);
3566                         newContent = newContent + sourceContent;
3567                         logger.log(logger.EXTREME, "New note content");
3568                         logger.log(logger.EXTREME, newContent);
3569                         logger.log(logger.EXTREME, "End of content");
3570                         for (int j=0; j<source.getResourcesSize(); j++) {
3571                                 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
3572                                 Resource r = source.getResources().get(j);
3573                                 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3574                                 
3575                                 Calendar currentTime = new GregorianCalendar();
3576                                 Long l = new Long(currentTime.getTimeInMillis());
3577                                                         
3578                                 long prevGuid = 0;
3579                                 l = prevGuid;
3580                                 while (l == prevGuid) {
3581                                         currentTime = new GregorianCalendar();
3582                                         l = new Long(currentTime.getTimeInMillis());
3583                                 }
3584                                 String newResGuid = new String(Long.toString(l));
3585                                 newRes.setNoteGuid(targetGuid);
3586                                 newRes.setGuid(newResGuid);
3587                                 newRes.setUpdateSequenceNum(0);
3588                                 newRes.setActive(true);
3589                                 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
3590                         }
3591                 }
3592                 logger.log(logger.EXTREME, "Updating note");
3593                 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
3594                 for (int i=0; i<sources.size(); i++) {
3595                         logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
3596                         listManager.deleteNote(sources.get(i));
3597                 }
3598                 logger.log(logger.EXTREME, "Exiting merge note");
3599         }
3600         // A resource within a note has had a guid change 
3601         @SuppressWarnings("unused")
3602         private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
3603                 if (!oldGuid.equals(newGuid))
3604                         Global.resourceMap.put(oldGuid, newGuid);
3605         }
3606         // View a thumbnail of the note
3607         public void thumbnailView() {
3608                 
3609                 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
3610                 QFile thumbnail = new QFile(thumbnailName);
3611                 if (!thumbnail.exists()) {
3612                         
3613                         QImage img = new QImage();
3614                         img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
3615                         thumbnailViewer.setThumbnail(img);
3616                 } else
3617                         thumbnailViewer.setThumbnail(thumbnailName);
3618                 if (!thumbnailViewer.isVisible()) 
3619                         thumbnailViewer.showFullScreen();
3620         }
3621
3622         //**********************************************************
3623     //**********************************************************
3624     //* Online user actions
3625     //**********************************************************
3626     //**********************************************************
3627     private void setupOnlineMenu() {
3628         if (!Global.isConnected) {
3629                 menuBar.noteOnlineHistoryAction.setEnabled(false);
3630                 return;
3631         } else {
3632                 menuBar.noteOnlineHistoryAction.setEnabled(true);
3633         }
3634     }
3635     @SuppressWarnings("unused")
3636         private void viewNoteHistory() {
3637         if (currentNoteGuid == null || currentNoteGuid.equals("")) 
3638                 return;
3639         if (currentNote.getUpdateSequenceNum() == 0) {
3640                 setMessage("Note has never been synchronized.");
3641                         QMessageBox.information(this, "Error", "This note has never been sent to Evernote, so there is no history.");
3642                         return;
3643         }
3644         
3645         setMessage("Getting Note History");
3646         waitCursor(true);
3647         Note currentOnlineNote = null;
3648         versions = null;
3649         try {
3650                 if (Global.isPremium())
3651                         versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
3652                 else
3653                         versions = new ArrayList<NoteVersionId>();
3654                 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
3655                 } catch (EDAMUserException e) {
3656                         setMessage("EDAMUserException: " +e.getMessage());
3657                         return;
3658                 } catch (EDAMSystemException e) {
3659                         setMessage("EDAMSystemException: " +e.getMessage());
3660                         return;
3661                 } catch (EDAMNotFoundException e) {
3662                         setMessage("Note not found on server.");
3663                         QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
3664                         return;
3665                 } catch (TException e) {
3666                         setMessage("EDAMTransactionException: " +e.getMessage());
3667                         return;
3668                 }
3669                 
3670                 // If we've gotten this far, we have a good note.
3671                 if (historyWindow == null) {
3672                         historyWindow = new OnlineNoteHistory(conn);
3673                         historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
3674                         historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
3675                         historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
3676                 } else {
3677                         historyWindow.historyCombo.clear();
3678                 }
3679                 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
3680                 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
3681                         isDirty = true;
3682                 historyWindow.setCurrent(isDirty);
3683                 
3684                 loadHistoryWindowContent(currentOnlineNote);
3685                 historyWindow.load(versions);
3686                 setMessage("History retrieved");
3687                 waitCursor(false);
3688                 historyWindow.exec();
3689     }
3690     private Note reloadHistoryWindow(String selection) {
3691         waitCursor(true);
3692                 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
3693                 String dateTimeFormat = new String(fmt);
3694                 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
3695                 int index = -1;
3696                 int usn = 0;
3697                 
3698                 for (int i=0; i<versions.size(); i++) {
3699                         StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getServiceUpdated()));
3700                         if (versionDate.toString().equals(selection))
3701                                 index = i;
3702                 }
3703                 
3704                 if (index > -1 || selection.indexOf("Current") > -1) {
3705                         Note historyNote = null;
3706                         try {
3707                                 if (index > -1) {
3708                                         usn = versions.get(index).getUpdateSequenceNum();
3709                                         historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
3710                                 } else
3711                                         historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
3712                         } catch (EDAMUserException e) {
3713                                 setMessage("EDAMUserException: " +e.getMessage());
3714                                 waitCursor(false);
3715                                 return null;
3716                         } catch (EDAMSystemException e) {
3717                                 setMessage("EDAMSystemException: " +e.getMessage());
3718                                 waitCursor(false);
3719                                 return null;
3720                         } catch (EDAMNotFoundException e) {
3721                                 setMessage("EDAMNotFoundException: " +e.getMessage());
3722                                 waitCursor(false);
3723                                 return null;
3724                         } catch (TException e) {
3725                                 setMessage("EDAMTransactionException: " +e.getMessage());
3726                                 waitCursor(false);
3727                                 return null;
3728                         }
3729                         
3730                         waitCursor(false);
3731                         if (historyNote != null) 
3732                                 historyWindow.setContent(historyNote);
3733                         return historyNote;
3734                 }
3735                 waitCursor(false);
3736                 return null;
3737     }
3738     private void loadHistoryWindowContent(Note note) {
3739         note.setUpdateSequenceNum(0);
3740                 historyWindow.setContent(note); 
3741     }
3742     @SuppressWarnings("unused")
3743         private void restoreHistoryNoteAsNew() {
3744         setMessage("Restoring as new note.");
3745         duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
3746         setMessage("Note has been restored as a new note.");
3747     }
3748     @SuppressWarnings("unused")
3749         private void restoreHistoryNote() {
3750         setMessage("Restoring note.");
3751         Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
3752         conn.getNoteTable().expungeNote(n.getGuid(), true, false);
3753         n.setActive(true);
3754         n.setDeleted(0);
3755                 for (int i=0; i<n.getResourcesSize(); i++) {
3756                         n.getResources().get(i).setActive(true);
3757                         conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
3758                 }
3759         listManager.addNote(n);
3760         conn.getNoteTable().addNote(n, true);
3761         refreshEvernoteNote(true);
3762         setMessage("Note has been restored.");
3763     }
3764     
3765     
3766     
3767         //**********************************************************
3768         //**********************************************************
3769         //* XML Modifying methods
3770         //**********************************************************
3771         //**********************************************************
3772     // find the appropriate icon for an attachment
3773     private String findIcon(String appl) {
3774         logger.log(logger.HIGH, "Entering NeverNote.findIcon");
3775         appl = appl.toLowerCase();
3776         String relativePath = appl + ".png";
3777         File f = Global.getFileManager().getImageDirFile(relativePath);
3778         if (f.exists()) {
3779             return relativePath;
3780         }
3781         logger.log(logger.HIGH, "Leaving NeverNote.findIcon");
3782         return "attachment.png";
3783     }
3784     // Modify the en-media tag into an attachment
3785     private void modifyApplicationTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {
3786         logger.log(logger.HIGH, "Entering NeverNote.modifyApplicationTags");
3787         if (appl.equalsIgnoreCase("vnd.evernote.ink"))
3788                 inkNote = true;
3789         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());
3790         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);
3791         if (r == null || r.getData() == null) 
3792                 resourceErrorMessage();
3793                 if (r!= null) {
3794                         if (r.getData()!=null) {
3795                                 // Did we get a generic applicaiton?  Then look at the file name to 
3796                                 // try and find a good application type for the icon
3797                                 if (appl.equalsIgnoreCase("octet-stream")) {
3798                                         if (r.getAttributes() != null && r.getAttributes().getFileName() != null) {
3799                                                 String fn = r.getAttributes().getFileName();
3800                                                 int pos = fn.lastIndexOf(".");
3801                                                 if (pos > -1) {
3802                                                         appl = fn.substring(pos+1);
3803                                                 }
3804                                         }
3805                                 }
3806                                 
3807                                 String fileDetails = null;
3808                                 if (r.getAttributes() != null && r.getAttributes().getFileName() != null && !r.getAttributes().getFileName().equals(""))
3809                                         fileDetails = r.getAttributes().getFileName();
3810                                 String contextFileName;
3811                                 FileManager fileManager = Global.getFileManager();
3812                                 if (fileDetails != null && !fileDetails.equals("")) {
3813                                         enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +fileDetails);
3814                                         contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + fileDetails);
3815                                 } else { 
3816                                         enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +appl);
3817                                         contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + appl);
3818                                 }
3819                                 contextFileName = contextFileName.replace("\\", "/");
3820                                 enmedia.setAttribute("onContextMenu", "window.jambi.resourceContextMenu('" +contextFileName +"');");
3821                                 if (fileDetails == null || fileDetails.equals(""))
3822                                         fileDetails = "";
3823                                 enmedia.setAttribute("en-tag", "en-media");
3824                                 enmedia.setAttribute("guid", r.getGuid());
3825                                 enmedia.setTagName("a");
3826                                 QDomElement newText = doc.createElement("img");
3827                                 boolean goodPreview = false;
3828                                 String filePath = "";
3829                                 if (appl.equalsIgnoreCase("pdf") && Global.pdfPreview()) {
3830                                         String fileName;
3831                                         Resource res = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3832                                         if (res.getAttributes() != null && 
3833                                                         res.getAttributes().getFileName() != null && 
3834                                                         !res.getAttributes().getFileName().trim().equals(""))
3835                                                 fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();
3836                                         else
3837                                                 fileName = res.getGuid()+".pdf";
3838                                         QFile file = new QFile(fileManager.getResDirPath(fileName));
3839                                 QFile.OpenMode mode = new QFile.OpenMode();
3840                                 mode.set(QFile.OpenModeFlag.WriteOnly);
3841                                 file.open(mode);
3842                                 QDataStream out = new QDataStream(file);
3843                                 Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);
3844                                         QByteArray binData = new QByteArray(resBinary.getData().getBody());
3845                                         resBinary = null;
3846                                 out.writeBytes(binData.toByteArray());
3847                                 file.close();
3848                                 PDFPreview pdfPreview = new PDFPreview();
3849                                         goodPreview = pdfPreview.setupPreview(file.fileName(), appl,0);
3850                                         if (goodPreview) {
3851                                                 QDomElement span = doc.createElement("span");
3852                                                 QDomElement table = doc.createElement("table");
3853                                                 span.setAttribute("pdfNavigationTable", "true");
3854                                                 QDomElement tr = doc.createElement("tr");
3855                                                 QDomElement td = doc.createElement("td");
3856                                                 QDomElement left = doc.createElement("img");
3857                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3858                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3859                                                 left.setAttribute("onMouseOver", "style.cursor='hand'");
3860                                                 QDomElement right = doc.createElement("img");
3861                                                 right.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3862                                                 left.setAttribute("onMouseDown", "window.jambi.previousPage('" +file.fileName() +"')");
3863                                                 // NFC TODO: should these be file:// URLs?
3864                                                 left.setAttribute("src", Global.getFileManager().getImageDirPath("small_left.png"));
3865                                                 right.setAttribute("src", Global.getFileManager().getImageDirPath("small_right.png"));
3866                                                 right.setAttribute("onMouseOver", "style.cursor='hand'");
3867                                                 
3868                                                 table.appendChild(tr);
3869                                                 tr.appendChild(td);
3870                                                 td.appendChild(left);
3871                                                 td.appendChild(right);
3872                                                 span.appendChild(table);
3873                                                 enmedia.parentNode().insertBefore(span, enmedia);
3874                                         } 
3875                                         filePath = fileName+".png";
3876                                 }
3877                                 String icon = findIcon(appl);
3878                                 if (icon.equals("attachment.png"))
3879                                         icon = findIcon(fileDetails.substring(fileDetails.indexOf(".")+1));
3880                                 // NFC TODO: should this be a 'file://' URL?
3881                                 newText.setAttribute("src", Global.getFileManager().getImageDirPath(icon));
3882                                 if (goodPreview) {
3883                                         // NFC TODO: should this be a 'file://' URL?
3884                                         newText.setAttribute("src", fileManager.getResDirPath(filePath));
3885                                         newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");
3886                                 }
3887                                 newText.setAttribute("title", fileDetails);
3888                                 enmedia.removeChild(enmedia.firstChild());
3889                                 
3890                                 enmedia.appendChild(newText);
3891                         }
3892                 }
3893                 logger.log(logger.HIGH, "Leaving NeverNote.modifyApplicationTags");
3894     }
3895     // Modify the en-to tag into an input field
3896     private void modifyTodoTags(QDomElement todo) {
3897         logger.log(logger.HIGH, "Entering NeverNote.modifyTodoTags");
3898                 todo.setAttribute("type", "checkbox");
3899                 String checked = todo.attribute("checked");
3900                 todo.removeAttribute("checked");
3901                 if (checked.equalsIgnoreCase("true"))
3902                         todo.setAttribute("checked", "");
3903                 else
3904                         todo.setAttribute("unchecked","");
3905                 todo.setAttribute("value", checked);
3906                 todo.setAttribute("onClick", "value=checked;window.jambi.contentChanged(); ");
3907                 todo.setTagName("input");
3908                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTodoTags");
3909     }
3910     // Modify any cached todo tags that may have changed
3911     private String modifyCachedTodoTags(String note) {
3912         logger.log(logger.HIGH, "Entering NeverNote.modifyCachedTodoTags");
3913         StringBuffer html = new StringBuffer(note);
3914                 for (int i=html.indexOf("<input", 0); i>-1; i=html.indexOf("<input", i)) {
3915                         int endPos =html.indexOf(">",i+1);
3916                         String input = html.substring(i,endPos);
3917                         if (input.indexOf("value=\"true\"") > 0) 
3918                                 input = input.replace("unchecked=\"\"", "checked=\"\"");
3919                         else
3920                                 input = input.replace("checked=\"\"", "unchecked=\"\"");
3921                         html.replace(i, endPos, input);
3922                         i++;
3923                 }
3924                 logger.log(logger.HIGH, "Leaving NeverNote.modifyCachedTodoTags");
3925                 return html.toString();
3926     }
3927     // Modify the en-media tag into an image tag so it can be displayed.
3928     private void modifyImageTags(QDomElement docElem, QDomElement enmedia, QDomAttr hash) {
3929         logger.log(logger.HIGH, "Entering NeverNote.modifyImageTags");
3930         String type = enmedia.attribute("type");
3931         if (type.startsWith("image/"))
3932                 type = "."+type.substring(6);
3933         else
3934                 type="";
3935         
3936         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNoteGuid, hash.value());
3937         QFile tfile = new QFile(Global.getFileManager().getResDirPath(resGuid + type));
3938         if (!tfile.exists()) {
3939                 Resource r = null;
3940                 if (resGuid != null)
3941                         r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid,true);
3942                         if (r==null || r.getData() == null || r.getData().getBody().length == 0)
3943                                 resourceErrorMessage();
3944                         if (r!= null && r.getData() != null && r.getData().getBody().length > 0) {
3945                                 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));
3946                                 QByteArray binData = new QByteArray(r.getData().getBody());
3947                                 tfile.write(binData);
3948                                 tfile.close();
3949                                 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3950                                 enmedia.setAttribute("en-tag", "en-media");
3951                                 enmedia.setNodeValue("");
3952                         enmedia.setAttribute("guid", r.getGuid());
3953                         enmedia.setTagName("img");
3954                 }
3955         }
3956                 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3957                 enmedia.setAttribute("en-tag", "en-media");
3958                 enmedia.setAttribute("onContextMenu", "window.jambi.imageContextMenu('" +tfile.fileName()  +"');");
3959                 enmedia.setNodeValue("");
3960                 enmedia.setAttribute("guid", resGuid);
3961                 enmedia.setTagName("img");
3962
3963                 logger.log(logger.HIGH, "Leaving NeverNote.modifyImageTags");
3964     }
3965         // Modify tags from Evernote specific things to XHTML tags.
3966         private QDomDocument modifyTags(QDomDocument doc) {
3967                 logger.log(logger.HIGH, "Entering NeverNote.modifyTags");
3968                 if (tempFiles == null)
3969                         tempFiles = new ArrayList<QTemporaryFile>();
3970                 tempFiles.clear();
3971                 QDomElement docElem = doc.documentElement();
3972                 
3973                 // Modify en-media tags
3974                 QDomNodeList anchors = docElem.elementsByTagName("en-media");
3975                 int enMediaCount = anchors.length();
3976                 for (int i=enMediaCount-1; i>=0; i--) {
3977                         QDomElement enmedia = anchors.at(i).toElement();
3978                         if (enmedia.hasAttribute("type")) {
3979                                 QDomAttr attr = enmedia.attributeNode("type");
3980                                 QDomAttr hash = enmedia.attributeNode("hash");
3981                                 String[] type = attr.nodeValue().split("/");
3982                                 String appl = type[1];
3983                                 
3984                                 if (type[0] != null) {
3985                                         if (type[0].equals("image")) {
3986                                                 modifyImageTags(docElem, enmedia, hash);
3987                                         }
3988                                         if (!type[0].equals("image")) {
3989                                                 modifyApplicationTags(doc, docElem, enmedia, hash, appl);
3990                                         }
3991                                 }
3992                         }
3993                 }
3994                 
3995                 // Modify todo tags
3996                 anchors = docElem.elementsByTagName("en-todo");
3997                 int enTodoCount = anchors.length();
3998                 for (int i=enTodoCount-1; i>=0; i--) {
3999                         QDomElement enmedia = anchors.at(i).toElement();
4000                         modifyTodoTags(enmedia);
4001                 }
4002                 
4003                 // Modify en-crypt tags
4004                 anchors = docElem.elementsByTagName("en-crypt");
4005                 int enCryptLen = anchors.length();
4006                 for (int i=enCryptLen-1; i>=0; i--) {
4007                         QDomElement enmedia = anchors.at(i).toElement();
4008                         enmedia.setAttribute("contentEditable","false");
4009                         enmedia.setAttribute("src", Global.getFileManager().getImageDirPath("encrypt.png"));
4010                         enmedia.setAttribute("en-tag","en-crypt");
4011                         enmedia.setAttribute("alt", enmedia.text());
4012                         Global.cryptCounter++;
4013                         enmedia.setAttribute("id", "crypt"+Global.cryptCounter.toString());
4014                         String encryptedText = enmedia.text();
4015                         
4016                         // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
4017                         if (encryptedText.endsWith("\n"))
4018                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
4019                         if (encryptedText.endsWith("\r"))
4020                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
4021                         
4022                         // Add the commands
4023                         String hint = enmedia.attribute("hint");
4024                         hint = hint.replace("'","&apos;");
4025                         enmedia.setAttribute("onClick", "window.jambi.decryptText('crypt"+Global.cryptCounter.toString()+"', '"+encryptedText+"', '"+hint+"');");
4026                         enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
4027                         enmedia.setTagName("img");
4028                         enmedia.removeChild(enmedia.firstChild());   // Remove the actual encrypted text
4029                 }
4030
4031                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTags");
4032                 return doc;
4033         }
4034         // Rebuild the note HTML to something usable
4035         private String rebuildNoteHTML(String noteGuid, String note) {
4036                 logger.log(logger.HIGH, "Entering NeverNote.rebuildNoteHTML");
4037                 logger.log(logger.EXTREME, "Note guid: " +noteGuid);
4038                 logger.log(logger.EXTREME, "Note Text:" +note);
4039                 QDomDocument doc = new QDomDocument();
4040                 QDomDocument.Result result = doc.setContent(note);
4041                 if (!result.success) {
4042                         logger.log(logger.MEDIUM, tr("Parse error when rebuilding HTML"));
4043                         logger.log(logger.MEDIUM, tr("Note guid: " +noteGuid));
4044                         logger.log(logger.EXTREME, tr("Start of unmodified note HTML"));
4045                         logger.log(logger.EXTREME, note);
4046                         logger.log(logger.EXTREME, tr("End of unmodified note HTML"));
4047                         return note;
4048                 }
4049
4050                 if (tempFiles == null)
4051                         tempFiles = new ArrayList<QTemporaryFile>();
4052                 tempFiles.clear();
4053                 
4054                 doc = modifyTags(doc);
4055                 doc = addHilight(doc);
4056                 QDomElement docElem = doc.documentElement();
4057                 docElem.setTagName("Body");
4058 //              docElem.setAttribute("bgcolor", "green");
4059                 logger.log(logger.EXTREME, "Rebuilt HTML:");
4060                 logger.log(logger.EXTREME, doc.toString());     
4061                 logger.log(logger.HIGH, "Leaving NeverNote.rebuildNoteHTML");
4062                 // Fix the stupid problem where inserting an <img> tag after an <a> tag (which is done
4063                 // to get the <en-media> application tag to work properly) causes spaces to be inserted
4064                 // between the <a> & <img>.  This messes things up later.  This is an ugly hack.
4065                 StringBuffer html = new StringBuffer(doc.toString());
4066                 for (int i=html.indexOf("<a en-tag=\"en-media\" ", 0); i>-1; i=html.indexOf("<a en-tag=\"en-media\" ", i)) {
4067                         i=html.indexOf(">\n",i+1);
4068                         int z = html.indexOf("<img",i);
4069                         for (int j=z-1; j>i; j--) 
4070                                 html.deleteCharAt(j);
4071                         i=html.indexOf("/>", z+1);
4072                         z = html.indexOf("</a>",i);
4073                         for (int j=z-1; j>i+1; j--) 
4074                                 html.deleteCharAt(j);
4075                 } 
4076                 return html.toString();
4077         }       
4078         // Scan and do hilighting of words
4079         private QDomDocument addHilight(QDomDocument doc) {
4080                 EnSearch e = listManager.getEnSearch();
4081                 if (e.hilightWords == null || e.hilightWords.size() == 0)
4082                         return doc;
4083                 XMLInsertHilight hilight = new XMLInsertHilight(doc, listManager.getEnSearch().hilightWords);
4084                 return hilight.getDoc();
4085         }
4086
4087         // An error has happended fetching a resource.  let the user know
4088         private void resourceErrorMessage() {
4089                 if (inkNote)
4090                         return;
4091                 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4092                 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4093                 "In a perfect world this wouldn't happen, but it has.\n" +
4094                 "It is embarasing when a program like me, designed to save all your\n"+
4095                 "precious data, has a problem finding data.\n\n" +
4096                 "I guess life isn't fair, but I'll survive.  Somehow...\n\n" +
4097                 "In the mean time, I'm not going to let you make changes to this note.\n" +
4098                 "Don't get angry.  I'm doing it to prevent you from messing up\n"+
4099                 "this note on the Evernote servers.  Sorry."+
4100                 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4101                 inkNote = true;
4102 ////            browserWindow.setEnabled(false);
4103                 browserWindow.setReadOnly(true);
4104         }
4105
4106         
4107         
4108         
4109         //**********************************************************
4110         //**********************************************************
4111         //* Timer functions
4112         //**********************************************************
4113         //**********************************************************
4114         // We should now do a sync with Evernote
4115         private void syncTimer() {
4116                 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
4117                 syncRunner.syncNeeded = true;
4118                 syncRunner.disableUploads = Global.disableUploads;
4119                 syncStart();
4120                 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
4121         }
4122         private void syncStart() {
4123                 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
4124                 saveNote();
4125                 if (!syncRunning && Global.isConnected) {
4126                         syncRunner.setConnected(true);
4127                         syncRunner.setKeepRunning(Global.keepRunning);
4128                         syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
4129                         
4130                         if (syncThreadsReady > 0) {
4131                                 saveNoteIndexWidth();
4132                                 if (syncRunner.addWork("SYNC")) {
4133                                         syncRunning = true;
4134                                         syncRunner.syncNeeded = true;
4135                                         syncThreadsReady--;
4136                                 }                               
4137                         }
4138                 }
4139                 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
4140         }
4141         @SuppressWarnings("unused")
4142         private void syncThreadComplete(Boolean refreshNeeded) {
4143                 setMessage("Finalizing Synchronization");
4144                 syncThreadsReady++;
4145                 syncRunning = false;
4146                 syncRunner.syncNeeded = false;
4147                 synchronizeAnimationTimer.stop();
4148                 noteIndexUpdated(true);
4149                 synchronizeButton.setIcon(synchronizeAnimation.get(0));
4150                 saveNote();
4151 //              noteTableView.selectionModel().selectionChanged.disconnect(this, "noteTableSelection()");
4152                 noteTableView.selectionModel().blockSignals(true);
4153                 scrollToGuid(currentNoteGuid);
4154                 noteTableView.selectionModel().blockSignals(false);
4155 //              noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
4156 //              indexRunner.setKeepRunning(Global.keepRunning);
4157                 
4158                 // Reload the unindexed table  If the dbthread is dead, we are probably shutting down.
4159                 if (!dbThread.isAlive())
4160                         return;
4161                 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
4162                 for (int i=0; i<noteTableView.model.rowCount(); i++) {
4163                         QModelIndex modelIndex =  noteTableView.model.index(i, Global.noteTableGuidPosition);
4164                         if (modelIndex != null) {
4165                         SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
4166                                 String tableGuid =  (String)ix.values().toArray()[0];
4167                                 String synch = "true";
4168                                 for (int j=0; j<listManager.getUnsynchronizedNotes().size(); j++) {
4169                                         if (listManager.getUnsynchronizedNotes().get(j).equalsIgnoreCase(tableGuid)) {
4170                                                 synch = "false";
4171                                                 j = listManager.getUnsynchronizedNotes().size();
4172                                         }
4173                                 }
4174                                 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, synch);
4175                         }
4176                 }       
4177                 refreshEvernoteNote(false);
4178                 scrollToGuid(currentNoteGuid);
4179                 setMessage("Synchronization Complete");
4180                 logger.log(logger.MEDIUM, "Sync complete.");
4181         }   
4182 //      public void setSequenceDate(long t) {
4183 //              Global.setSequenceDate(t);
4184 //      }
4185         public void saveUploadAmount(long t) {
4186                 Global.saveUploadAmount(t);
4187         }
4188 //      public void setUpdateSequenceNumber(int t) {
4189 //              Global.setUpdateSequenceNumber(t);
4190 //      }
4191         public void saveUserInformation(User user) {
4192                 Global.saveUserInformation(user);
4193         }
4194         public void saveEvernoteUpdateCount(int i) {
4195                 Global.saveEvernoteUpdateCount(i);
4196         }
4197         public void refreshLists() {
4198                 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
4199                 updateQuotaBar();
4200                 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
4201                 tagIndexUpdated(true);
4202                 notebookIndexUpdated();
4203                 savedSearchIndexUpdated();
4204                 listManager.loadNotesIndex();
4205
4206                 noteTableView.selectionModel().blockSignals(true);
4207         noteIndexUpdated(true);
4208                 noteTableView.selectionModel().blockSignals(false);
4209                 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
4210         }
4211
4212         
4213         @SuppressWarnings("unused")
4214         private void authTimer() {
4215         Calendar cal = Calendar.getInstance();
4216                 
4217         // If we are not connected let's get out of here
4218         if (!Global.isConnected)
4219                 return;
4220                 
4221                 // If this is the first time through, then we need to set this
4222  //             if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime) 
4223 //                      syncRunner.authRefreshTime = cal.getTimeInMillis();
4224                 
4225 //              long now = new Date().getTime();
4226 //              if (now > Global.authRefreshTime && Global.isConnected) {
4227                         syncRunner.authRefreshNeeded = true;
4228                         syncStart();
4229 //              }
4230         }
4231         @SuppressWarnings("unused")
4232         private void authRefreshComplete(boolean goodSync) {
4233                 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
4234                 Global.isConnected = syncRunner.isConnected;
4235                 if (goodSync) {
4236 //                      authTimer.start((int)syncRunner.authTimeRemaining/4);
4237                         authTimer.start(1000*60*15);
4238                         logger.log(logger.LOW, "Authentication token has been renewed");
4239 //                      setMessage("Authentication token has been renewed.");
4240                 } else {
4241                         authTimer.start(1000*60*5);
4242                         logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
4243 //                      setMessage("Authentication token renew has failed - retry in 5 minutes.");
4244                 }
4245                 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
4246         }
4247         
4248         
4249         @SuppressWarnings("unused")
4250         private synchronized void indexTimer() {
4251                 logger.log(logger.EXTREME, "Index timer activated.  Sync running="+syncRunning);
4252                 if (syncRunning) 
4253                         return;
4254                 // Look for any unindexed notes.  We only refresh occasionally 
4255                 // and do one at a time to keep overhead down.
4256                 if (!indexDisabled && indexRunner.getWorkQueueSize() == 0) { 
4257                         List<String> notes = conn.getNoteTable().getNextUnindexed(1);
4258                         String unindexedNote = null;
4259                         if (notes.size() > 0)
4260                                 unindexedNote = notes.get(0);
4261                         if (unindexedNote != null && Global.keepRunning) {
4262                                 indexNoteContent(unindexedNote);
4263                         }
4264                         if (notes.size()>0) {
4265                                 indexTimer.setInterval(100);
4266                                 return;
4267                         }
4268                         List<String> unindexedResources = conn.getNoteTable().noteResourceTable.getNextUnindexed(1);
4269                         if (unindexedResources.size() > 0 && indexRunner.getWorkQueueSize() == 0) {
4270                                 String unindexedResource = unindexedResources.get(0);
4271                                 if (unindexedResource != null && Global.keepRunning) {
4272                                         indexNoteResource(unindexedResource);
4273                                 }
4274                         }
4275                         if (unindexedResources.size() > 0) {
4276                                 indexTimer.setInterval(100);
4277                                 return;
4278                         } else {
4279                                 indexTimer.setInterval(indexTime);
4280                         }
4281                         if (indexRunning) {
4282                                 setMessage("Index completed.");
4283                                 logger.log(logger.LOW, "Indexing has completed.");
4284                                 indexRunning = false;
4285                                 indexTimer.setInterval(indexTime);
4286                         }
4287                 }
4288                 logger.log(logger.EXTREME, "Leaving neverNote index timer");
4289         }
4290         private synchronized void indexNoteContent(String unindexedNote) {
4291                 logger.log(logger.EXTREME, "Entering NeverNote.indexNoteContent()");
4292                 logger.log(logger.MEDIUM, "Unindexed Note found: "+unindexedNote);
4293                 indexRunner.setIndexType(indexRunner.CONTENT);
4294                 indexRunner.addWork("CONTENT "+unindexedNote);
4295                 if (!indexRunning) {
4296                         setMessage("Indexing notes.");
4297                         logger.log(logger.LOW, "Beginning to index note contents.");
4298                         indexRunning = true;
4299                 }
4300                 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteContent()");
4301         }
4302         private synchronized void indexNoteResource(String unindexedResource) {
4303                 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4304                 indexRunner.addWork(new String("RESOURCE "+unindexedResource));
4305                 if (!indexRunning) {
4306                         setMessage("Indexing notes.");
4307                         indexRunning = true;
4308                 }
4309                 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4310         }
4311         @SuppressWarnings("unused")
4312         private void indexThreadComplete(String guid) {
4313                 logger.log(logger.MEDIUM, "Index complete for "+guid);
4314         }
4315         @SuppressWarnings("unused")
4316         private synchronized void toggleNoteIndexing() {
4317                 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
4318                 indexDisabled = !indexDisabled;
4319                 if (!indexDisabled)
4320                         setMessage("Indexing is now enabled.");
4321                 else
4322                         setMessage("Indexing is now disabled.");
4323                 menuBar.disableIndexing.setChecked(indexDisabled);
4324         logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
4325     }  
4326         
4327         @SuppressWarnings("unused")
4328         private void threadMonitorCheck() {
4329                 int MAX=3;
4330                 
4331                 
4332                 boolean alive;
4333                 alive = listManager.threadCheck(Global.tagCounterThreadId);
4334                 if (!alive) {
4335                         tagDeadCount++;
4336                         if (tagDeadCount > MAX)
4337                                 QMessageBox.information(this, "A thread his died.", "It appears as the tag counter thread has died.  I recommend "+
4338                                 "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
4339                 } else
4340                         tagDeadCount=0;
4341                 
4342                 alive = listManager.threadCheck(Global.notebookCounterThreadId);
4343                 if (!alive) {
4344                         notebookThreadDeadCount++;
4345                         QMessageBox.information(this, "A thread his died.", "It appears as the notebook counter thread has died.  I recommend "+
4346                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
4347                 } else
4348                         notebookThreadDeadCount=0;
4349                 
4350                 alive = listManager.threadCheck(Global.trashCounterThreadId);
4351                 if (!alive) {
4352                         trashDeadCount++;
4353                         QMessageBox.information(this, "A thread his died.", "It appears as the trash counter thread has died.  I recommend "+
4354                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
4355                 } else
4356                         trashDeadCount = 0;
4357
4358                 alive = listManager.threadCheck(Global.saveThreadId);
4359                 if (!alive) {
4360                         saveThreadDeadCount++;
4361                         QMessageBox.information(this, "A thread his died.", "It appears as the note saver thread has died.  I recommend "+
4362                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
4363                 } else
4364                         saveThreadDeadCount=0;
4365
4366                 if (!dbThread.isAlive()) {
4367                         dbThreadDeadCount++;
4368                         QMessageBox.information(this, "A thread his died.", "It appears as the database thread has died.  I recommend "+
4369                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
4370                 } else
4371                         dbThreadDeadCount=0;
4372
4373                 if (!syncThread.isAlive()) {
4374                         syncThreadDeadCount++;
4375                         QMessageBox.information(this, "A thread his died.", "It appears as the synchronization thread has died.  I recommend "+
4376                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
4377                 } else
4378                         syncThreadDeadCount=0;
4379
4380                 if (!indexThread.isAlive()) {
4381                         indexThreadDeadCount++;
4382                         QMessageBox.information(this, "A thread his died.", "It appears as the index thread has died.  I recommend "+
4383                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry.");
4384                 } else
4385                         indexThreadDeadCount=0;
4386
4387                 
4388         }
4389
4390         
4391         
4392         //**************************************************
4393         //* Backup & Restore
4394         //**************************************************
4395         @SuppressWarnings("unused")
4396         private void databaseBackup() {
4397                 QFileDialog fd = new QFileDialog(this);
4398                 fd.setFileMode(FileMode.AnyFile);
4399                 fd.setConfirmOverwrite(true);
4400                 fd.setWindowTitle("Backup Database");
4401                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4402                 fd.setAcceptMode(AcceptMode.AcceptSave);
4403                 fd.setDirectory(System.getProperty("user.home"));
4404                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4405                         return;
4406                 }
4407                 
4408                 
4409         waitCursor(true);
4410         setMessage("Backing up database");
4411         saveNote();
4412 //      conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
4413         
4414         ExportData noteWriter = new ExportData(conn, true);
4415         String fileName = fd.selectedFiles().get(0);
4416
4417         if (!fileName.endsWith(".nnex"))
4418                 fileName = fileName +".nnex";
4419         noteWriter.exportData(fileName);
4420         setMessage("Database backup completed.");
4421  
4422
4423         waitCursor(false);
4424         }
4425         @SuppressWarnings("unused")
4426         private void databaseRestore() {
4427                 if (QMessageBox.question(this, "Confirmation",
4428                                 "This is used to restore a database from backups.\n" +
4429                                 "It is HIGHLY recommened that this only be used to populate\n" +
4430                                 "an empty database.  Restoring into a database that\n already has data" +
4431                                 " can cause problems.\n\nAre you sure you want to continue?",
4432                                 QMessageBox.StandardButton.Yes, 
4433                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4434                                         return;
4435                                 }
4436                 
4437                 
4438                 QFileDialog fd = new QFileDialog(this);
4439                 fd.setFileMode(FileMode.ExistingFile);
4440                 fd.setConfirmOverwrite(true);
4441                 fd.setWindowTitle("Restore Database");
4442                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4443                 fd.setAcceptMode(AcceptMode.AcceptOpen);
4444                 fd.setDirectory(System.getProperty("user.home"));
4445                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4446                         return;
4447                 }
4448                 
4449                 
4450                 waitCursor(true);
4451                 setMessage("Restoring database");
4452         ImportData noteReader = new ImportData(conn, true);
4453         noteReader.importData(fd.selectedFiles().get(0));
4454         
4455         if (noteReader.lastError != 0) {
4456                 setMessage(noteReader.getErrorMessage());
4457                 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
4458                 waitCursor(false);
4459                 return;
4460         }
4461         
4462         listManager.loadNoteTitleColors();
4463         refreshLists();
4464         refreshEvernoteNote(true);
4465         setMessage("Database has been restored.");
4466         waitCursor(false);
4467         }
4468         @SuppressWarnings("unused")
4469         private void exportNotes() {
4470                 QFileDialog fd = new QFileDialog(this);
4471                 fd.setFileMode(FileMode.AnyFile);
4472                 fd.setConfirmOverwrite(true);
4473                 fd.setWindowTitle("Backup Database");
4474                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4475                 fd.setAcceptMode(AcceptMode.AcceptSave);
4476                 fd.setDirectory(System.getProperty("user.home"));
4477                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4478                         return;
4479                 }
4480                 
4481                 
4482         waitCursor(true);
4483         setMessage("Exporting Notes");
4484         saveNote();
4485         
4486                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
4487                         selectedNoteGUIDs.add(currentNoteGuid);
4488                 
4489         ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
4490         String fileName = fd.selectedFiles().get(0);
4491
4492         if (!fileName.endsWith(".nnex"))
4493                 fileName = fileName +".nnex";
4494         noteWriter.exportData(fileName);
4495         setMessage("Export completed.");
4496  
4497
4498         waitCursor(false);
4499                 
4500         }
4501         @SuppressWarnings("unused")
4502         private void importNotes() {
4503                 QFileDialog fd = new QFileDialog(this);
4504                 fd.setFileMode(FileMode.ExistingFile);
4505                 fd.setConfirmOverwrite(true);
4506                 fd.setWindowTitle("Import Notes");
4507                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4508                 fd.setAcceptMode(AcceptMode.AcceptOpen);
4509                 fd.setDirectory(System.getProperty("user.home"));
4510                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4511                         return;
4512                 }
4513                 
4514                 
4515         waitCursor(true);
4516         setMessage("Importing Notes");
4517         saveNote();
4518         
4519                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
4520                         selectedNoteGUIDs.add(currentNoteGuid);
4521                 
4522         ImportData noteReader = new ImportData(conn, false);
4523         String fileName = fd.selectedFiles().get(0);
4524
4525         if (!fileName.endsWith(".nnex"))
4526                 fileName = fileName +".nnex";
4527         if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0) 
4528                 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
4529         else
4530                 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
4531   
4532         noteReader.importData(fileName);
4533         
4534         if (noteReader.lastError != 0) {
4535                 setMessage(noteReader.getErrorMessage());
4536                 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
4537                 waitCursor(false);
4538                 return;
4539         }
4540         
4541         listManager.loadNoteTitleColors();
4542         refreshLists();
4543         refreshEvernoteNote(false);
4544         setMessage("Notes have been imported.");
4545         waitCursor(false);
4546         
4547         setMessage("Import completed.");
4548  
4549
4550         waitCursor(false);
4551                 
4552         }
4553         
4554         //**************************************************
4555         //* Duplicate a note 
4556         //**************************************************
4557         @SuppressWarnings("unused")
4558         private void duplicateNote() {
4559                 saveNote();
4560                 duplicateNote(currentNoteGuid);
4561         }
4562
4563         
4564         
4565         //**************************************************
4566         //* Folder Imports
4567         //**************************************************
4568         public void setupFolderImports() {
4569                 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
4570                 
4571                 if (importKeepWatcher == null)
4572                         importKeepWatcher = new QFileSystemWatcher();
4573                 if (importDeleteWatcher == null) {
4574                         importDeleteWatcher = new QFileSystemWatcher();
4575                         for (int i=0; i<records.size(); i++) {
4576                                 if (!records.get(i).keep)
4577                                         folderImportDelete(records.get(i).folder); 
4578                         }
4579                 }
4580
4581                                 
4582                 
4583 //              importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
4584                 for (int i=0; i<records.size(); i++) {
4585                         if (records.get(i).keep) 
4586                                 importKeepWatcher.addPath(records.get(i).folder);
4587                         else
4588                                 importDeleteWatcher.addPath(records.get(i).folder);
4589                 }
4590                 
4591                 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
4592                 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
4593                 
4594                 // Look at the files already there so we don't import them again if a new file is created
4595                 if (importedFiles == null) {
4596                         importedFiles = new ArrayList<String>();
4597                         for (int j=0; j<records.size(); j++) {
4598                                 QDir dir = new QDir(records.get(j).folder);
4599                                 List<QFileInfo> list = dir.entryInfoList();
4600                                 for (int k=0; k<list.size(); k++) {
4601                                         if (list.get(k).isFile())
4602                                                 importedFiles.add(list.get(k).absoluteFilePath());
4603                                 }
4604                         }
4605                 }
4606         }
4607         public void folderImport() {
4608                 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
4609                 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
4610                 dialog.exec();
4611                 if (!dialog.okClicked())
4612                         return;
4613                 
4614                 // We have some sort of update.
4615                 if (importKeepWatcher.directories().size() > 0)
4616                         importKeepWatcher.removePaths(importKeepWatcher.directories());
4617                 if (importDeleteWatcher.directories().size() > 0)
4618                         importDeleteWatcher.removePaths(importDeleteWatcher.directories());
4619                 
4620                 conn.getWatchFolderTable().expungeAll();
4621                 // Start building from the table
4622                 for (int i=0; i<dialog.table.rowCount(); i++) {
4623                         QTableWidgetItem item = dialog.table.item(i, 0);
4624                         String dir = item.text();
4625                         item = dialog.table.item(i, 1);
4626                         String notebook = item.text();
4627                         item = dialog.table.item(i, 2);
4628                         boolean keep;
4629                         if (item.text().equalsIgnoreCase("Keep"))
4630                                 keep = true;
4631                         else
4632                                 keep = false;
4633                         
4634                         String guid = conn.getNotebookTable().findNotebookByName(notebook);
4635                         conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
4636                 }
4637                 setupFolderImports();
4638         }
4639         
4640         public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
4641                 
4642                 String whichOS = System.getProperty("os.name");
4643                 if (whichOS.contains("Windows")) 
4644                         dirName = dirName.replace('/','\\');
4645                 
4646                 FileImporter importer = new FileImporter(logger, conn);
4647                 
4648                 QDir dir = new QDir(dirName);
4649                 List<QFileInfo> list = dir.entryInfoList();
4650                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4651
4652                 for (int i=0; i<list.size(); i++){
4653                         
4654                         boolean redundant = false;
4655                         // Check if we've already imported this one or if it existed before
4656                         for (int j=0; j<importedFiles.size(); j++) {
4657                                 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
4658                                         redundant = true;
4659                         }
4660                         
4661                         if (!redundant) {
4662                                 importer.setFileInfo(list.get(i));
4663                                 importer.setFileName(list.get(i).absoluteFilePath());
4664                         
4665                         
4666                                 if (list.get(i).isFile() && importer.isValidType()) {
4667                         
4668                                         if (!importer.importFile()) {
4669                                                 // If we can't get to the file, it is probably locked.  We'll try again later.
4670                                                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4671                                                 importFilesKeep.add(list.get(i).absoluteFilePath());
4672                                                 return;
4673                                         }
4674
4675                                         Note newNote = importer.getNote();
4676                                         newNote.setNotebookGuid(notebook);
4677                                         newNote.setTitle(dir.at(i));
4678                                         listManager.addNote(newNote);
4679                                         conn.getNoteTable().addNote(newNote, true);
4680                                         listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4681                                         noteTableView.insertRow(listManager, newNote, true, -1);
4682                                         listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4683                                         listManager.countNotebookResults(listManager.getNoteIndex());
4684                                         importedFiles.add(list.get(i).absoluteFilePath());
4685                                 }
4686                         }
4687                 }
4688         
4689         
4690         }
4691         
4692         public void folderImportDelete(String dirName) {
4693                 
4694                 String whichOS = System.getProperty("os.name");
4695                 if (whichOS.contains("Windows")) 
4696                         dirName = dirName.replace('/','\\');
4697                 
4698                 FileImporter importer = new FileImporter(logger, conn);
4699                 QDir dir = new QDir(dirName);
4700                 List<QFileInfo> list = dir.entryInfoList();
4701                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4702                 
4703                 for (int i=0; i<list.size(); i++){
4704                         importer.setFileInfo(list.get(i));
4705                         importer.setFileName(list.get(i).absoluteFilePath());
4706                         
4707                         if (list.get(i).isFile() && importer.isValidType()) {
4708                 
4709                                 if (!importer.importFile()) {
4710                                         // If we can't get to the file, it is probably locked.  We'll try again later.
4711                                         logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4712                                         importFilesKeep.add(list.get(i).absoluteFilePath());
4713                                         return;
4714                                 }
4715                 
4716                                 Note newNote = importer.getNote();
4717                                 newNote.setNotebookGuid(notebook);
4718                                 newNote.setTitle(dir.at(i));
4719                                 listManager.addNote(newNote);
4720                                 conn.getNoteTable().addNote(newNote, true);
4721                                 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4722                                 noteTableView.insertRow(listManager, newNote, true, -1);
4723                                 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4724                                 listManager.countNotebookResults(listManager.getNoteIndex());
4725                                 dir.remove(dir.at(i));
4726                         }
4727                 }
4728         }
4729         
4730         
4731         //**************************************************
4732         //* External events
4733         //**************************************************
4734         private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
4735                 logger.log(logger.HIGH, "Entering exernalFileEdited");
4736
4737                 // Strip URL prefix and base dir path
4738                 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
4739                 String name = fileName.replace(dPath, "");
4740
4741                 int pos = name.lastIndexOf('.');
4742                 String guid = name;
4743                 if (pos > -1) {
4744                         guid = guid.substring(0,pos);
4745                 }
4746                 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
4747                 if (pos > -1) {
4748                         guid = name.substring(0, pos);
4749                 }
4750                 
4751                 QFile file = new QFile(fileName);
4752         if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
4753                 // If we can't get to the file, it is probably locked.  We'll try again later.
4754                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4755                 externalFiles.add(fileName);
4756                 return;
4757                 }
4758                 QByteArray binData = file.readAll();
4759         file.close();
4760         if (binData.size() == 0) {
4761                 // If we can't get to the file, it is probably locked.  We'll try again later.
4762                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4763                 externalFiles.add(fileName);
4764                 return;
4765         }
4766         
4767         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
4768         if (r==null)
4769                 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
4770         if (r == null || r.getData() == null || r.getData().getBody() == null)
4771                 return;
4772         String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
4773         MessageDigest md = MessageDigest.getInstance("MD5");
4774                 md.update(binData.toByteArray());
4775                 byte[] hash = md.digest();
4776         String newHash = Global.byteArrayToHexString(hash);
4777         if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
4778                 updateResourceContentHash(r.getGuid(), oldHash, newHash);
4779         }
4780         conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
4781         Data data = r.getData();
4782         data.setBody(binData.toByteArray());
4783         data.setBodyHash(hash);
4784         logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
4785         r.setData(data);
4786         conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
4787         
4788         if (r.getNoteGuid().equals(currentNoteGuid)) {
4789                         QWebSettings.setMaximumPagesInCache(0);
4790                         QWebSettings.setObjectCacheCapacities(0, 0, 0);
4791                         refreshEvernoteNote(true);
4792                         browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
4793         }
4794         
4795                 logger.log(logger.HIGH, "Exiting externalFielEdited");
4796         }
4797         // This is a timer event that tries to save any external files that were edited.  This
4798         // is only needed if we couldn't save a file earlier.
4799         public void externalFileEditedSaver() {
4800                 for (int i=externalFiles.size()-1; i>=0; i--) {
4801                         try {
4802                                 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
4803                                 externalFileEdited(externalFiles.get(i));
4804                                 externalFiles.remove(i);
4805                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4806                 }
4807                 for (int i=0; i<importFilesKeep.size(); i++) {
4808                         try {
4809                                 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
4810                                 folderImportKeep(importFilesKeep.get(i));
4811                                 importFilesKeep.remove(i);
4812                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4813                 }
4814                 for (int i=0; i<importFilesDelete.size(); i++) {
4815                         logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
4816                         folderImportDelete(importFilesDelete.get(i));
4817                         importFilesDelete.remove(i);
4818                 }
4819         }
4820         
4821         
4822         
4823         
4824         // If an attachment on the current note was edited, we need to update the current notes's hash
4825         // Update a note content's hash.  This happens if a resource is edited outside of NN
4826         public void updateResourceContentHash(String guid, String oldHash, String newHash) {
4827                 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
4828                 int endPos;
4829                 for (;position>-1;) {
4830                         endPos = browserWindow.getContent().indexOf(">", position+1);
4831                         String oldSegment = browserWindow.getContent().substring(position,endPos);
4832                         int hashPos = oldSegment.indexOf("hash=\"");
4833                         int hashEnd = oldSegment.indexOf("\"", hashPos+7);
4834                         String hash = oldSegment.substring(hashPos+6, hashEnd);
4835                         if (hash.equalsIgnoreCase(oldHash)) {
4836                                 String newSegment = oldSegment.replace(oldHash, newHash);
4837                                 String content = browserWindow.getContent().substring(0,position) +
4838                                                  newSegment +
4839                                                  browserWindow.getContent().substring(endPos);
4840                                 browserWindow.getBrowser().setContent(new QByteArray(content));;
4841                         }
4842                         
4843                         position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
4844                 }
4845         }
4846
4847
4848         
4849         
4850         //*************************************************
4851         //* Check database userid & passwords
4852         //*************************************************
4853         public boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
4854                         Connection connection;
4855                         
4856                         try {
4857                                 Class.forName("org.h2.Driver");
4858                         } catch (ClassNotFoundException e1) {
4859                                 e1.printStackTrace();
4860                                 System.exit(16);
4861                         }
4862
4863                         try {
4864                                 String passwordString = null;
4865                                 if (cypherPassword==null || cypherPassword.trim().equals(""))
4866                                         passwordString = userPassword;
4867                                 else
4868                                         passwordString = cypherPassword+" "+userPassword;
4869                                 connection = DriverManager.getConnection(url,userid,passwordString);
4870                         } catch (SQLException e) {
4871                                 return false;
4872                         }
4873                         try {
4874                                 connection.close();
4875                         } catch (SQLException e) {
4876                                 e.printStackTrace();
4877                         }
4878                         return true;
4879         }
4880
4881 }