OSDN Git Service

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