OSDN Git Service

Moved the show/hide of the note index column from the Edit/Preferences menu to a...
[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.QCursor;
89 import com.trolltech.qt.gui.QDesktopServices;
90 import com.trolltech.qt.gui.QDialog;
91 import com.trolltech.qt.gui.QFileDialog;
92 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
93 import com.trolltech.qt.gui.QFileDialog.FileMode;
94 import com.trolltech.qt.gui.QGridLayout;
95 import com.trolltech.qt.gui.QHBoxLayout;
96 import com.trolltech.qt.gui.QIcon;
97 import com.trolltech.qt.gui.QImage;
98 import com.trolltech.qt.gui.QLabel;
99 import com.trolltech.qt.gui.QListWidget;
100 import com.trolltech.qt.gui.QMainWindow;
101 import com.trolltech.qt.gui.QMenu;
102 import com.trolltech.qt.gui.QMessageBox;
103 import com.trolltech.qt.gui.QMessageBox.StandardButton;
104 import com.trolltech.qt.gui.QPixmap;
105 import com.trolltech.qt.gui.QPrintDialog;
106 import com.trolltech.qt.gui.QPrinter;
107 import com.trolltech.qt.gui.QProgressBar;
108 import com.trolltech.qt.gui.QSizePolicy;
109 import com.trolltech.qt.gui.QSizePolicy.Policy;
110 import com.trolltech.qt.gui.QSpinBox;
111 import com.trolltech.qt.gui.QSplashScreen;
112 import com.trolltech.qt.gui.QSplitter;
113 import com.trolltech.qt.gui.QStatusBar;
114 import com.trolltech.qt.gui.QSystemTrayIcon;
115 import com.trolltech.qt.gui.QTableWidgetItem;
116 import com.trolltech.qt.gui.QTextEdit;
117 import com.trolltech.qt.gui.QToolBar;
118 import com.trolltech.qt.gui.QTreeWidgetItem;
119 import com.trolltech.qt.webkit.QWebPage.WebAction;
120 import com.trolltech.qt.webkit.QWebSettings;
121 import com.trolltech.qt.xml.QDomAttr;
122 import com.trolltech.qt.xml.QDomDocument;
123 import com.trolltech.qt.xml.QDomElement;
124 import com.trolltech.qt.xml.QDomNodeList;
125
126 import cx.fbn.nevernote.config.FileManager;
127 import cx.fbn.nevernote.config.InitializationException;
128 import cx.fbn.nevernote.config.StartupConfig;
129 import cx.fbn.nevernote.dialog.AccountDialog;
130 import cx.fbn.nevernote.dialog.ConfigDialog;
131 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
132 import cx.fbn.nevernote.dialog.DatabaseStatus;
133 import cx.fbn.nevernote.dialog.FindDialog;
134 import cx.fbn.nevernote.dialog.LoginDialog;
135 import cx.fbn.nevernote.dialog.NotebookArchive;
136 import cx.fbn.nevernote.dialog.NotebookEdit;
137 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
138 import cx.fbn.nevernote.dialog.SavedSearchEdit;
139 import cx.fbn.nevernote.dialog.TagEdit;
140 import cx.fbn.nevernote.dialog.ThumbnailViewer;
141 import cx.fbn.nevernote.dialog.WatchFolder;
142 import cx.fbn.nevernote.filters.EnSearch;
143 import cx.fbn.nevernote.gui.AttributeTreeWidget;
144 import cx.fbn.nevernote.gui.BrowserWindow;
145 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
146 import cx.fbn.nevernote.gui.MainMenuBar;
147 import cx.fbn.nevernote.gui.NotebookTreeWidget;
148 import cx.fbn.nevernote.gui.PDFPreview;
149 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
150 import cx.fbn.nevernote.gui.TableView;
151 import cx.fbn.nevernote.gui.TagTreeWidget;
152 import cx.fbn.nevernote.gui.Thumbnailer;
153 import cx.fbn.nevernote.gui.TrashTreeWidget;
154 import cx.fbn.nevernote.sql.DatabaseConnection;
155 import cx.fbn.nevernote.sql.WatchFolderRecord;
156 import cx.fbn.nevernote.threads.IndexRunner;
157 import cx.fbn.nevernote.threads.SyncRunner;
158 import cx.fbn.nevernote.utilities.AESEncrypter;
159 import cx.fbn.nevernote.utilities.ApplicationLogger;
160 import cx.fbn.nevernote.utilities.FileImporter;
161 import cx.fbn.nevernote.utilities.FileUtils;
162 import cx.fbn.nevernote.utilities.ListManager;
163 import cx.fbn.nevernote.utilities.SyncTimes;
164 import cx.fbn.nevernote.xml.ExportData;
165 import cx.fbn.nevernote.xml.ImportData;
166 import cx.fbn.nevernote.xml.XMLInsertHilight;
167
168
169 public class NeverNote extends QMainWindow{
170         
171         QStatusBar                              statusBar;                                      // Application status bar
172         
173         DatabaseConnection              conn;
174         
175         MainMenuBar                             menuBar;                                        // Main menu bar
176         FindDialog                              find;                                           // Text search in note dialog
177         List<String>                    emitLog;                                        // Messages displayed in the status bar;
178         QSystemTrayIcon                 trayIcon;                                       // little tray icon
179         QMenu                                   trayMenu;                                       // System tray menu
180         QAction                                 trayExitAction;                         // Exit the application
181         QAction                                 trayShowAction;                         // toggle the show/hide action          
182         QAction                                 trayAddNoteAction;                      // Add a note from the system tray
183         
184     NotebookTreeWidget          notebookTree;                           // List of notebooks
185     AttributeTreeWidget         attributeTree;                          // List of note attributes
186     TagTreeWidget                       tagTree;                                        // list of user created tags
187     SavedSearchTreeWidget       savedSearchTree;                        // list of saved searches
188     TrashTreeWidget                     trashTree;                                      // Trashcan
189     TableView                           noteTableView;                          //      List of notes (the widget).
190
191     public BrowserWindow        browserWindow;                          // Window containing browser & labels
192     QToolBar                            toolBar;                                        // The tool bar under the menu
193 //    QLineEdit                                 searchField;                            // The search filter bar on the toolbar
194     QComboBox                           searchField;                            // search filter bar on the toolbar;
195     boolean                                     searchPerformed = false;        // Search was done?
196     QProgressBar                        quotaBar;                                       // The current quota usage
197     
198     ApplicationLogger           logger;
199     List<String>                        selectedNotebookGUIDs;          // List of notebook GUIDs
200     List<String>                        selectedTagGUIDs;                       // List of selected tag GUIDs
201     List<String>                        selectedNoteGUIDs;                      // List of selected notes
202     String                                      selectedSavedSearchGUID;        // Currently selected saved searches
203     
204     NoteFilter                          filter;                                         // Note filter
205     String                                      currentNoteGuid;                        // GUID of the current note 
206     Note                                        currentNote;                            // The currently viewed note
207     boolean                                     noteDirty;                                      // Has the note been changed?
208     boolean                             inkNote;                    // if this is an ink note, it is read only
209   
210     ListManager                         listManager;                                    // DB runnable task
211     
212     List<QTemporaryFile>        tempFiles;                                      // Array of temporary files;
213     
214     QTimer                                      indexTimer;                                     // timer to start the index thread
215     IndexRunner                         indexRunner;                            // thread to index notes
216     QThread                                     indexThread;
217     
218     QTimer                                      syncTimer;                                      // Sync on an interval
219     QTimer                                      syncDelayTimer;                         // Sync delay to free up database
220     SyncRunner                          syncRunner;                                     // thread to do a sync.
221     QThread                                     syncThread;
222     QTimer                                      saveTimer;                                      // Timer to save note contents
223     
224     QTimer                                      authTimer;                                      // Refresh authentication
225     QTimer                                      externalFileSaveTimer;          // Save files altered externally
226     List<String>                        externalFiles;                          // External files to save later
227     List<String>                        importFilesKeep;                        // Auto-import files to save later
228     List<String>                        importFilesDelete;                      // Auto-import files to save later
229     
230     int                                         indexTime;                                      // how often to try and index
231     boolean                                     indexRunning;                           // Is indexing running?
232     boolean                                     indexDisabled;                          // Is indexing disabled?
233     
234     int                                         syncThreadsReady;                       // number of sync threads that are free
235     int                                         syncTime;                                       // Sync interval
236     boolean                                     syncRunning;                            // Is sync running?
237     boolean                                     automaticSync;                          // do sync automatically?
238     QTreeWidgetItem                     attributeTreeSelected;
239
240     QAction                             prevButton;                                     // Go to the previous item viewed
241     QAction                             nextButton;                                     // Go to the next item in the history
242     QAction                             downButton;                                     // Go to the next item in the list
243     QAction                             upButton;                                       // Go to the prev. item in the list;
244     QAction                             synchronizeButton;                      // Synchronize with Evernote
245     List<QIcon>                 synchronizeAnimation;           // Synchronize movie
246     QTimer                              synchronizeAnimationTimer;      // Timer to change animation button
247     int                                 synchronizeFrame;                       // Current frame being viewed
248     QAction                     printButton;                            // Print Button
249     QAction                             tagButton;                                      // Tag edit button
250     QAction                             attributeButton;                        // Attribute information button
251     QAction                     emailButton;                            // Email button
252     QAction                     deleteButton;                           // Delete button
253     QAction                             newButton;                                      // new Note Button;
254     QSpinBox                    zoomSpinner;                            // Zoom zoom
255     QAction                             searchClearButton;                      // Clear the search field
256     
257     QSplitter                   mainLeftRightSplitter;          // main splitter for left/right side
258     QSplitter                   leftSplitter1;                          // first left hand splitter
259     QSplitter                   browserIndexSplitter;           // splitter between note index & note text
260     
261     QFileSystemWatcher  importKeepWatcher;                      // Watch & keep auto-import
262     QFileSystemWatcher  importDeleteWatcher;            // Watch & Delete auto-import
263     List<String>                importedFiles;                          // History of imported files (so we don't import twice)
264     
265     OnlineNoteHistory   historyWindow;                          // online history window 
266     List<NoteVersionId> versions;                                       // history versions
267     
268     QTimer                              threadMonitorTimer;                     // Timer to watch threads.
269     int                                 dbThreadDeadCount=0;            // number of consecutive dead times for the db thread
270     int                                 syncThreadDeadCount=0;          // number of consecutive dead times for the sync thread
271     int                                 indexThreadDeadCount=0;         // number of consecutive dead times for the index thread
272     int                                 notebookThreadDeadCount=0;      // number of consecutive dead times for the notebook thread
273     int                                 tagDeadCount=0;                         // number of consecutive dead times for the tag thread
274     int                                 trashDeadCount=0;                       // number of consecutive dead times for the trash thread
275     int                                 saveThreadDeadCount=0;          // number of consecutive dead times for the save thread
276     
277     HashMap<String, String>             noteCache;                      // Cash of note content 
278     List<String>                historyGuids;                           // GUIDs of previously viewed items
279     int                                 historyPosition;                        // Position within the viewed items
280     boolean                             fromHistory;                            // Is this from the history queue?
281     String                              trashNoteGuid;                          // Guid to restore / set into or out of trash to save position
282     Thumbnailer                 preview;                                        // generate preview image
283     ThumbnailViewer             thumbnailViewer;                        // View preview thumbnail; 
284     
285     String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
286         
287         
288     //***************************************************************
289     //***************************************************************
290     //** Constructor & main entry point
291     //***************************************************************
292     //***************************************************************
293     // Application Constructor  
294         public NeverNote(DatabaseConnection dbConn)  {
295                 conn = dbConn;          
296
297                 thread().setPriority(Thread.MAX_PRIORITY);
298                 
299                 logger = new ApplicationLogger("nevernote.log");
300                 logger.log(logger.HIGH, "Starting Application");
301
302                 conn.checkDatabaseVersion();
303                 
304                 // Start building the invalid XML tables
305                 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
306                 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
307                 
308                 for (int i=0; i<elements.size(); i++) {
309                         Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
310                 }
311                 
312                 logger.log(logger.EXTREME, "Starting GUI build");
313
314                 QTranslator qtTranslator = new QTranslator();
315                 qtTranslator.load("classpath:/translations/qt_" + QLocale.system().name() + ".qm");
316                 QApplication.instance().installTranslator(qtTranslator);
317
318                 QTranslator nevernoteTranslator = new QTranslator();
319                 nevernoteTranslator.load("classpath:/translations/nevernote_"+QLocale.system().name()+ ".qm");
320                 QApplication.instance().installTranslator(nevernoteTranslator);
321
322                 Global.originalPalette = QApplication.palette();
323                 QApplication.setStyle(Global.getStyle());
324                 if (Global.useStandardPalette())
325                         QApplication.setPalette(QApplication.style().standardPalette());
326         setWindowTitle("NeverNote");
327         
328         mainLeftRightSplitter = new QSplitter();
329         setCentralWidget(mainLeftRightSplitter);
330         leftSplitter1 = new QSplitter();
331         leftSplitter1.setOrientation(Qt.Orientation.Vertical);
332                 
333         browserIndexSplitter = new QSplitter();
334         browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
335         
336         //* Setup threads & thread timers
337         int indexRunnerCount = Global.getIndexThreads();
338         indexRunnerCount = 1;
339         QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5);     // increase max thread count
340
341                 logger.log(logger.EXTREME, "Building list manager");
342         listManager = new ListManager(conn, logger);
343         
344                 logger.log(logger.EXTREME, "Building index runners & timers");
345         indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
346                 indexThread = new QThread(indexRunner, "Index Thread");
347                 indexThread.start();
348                 
349         synchronizeAnimationTimer = new QTimer();
350         synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
351         
352                 indexTimer = new QTimer();
353                 indexTime = 1000*60*5;     // look for unindexed every 5 minutes
354 //              indexTime = 1000*5;
355                 indexTimer.start(indexTime);  // Start indexing timer
356                 indexTimer.timeout.connect(this, "indexTimer()");
357                 indexDisabled = false;
358                 indexRunning = false;
359                                 
360                 logger.log(logger.EXTREME, "Setting sync thread & timers");
361                 syncThreadsReady=1;
362                 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
363                 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
364                 syncTimer = new QTimer();
365                 syncTimer.timeout.connect(this, "syncTimer()");
366         syncRunner.status.message.connect(this, "setMessage(String)");
367         syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
368         syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
369         syncRunning = false;    
370                 if (syncTime > 0) {
371                         automaticSync = true;
372                         syncTimer.start(syncTime*60*1000);
373                 } else {
374                         automaticSync = false;
375                         syncTimer.stop();
376                 }
377                 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
378                 syncThread = new QThread(syncRunner, "Synchronization Thread");
379                 syncThread.start();
380                 
381                 
382                 logger.log(logger.EXTREME, "Starting authentication timer");
383                 authTimer = new QTimer();
384                 authTimer.timeout.connect(this, "authTimer()");
385                 authTimer.start(1000*60*15);
386                 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
387                 
388                 logger.log(logger.EXTREME, "Setting save note timer");
389                 saveTimer = new QTimer();
390                 saveTimer.timeout.connect(this, "saveNote()");
391                 if (Global.getAutoSaveInterval() > 0) {
392                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval()); 
393 //                      saveTimer.setInterval(1000*10); // auto save every 20 seconds;
394                         saveTimer.start();
395                 }
396                 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
397                 
398                 logger.log(logger.EXTREME, "Starting external file monitor timer");
399                 externalFileSaveTimer = new QTimer();
400                 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
401                 externalFileSaveTimer.setInterval(1000*5);   // save every 5 seconds;
402                 externalFiles = new ArrayList<String>();
403                 importFilesDelete = new ArrayList<String>();
404                 importFilesKeep = new ArrayList<String>();
405                 externalFileSaveTimer.start();
406                 
407         notebookTree = new NotebookTreeWidget();
408         attributeTree = new AttributeTreeWidget();
409         tagTree = new TagTreeWidget(conn);
410         savedSearchTree = new SavedSearchTreeWidget();
411         trashTree = new TrashTreeWidget();
412         noteTableView = new TableView(logger, listManager);
413         
414         QGridLayout leftGrid = new QGridLayout();
415         leftSplitter1.setLayout(leftGrid);
416         leftGrid.addWidget(notebookTree, 1, 1);
417         leftGrid.addWidget(tagTree,2,1);
418         leftGrid.addWidget(attributeTree,3,1);
419         leftGrid.addWidget(savedSearchTree,4,1);
420         leftGrid.addWidget(trashTree, 5, 1);
421         
422         // Setup the browser window
423         noteCache = new HashMap<String,String>();
424         browserWindow = new BrowserWindow(conn);
425
426         browserIndexSplitter.addWidget(noteTableView);
427         browserIndexSplitter.addWidget(browserWindow);
428         
429         mainLeftRightSplitter.addWidget(leftSplitter1);
430         mainLeftRightSplitter.addWidget(browserIndexSplitter);
431
432         searchField = new QComboBox();
433         searchField.setEditable(true);
434         searchField.activatedIndex.connect(this, "searchFieldChanged()");
435         searchField.setDuplicatesEnabled(false);
436         searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
437         
438         quotaBar = new QProgressBar();
439         
440         // Setup the thumbnail viewer
441         thumbnailViewer = new ThumbnailViewer();
442         thumbnailViewer.upArrow.connect(this, "upAction()");
443         thumbnailViewer.downArrow.connect(this, "downAction()");
444         thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
445         thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
446
447         listManager.loadNotesIndex();
448         initializeNotebookTree();
449         initializeTagTree();
450         initializeSavedSearchTree();
451         attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
452         attributeTreeSelected = null;
453         initializeNoteTable();    
454
455                 selectedNoteGUIDs = new ArrayList<String>();
456                 statusBar = new QStatusBar();
457                 setStatusBar(statusBar);
458                 menuBar = new MainMenuBar(this);
459                 emitLog = new ArrayList<String>();
460                 
461                 tagTree.setDeleteAction(menuBar.tagDeleteAction);
462                 tagTree.setEditAction(menuBar.tagEditAction);
463                 tagTree.setAddAction(menuBar.tagAddAction);
464                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
465                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
466                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
467                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
468         
469                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
470                 notebookTree.setEditAction(menuBar.notebookEditAction);
471                 notebookTree.setAddAction(menuBar.notebookAddAction);
472                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
473                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
474                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
475
476                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
477                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
478                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
479                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
480                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
481                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
482                         
483                 noteTableView.setAddAction(menuBar.noteAdd);
484                 noteTableView.setDeleteAction(menuBar.noteDelete);
485                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
486                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
487                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
488                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
489                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
490                 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
491                 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
492                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
493                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
494                 trashTree.load();
495         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
496                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
497                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
498                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
499                 trashTree.updateCounts(listManager.getTrashCount());
500
501                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
502                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
503
504                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
505                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
506                 
507                 if (!Global.isWindowVisible("editorButtonBar"))
508                         toggleEditorButtonBar();
509                 if (!Global.isWindowVisible("leftPanel"))
510                         menuBar.hideLeftSide.setChecked(true);
511                 
512                 setMenuBar(menuBar);
513                 setupToolBar();
514                 find = new FindDialog();
515                 find.getOkButton().clicked.connect(this, "doFindText()");
516                 
517                 // Setup the tray icon menu bar
518                 trayShowAction = new QAction("Show/Hide", this);
519                 trayExitAction = new QAction("Exit", this);
520                 trayAddNoteAction = new QAction("Add Note", this);
521                 
522                 trayExitAction.triggered.connect(this, "close()");
523                 trayAddNoteAction.triggered.connect(this, "addNote()");
524                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
525                 
526                 trayMenu = new QMenu(this);
527                 trayMenu.addAction(trayAddNoteAction);
528                 trayMenu.addAction(trayShowAction);
529                 trayMenu.addAction(trayExitAction);
530                 
531                 
532                 trayIcon = new QSystemTrayIcon(this);
533                 trayIcon.setToolTip("NeverNote");
534                 trayIcon.setContextMenu(trayMenu);
535                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
536
537                 currentNoteGuid="";
538                 currentNoteGuid = Global.getLastViewedNoteGuid();
539         historyGuids = new ArrayList<String>();
540         historyPosition = 0;
541         fromHistory = false;
542                 noteDirty = false;
543                 if (!currentNoteGuid.trim().equals("")) {
544                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
545                 }
546                 
547                 noteIndexUpdated(true);
548                 showColumns();
549                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
550                 if (menuBar.showEditorBar.isChecked())
551                 showEditorButtons();
552                 tagIndexUpdated(true);
553                 savedSearchIndexUpdated();
554                 notebookIndexUpdated();
555                 updateQuotaBar();
556         setupSyncSignalListeners();        
557         setupBrowserSignalListeners();
558         setupIndexListeners();
559               
560         
561         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
562         tagTree.showAllTags(true);
563
564                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
565         setWindowIcon(appIcon);
566         trayIcon.setIcon(appIcon);
567         if (Global.showTrayIcon())
568                 trayIcon.show();
569         else
570                 trayIcon.hide();
571         
572         scrollToGuid(currentNoteGuid);
573         if (Global.automaticLogin()) {
574                 remoteConnect();
575                 if (Global.isConnected)
576                         syncTimer();
577         }
578         setupFolderImports();
579         
580         loadStyleSheet();
581         restoreWindowState();
582         
583         if (Global.mimicEvernoteInterface) {
584                 notebookTree.selectGuid("");
585         }
586         
587         threadMonitorTimer = new QTimer();
588         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
589         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
590         
591         historyGuids.add(currentNoteGuid);
592         historyPosition = 1;
593         
594         int sortCol = Global.getSortColumn();
595                 int sortOrder = Global.getSortOrder();
596                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
597         }
598
599         
600         // Main entry point
601         public static void main(String[] args) {
602                 QApplication.initialize(args);
603                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
604                 QSplashScreen splash = new QSplashScreen(pixmap);
605                 boolean showSplash;
606                 
607                 DatabaseConnection dbConn;
608
609         try {
610             initializeGlobalSettings(args);
611
612             showSplash = Global.isWindowVisible("SplashScreen");
613             if (showSplash)
614                 splash.show();
615
616             dbConn = setupDatabaseConnection();
617
618             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
619             Global.getFileManager().purgeResDirectory();
620
621         } catch (InitializationException e) {
622             // Fatal
623             e.printStackTrace();
624             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
625             return;
626         }
627
628         NeverNote application = new NeverNote(dbConn);
629
630                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
631                 if (Global.wasWindowMaximized())
632                         application.showMaximized();
633                 else
634                         application.show();
635                 if (showSplash)
636                         splash.finish(application);
637                 QApplication.exec();
638                 System.out.println("Goodbye.");
639                 QApplication.exit();
640         }
641
642     /**
643      * Open the internal database, or create if not present
644      *
645      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
646      */
647     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
648         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
649         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
650
651         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
652             boolean goodCheck = false;
653             while (!goodCheck) {
654                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
655                 dialog.exec();
656                 if (!dialog.okPressed())
657                     System.exit(0);
658                 Global.cipherPassword = dialog.getPassword();
659                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
660                         Global.getDatabaseUserPassword(), Global.cipherPassword);
661             }
662         }
663         return dbConn;
664     }
665
666         private static void initializeGlobalSettings(String[] args) throws InitializationException {
667                 StartupConfig startupConfig = new StartupConfig();
668
669                 for (String arg : args) {
670                         String lower = arg.toLowerCase();
671                         if (lower.startsWith("--name="))
672                                 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
673                         if (lower.startsWith("--home="))
674                                 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
675                         if (lower.startsWith("--disable-viewing"))
676                                 startupConfig.setDisableViewing(true);
677                 }
678
679                 Global.setup(startupConfig);
680         }
681
682     // Exit point
683         @Override
684         public void closeEvent(QCloseEvent event) {     
685                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
686                 waitCursor(true);
687                 
688                 if (currentNote!= null & browserWindow!=null) {
689                         if (!currentNote.getTitle().equals(browserWindow.getTitle()))
690                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
691                 }
692                 saveNote();
693                 setMessage(tr("Beginning shutdown."));
694
695                 externalFileEditedSaver();
696                 if (Global.isConnected && Global.synchronizeOnClose()) {
697                         setMessage(tr("Performing synchronization before closing."));
698                         syncRunner.addWork("SYNC");
699                 }
700                 setMessage("Closing Program.");
701                 threadMonitorTimer.stop();
702
703                 syncRunner.addWork("STOP");
704                 indexRunner.addWork("STOP");
705                 saveNote();
706                 listManager.stop();
707                 saveWindowState();
708
709                 if (tempFiles != null)
710                         tempFiles.clear();
711
712                 browserWindow.noteSignal.tagsChanged.disconnect();
713                 browserWindow.noteSignal.titleChanged.disconnect();
714                 browserWindow.noteSignal.noteChanged.disconnect();
715                 browserWindow.noteSignal.notebookChanged.disconnect();
716                 browserWindow.noteSignal.createdDateChanged.disconnect();
717                 browserWindow.noteSignal.alteredDateChanged.disconnect();
718                 syncRunner.searchSignal.listChanged.disconnect();
719                 syncRunner.tagSignal.listChanged.disconnect();
720         syncRunner.notebookSignal.listChanged.disconnect();
721         syncRunner.noteIndexSignal.listChanged.disconnect();
722
723
724                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
725                 Global.setColumnPosition("noteTableCreationPosition", position);
726                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
727                 Global.setColumnPosition("noteTableTagPosition", position);
728                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
729                 Global.setColumnPosition("noteTableNotebookPosition", position);
730                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
731                 Global.setColumnPosition("noteTableChangedPosition", position);
732                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
733                 Global.setColumnPosition("noteTableAuthorPosition", position);
734                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
735                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
736                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
737                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
738                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
739                 Global.setColumnPosition("noteTableTitlePosition", position);
740                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
741                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
742                 
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     // Build the window tool bar
1930     private void setupToolBar() {
1931         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
1932         toolBar = addToolBar(tr("toolBar"));    
1933
1934         prevButton = toolBar.addAction("Previous");
1935         QIcon prevIcon = new QIcon(iconPath+"back.png");
1936         prevButton.setIcon(prevIcon);
1937         prevButton.triggered.connect(this, "previousViewedAction()");   
1938         
1939         nextButton = toolBar.addAction("Next");
1940         QIcon nextIcon = new QIcon(iconPath+"forward.png");
1941         nextButton.setIcon(nextIcon);
1942         nextButton.triggered.connect(this, "nextViewedAction()");       
1943         
1944         upButton = toolBar.addAction("Up");
1945         QIcon upIcon = new QIcon(iconPath+"up.png");
1946         upButton.setIcon(upIcon);
1947         upButton.triggered.connect(this, "upAction()");         
1948         
1949         downButton = toolBar.addAction("Down");
1950         QIcon downIcon = new QIcon(iconPath+"down.png");
1951         downButton.setIcon(downIcon);
1952         downButton.triggered.connect(this, "downAction()");
1953         
1954         synchronizeButton = toolBar.addAction("Synchronize");
1955         synchronizeAnimation = new ArrayList<QIcon>();
1956         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-0.png"));
1957         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-1.png"));
1958         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-2.png"));
1959         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-3.png"));
1960         synchronizeButton.setIcon(synchronizeAnimation.get(0));
1961         synchronizeFrame = 0;
1962         synchronizeButton.triggered.connect(this, "evernoteSync()");
1963         
1964         printButton = toolBar.addAction("Print");
1965         QIcon printIcon = new QIcon(iconPath+"print.png");
1966         printButton.setIcon(printIcon);
1967         printButton.triggered.connect(this, "printNote()");
1968         
1969         tagButton = toolBar.addAction("Tag"); 
1970         QIcon tagIcon = new QIcon(iconPath+"tag.png");
1971         tagButton.setIcon(tagIcon);
1972         tagButton.triggered.connect(browserWindow, "modifyTags()");
1973         
1974         attributeButton = toolBar.addAction("Attributes"); 
1975         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
1976         attributeButton.setIcon(attributeIcon);
1977         attributeButton.triggered.connect(this, "toggleNoteInformation()");
1978                 
1979         emailButton = toolBar.addAction("Email");
1980         QIcon emailIcon = new QIcon(iconPath+"email.png");
1981         emailButton.setIcon(emailIcon);
1982         emailButton.triggered.connect(this, "emailNote()");
1983         
1984         deleteButton = toolBar.addAction("Delete");     
1985         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
1986         deleteButton.setIcon(deleteIcon);
1987         deleteButton.triggered.connect(this, "deleteNote()");
1988                 
1989         newButton = toolBar.addAction("New");
1990         QIcon newIcon = new QIcon(iconPath+"new.png");
1991         newButton.triggered.connect(this, "addNote()");
1992         newButton.setIcon(newIcon);
1993         toolBar.addSeparator();
1994         toolBar.addWidget(new QLabel(tr("Quota:")));
1995         toolBar.addWidget(quotaBar);
1996         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
1997         updateQuotaBar();
1998         
1999         // Setup the zoom
2000         zoomSpinner = new QSpinBox();
2001         zoomSpinner.setMinimum(10);
2002         zoomSpinner.setMaximum(1000);
2003         zoomSpinner.setAccelerated(true);
2004         zoomSpinner.setSingleStep(10);
2005         zoomSpinner.setValue(100);
2006         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2007         toolBar.addWidget(new QLabel(tr("Zoom")));
2008         toolBar.addWidget(zoomSpinner);
2009         
2010         //toolBar.addWidget(new QLabel("                    "));
2011         toolBar.addSeparator();
2012         toolBar.addWidget(new QLabel(tr("  Search:")));
2013         toolBar.addWidget(searchField);
2014         QSizePolicy sizePolicy = new QSizePolicy();
2015         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2016         searchField.setSizePolicy(sizePolicy);
2017         searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2018
2019         searchClearButton = toolBar.addAction("Search Clear");
2020         QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2021         searchClearButton.setIcon(searchClearIcon);
2022         searchClearButton.triggered.connect(this, "searchFieldCleared()");
2023         
2024         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2025     }
2026     // Update the sychronize button picture
2027     @SuppressWarnings("unused")
2028         private void updateSyncButton() {
2029         synchronizeFrame++;
2030         if (synchronizeFrame == 4) 
2031                 synchronizeFrame = 0;
2032         synchronizeButton.setIcon(synchronizeAnimation.get(synchronizeFrame));
2033     }
2034     // Synchronize with Evernote
2035         @SuppressWarnings("unused")
2036         private void evernoteSync() {
2037         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2038         if (!Global.isConnected)
2039                 remoteConnect();
2040         if (Global.isConnected)
2041                 synchronizeAnimationTimer.start(200);
2042         syncTimer();
2043         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2044     }
2045     private void updateQuotaBar() {
2046         long limit = Global.getUploadLimit();
2047         long amount = Global.getUploadAmount();
2048         if (amount>0 && limit>0) {
2049                 int percent =(int)(amount*100/limit);
2050                 quotaBar.setValue(percent);
2051         } else 
2052                 quotaBar.setValue(0);
2053     }
2054         // Zoom changed
2055     @SuppressWarnings("unused")
2056         private void zoomChanged() {
2057         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2058     }
2059
2060     //****************************************************************
2061     //****************************************************************
2062     //* System Tray functions
2063     //****************************************************************
2064     //****************************************************************
2065         private void trayToggleVisible() {
2066         if (isVisible()) {
2067                 hide();
2068         } else {
2069                 show();
2070                 raise();
2071         }
2072     }
2073     @SuppressWarnings("unused")
2074         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2075         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2076                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2077                 trayToggleVisible();
2078         }
2079     }
2080     
2081     
2082     //***************************************************************
2083     //***************************************************************
2084     //** These functions deal with the trash tree
2085     //***************************************************************
2086     //***************************************************************    
2087     // Setup the tree containing the trash.
2088     @SuppressWarnings("unused")
2089         private void trashTreeSelection() {     
2090         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2091         
2092         clearNotebookFilter();
2093         clearTagFilter();
2094         clearAttributeFilter();
2095         clearSavedSearchFilter();
2096         
2097         String tempGuid = currentNoteGuid;
2098         
2099 //      currentNoteGuid = "";
2100         currentNote = new Note();
2101         selectedNoteGUIDs.clear();
2102         listManager.getSelectedNotebooks().clear();
2103         listManager.getSelectedTags().clear();
2104         listManager.setSelectedSavedSearch("");
2105         browserWindow.clear();
2106     
2107         // toggle the add buttons
2108         newButton.setEnabled(!newButton.isEnabled());
2109         menuBar.noteAdd.setEnabled(newButton.isEnabled());
2110         menuBar.noteAdd.setVisible(true);
2111         
2112         List<QTreeWidgetItem> selections = trashTree.selectedItems();
2113         if (selections.size() == 0) {
2114                 currentNoteGuid = trashNoteGuid;
2115                         trashNoteGuid = tempGuid;
2116                 Global.showDeleted = false;
2117                 menuBar.noteRestoreAction.setEnabled(false);
2118                 menuBar.noteRestoreAction.setVisible(false);
2119         }
2120         else {
2121                 currentNoteGuid = trashNoteGuid;
2122                         trashNoteGuid = tempGuid;
2123                 menuBar.noteRestoreAction.setEnabled(true);
2124                 menuBar.noteRestoreAction.setVisible(true);
2125                 Global.showDeleted = true;
2126         }
2127         listManager.loadNotesIndex();
2128         noteIndexUpdated(false);
2129 ////            browserWindow.setEnabled(newButton.isEnabled());
2130         browserWindow.setReadOnly(!newButton.isEnabled());
2131         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2132     }
2133     // Empty the trash file
2134     @SuppressWarnings("unused")
2135         private void emptyTrash() {
2136 //      browserWindow.clear();
2137         listManager.emptyTrash();
2138         if (trashTree.selectedItems().size() > 0) {
2139                 listManager.getSelectedNotebooks().clear();
2140                 listManager.getSelectedTags().clear();
2141                 listManager.setSelectedSavedSearch("");
2142                 newButton.setEnabled(!newButton.isEnabled());
2143                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2144                 menuBar.noteAdd.setVisible(true);
2145                 browserWindow.clear();
2146                 
2147                 clearTagFilter();
2148                 clearNotebookFilter();
2149                 clearSavedSearchFilter();
2150                 clearAttributeFilter();
2151                         
2152                 Global.showDeleted = false;
2153                 menuBar.noteRestoreAction.setEnabled(false);
2154                 menuBar.noteRestoreAction.setVisible(false);
2155                 
2156                 listManager.loadNotesIndex();
2157 //--->>>                noteIndexUpdated(true);
2158                 noteIndexUpdated(false);
2159         }       
2160    }
2161     // Show/Hide trash window
2162         private void toggleTrashWindow() {
2163                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2164         if (trashTree.isVisible())
2165                 trashTree.hide();
2166         else
2167                 trashTree.show();
2168         menuBar.hideTrash.setChecked(trashTree.isVisible());
2169         
2170                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2171         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2172     }    
2173         private void clearTrashFilter() {
2174                 Global.showDeleted = false;
2175         newButton.setEnabled(true);
2176         menuBar.noteAdd.setEnabled(true);
2177         menuBar.noteAdd.setVisible(true);
2178                 trashTree.blockSignals(true);
2179                 trashTree.clearSelection();
2180                 trashTree.blockSignals(false);
2181                 
2182         }
2183     
2184    
2185     //***************************************************************
2186     //***************************************************************
2187     //** These functions deal with connection settings
2188     //***************************************************************
2189     //***************************************************************
2190         // SyncRunner had a problem and things are disconnected
2191         @SuppressWarnings("unused")
2192         private void remoteErrorDisconnect() {
2193                 menuBar.connectAction.setText(tr("Connect"));
2194                 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2195                 menuBar.synchronizeAction.setEnabled(false);
2196                 synchronizeAnimationTimer.stop();
2197                 return;
2198         }
2199         // Do a manual connect/disconnect
2200     private void remoteConnect() {
2201         logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2202
2203         if (Global.isConnected) {
2204                 Global.isConnected = false;
2205                 syncRunner.enDisconnect();
2206                 setupConnectMenuOptions();
2207                 setupOnlineMenu();
2208                 return;
2209         }
2210         
2211         AESEncrypter aes = new AESEncrypter();
2212         try {
2213                         aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
2214                 } catch (FileNotFoundException e) {
2215                         // File not found, so we'll just get empty strings anyway. 
2216                 }
2217                 String userid = aes.getUserid();
2218                 String password = aes.getPassword();
2219                 if (!userid.equals("") && !password.equals("")) {
2220                 Global.username = userid;
2221                 Global.password = password;
2222                 }               
2223
2224         // Show the login dialog box
2225                 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
2226                         LoginDialog login = new LoginDialog();
2227                         login.exec();
2228                 
2229                         if (!login.okPressed()) {
2230                                 return;
2231                         }
2232         
2233                         Global.username = login.getUserid();
2234                         Global.password = login.getPassword();
2235                 }
2236                 syncRunner.username = Global.username;
2237                 syncRunner.password = Global.password;
2238                 syncRunner.userStoreUrl = Global.userStoreUrl;
2239                 syncRunner.noteStoreUrl = Global.noteStoreUrl;
2240                 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
2241                 syncRunner.enConnect();
2242                 Global.isConnected = syncRunner.isConnected;
2243                 setupOnlineMenu();
2244                 setupConnectMenuOptions();
2245                 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
2246     }
2247     private void setupConnectMenuOptions() {
2248         logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
2249                 if (!Global.isConnected) {
2250                         menuBar.connectAction.setText(tr("Connect"));
2251                         menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2252                         menuBar.synchronizeAction.setEnabled(false);
2253                 } else {
2254                         menuBar.connectAction.setText(tr("Disconnect"));
2255                         menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
2256                         menuBar.synchronizeAction.setEnabled(true);
2257                 }
2258                 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
2259     }
2260     
2261     
2262     
2263     //***************************************************************
2264     //***************************************************************
2265     //** These functions deal with the GUI Attribute tree
2266     //***************************************************************
2267     //***************************************************************    
2268     @SuppressWarnings("unused")
2269         private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
2270         
2271         clearTagFilter();
2272         clearNotebookFilter();
2273         clearTrashFilter();
2274         clearSavedSearchFilter();
2275
2276         if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
2277                 if (item.childCount() > 0) {
2278                         item.setSelected(false);
2279                 } else {
2280                 Global.createdBeforeFilter.reset();
2281                 Global.createdSinceFilter.reset();
2282                 Global.changedBeforeFilter.reset();
2283                 Global.changedSinceFilter.reset();
2284                 Global.containsFilter.reset();
2285                         attributeTreeSelected = item;
2286                         DateAttributeFilterTable f = null;
2287                         f = findDateAttributeFilterTable(item.parent());
2288                         if (f!=null)
2289                                 f.select(item.parent().indexOfChild(item));
2290                         else {
2291                                 Global.containsFilter.select(item.parent().indexOfChild(item));
2292                         }
2293                 }
2294                 listManager.loadNotesIndex();
2295                 noteIndexUpdated(false);
2296                 return;
2297         }
2298                 attributeTreeSelected = null;
2299                 item.setSelected(false);
2300         Global.createdBeforeFilter.reset();
2301         Global.createdSinceFilter.reset();
2302         Global.changedBeforeFilter.reset();
2303         Global.changedSinceFilter.reset();
2304         Global.containsFilter.reset();
2305         listManager.loadNotesIndex();
2306                 noteIndexUpdated(false); 
2307     }
2308     // This determines what attribute filter we need, depending upon the selection
2309     private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
2310                 if (w.parent() != null && w.childCount() > 0) {
2311                         QTreeWidgetItem parent = w.parent();
2312                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
2313                                 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2314                                         return Global.createdSinceFilter;
2315                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created && 
2316                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2317                                         return Global.createdBeforeFilter;
2318                         if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
2319                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2320                                         return Global.changedSinceFilter;
2321                 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified && 
2322                         w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2323                                                 return Global.changedBeforeFilter;
2324                 }
2325                 return null;
2326     }
2327
2328     // Show/Hide attribute search window
2329         private void toggleAttributesWindow() {
2330                 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
2331         if (attributeTree.isVisible())
2332                 attributeTree.hide();
2333         else
2334                 attributeTree.show();
2335         menuBar.hideAttributes.setChecked(attributeTree.isVisible());
2336         
2337                 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
2338         logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
2339     }    
2340         private void clearAttributeFilter() {
2341         Global.createdBeforeFilter.reset();
2342         Global.createdSinceFilter.reset();
2343         Global.changedBeforeFilter.reset();
2344         Global.changedSinceFilter.reset();
2345         Global.containsFilter.reset();
2346         attributeTreeSelected = null;
2347                 attributeTree.blockSignals(true);
2348                 attributeTree.clearSelection();
2349                 attributeTree.blockSignals(false);
2350         }
2351     
2352         
2353     //***************************************************************
2354     //***************************************************************
2355     //** These functions deal with the GUI Note index table
2356     //***************************************************************
2357     //***************************************************************    
2358     // Initialize the note list table
2359         private void initializeNoteTable() {
2360                 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
2361                 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
2362                 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
2363                 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
2364         }       
2365     // Show/Hide trash window
2366         @SuppressWarnings("unused")
2367         private void toggleNoteListWindow() {
2368                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
2369         if (noteTableView.isVisible())
2370                 noteTableView.hide();
2371         else
2372                 noteTableView.show();
2373         menuBar.hideNoteList.setChecked(noteTableView.isVisible());
2374         
2375                 Global.saveWindowVisible("noteList", noteTableView.isVisible());
2376         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
2377     }   
2378         // Handle the event that a user selects a note from the table
2379     @SuppressWarnings("unused")
2380         private void noteTableSelection() {
2381                 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
2382                 saveNote();
2383                 if (historyGuids.size() == 0) {
2384                         historyGuids.add(currentNoteGuid);
2385                         historyPosition = 1;
2386                 }
2387         noteTableView.showColumn(Global.noteTableGuidPosition);
2388         
2389         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2390         noteTableView.hideColumn(Global.noteTableGuidPosition);
2391         
2392         if (selections.size() > 0) {
2393                 QModelIndex index;
2394                 menuBar.noteDuplicateAction.setEnabled(true);
2395                 menuBar.noteOnlineHistoryAction.setEnabled(true);
2396                 menuBar.noteMergeAction.setEnabled(true);
2397                 selectedNoteGUIDs.clear();
2398                 if (selections.size() != 1 || Global.showDeleted) {
2399                         menuBar.noteDuplicateAction.setEnabled(false);
2400                 }
2401                 if (selections.size() != 1 || !Global.isConnected) {
2402                         menuBar.noteOnlineHistoryAction.setEnabled(false);
2403                 }
2404                 if (selections.size() == 1) {
2405                         menuBar.noteMergeAction.setEnabled(false);
2406                 }
2407                 for (int i=0; i<selections.size(); i++) {
2408                         int row = selections.get(i).row();
2409                         if (row == 0) 
2410                                 upButton.setEnabled(false);
2411                         else
2412                                 upButton.setEnabled(true);
2413                         if (row < listManager.getNoteTableModel().rowCount()-1)
2414                                 downButton.setEnabled(true);
2415                         else
2416                                 downButton.setEnabled(false);
2417                         index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
2418                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
2419                         currentNoteGuid = (String)ix.values().toArray()[0];
2420                         selectedNoteGUIDs.add(currentNoteGuid);
2421                 }
2422         }
2423         
2424         nextButton.setEnabled(true);
2425                 prevButton.setEnabled(true);
2426         if (!fromHistory) {
2427                 int endPosition = historyGuids.size()-1;
2428                 for (int j=historyPosition; j<=endPosition; j++) {
2429                         historyGuids.remove(historyGuids.size()-1);
2430                 }
2431                 historyGuids.add(currentNoteGuid);
2432                 historyPosition = historyGuids.size();
2433         } 
2434         if (historyPosition <= 1)
2435                 prevButton.setEnabled(false);
2436         if (historyPosition == historyGuids.size())
2437                 nextButton.setEnabled(false);
2438                 
2439         fromHistory = false;
2440         scrollToGuid(currentNoteGuid);
2441         refreshEvernoteNote(true);
2442                 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
2443     }    
2444         // Trigger a refresh when the note db has been updated
2445         private void noteIndexUpdated(boolean reload) {
2446                 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
2447                 saveNote();
2448         refreshEvernoteNoteList();
2449         logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
2450         noteTableView.load(reload);
2451         scrollToGuid(currentNoteGuid);
2452                 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
2453     }
2454         // Called when the list of notes is updated
2455     private void refreshEvernoteNoteList() {
2456         logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
2457         browserWindow.setDisabled(false);
2458                 if (selectedNoteGUIDs == null)
2459                         selectedNoteGUIDs = new ArrayList<String>();
2460                 selectedNoteGUIDs.clear();  // clear out old entries
2461                 
2462                 String saveCurrentNoteGuid = new String();
2463                 String tempNoteGuid = new String();
2464                                 
2465                 historyGuids.clear();
2466                 historyPosition = 0;
2467                 prevButton.setEnabled(false);
2468                 nextButton.setEnabled(false);
2469                 
2470                 if (currentNoteGuid == null) 
2471                         currentNoteGuid = new String();
2472                 
2473                 for (Note note : listManager.getNoteIndex()) {
2474                         tempNoteGuid = note.getGuid();
2475                         if (currentNoteGuid.equals(tempNoteGuid)) {
2476                                 saveCurrentNoteGuid = new String(tempNoteGuid);
2477                         }
2478                 }
2479                 
2480                 if (listManager.getNoteIndex().size() == 0) {
2481                         currentNoteGuid = "";
2482                         currentNote = null;
2483                         browserWindow.clear();
2484                         browserWindow.setDisabled(true);
2485                 } 
2486                 
2487                 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() >0) {
2488                         currentNoteGuid = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1).getGuid();
2489                         currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
2490                         refreshEvernoteNote(true);
2491                 } else {
2492                         refreshEvernoteNote(false);
2493                 }
2494                 reloadTagTree();
2495
2496                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
2497         } 
2498     // Called when the previous arrow button is clicked 
2499     @SuppressWarnings("unused")
2500         private void previousViewedAction() {
2501         if (!prevButton.isEnabled())
2502                 return;
2503         if (historyPosition == 0)
2504                 return;
2505                 historyPosition--;
2506         if (historyPosition <= 0)
2507                 return;
2508         String historyGuid = historyGuids.get(historyPosition-1);
2509         fromHistory = true;
2510         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2511                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
2512                 if (modelIndex != null) {
2513                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2514                         String tableGuid =  (String)ix.values().toArray()[0];
2515                         if (tableGuid.equals(historyGuid)) {
2516                                 noteTableView.selectRow(i);
2517                                 return;
2518                         }       
2519                 }
2520         }
2521     }
2522     @SuppressWarnings("unused")
2523         private void nextViewedAction() {
2524         if (!nextButton.isEnabled())
2525                 return;
2526         String historyGuid = historyGuids.get(historyPosition);
2527         historyPosition++;
2528         fromHistory = true;
2529         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2530                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
2531                 if (modelIndex != null) {
2532                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2533                         String tableGuid =  (String)ix.values().toArray()[0];
2534                         if (tableGuid.equals(historyGuid)) {
2535                                 noteTableView.selectRow(i);
2536                                 return;
2537                         }       
2538                 }
2539         }       
2540     }
2541     // Called when the up arrow is clicked 
2542     @SuppressWarnings("unused")
2543         private void upAction() {
2544         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2545         int row = selections.get(0).row();
2546         if (row > 0) {
2547                 noteTableView.selectRow(row-1);
2548         }
2549     }
2550     // Called when the down arrow is clicked 
2551     @SuppressWarnings("unused")
2552         private void downAction() {
2553         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2554         int row = selections.get(0).row();
2555         int max = listManager.getNoteTableModel().rowCount();
2556         if (row < max-1) {
2557                 noteTableView.selectRow(row+1);
2558         }
2559     }
2560     // Update a tag string for a specific note in the list
2561     @SuppressWarnings("unused")
2562         private void updateListTags(String guid, List<String> tags) {
2563         logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
2564         StringBuffer tagBuffer = new StringBuffer();
2565         for (int i=0; i<tags.size(); i++) {
2566                 tagBuffer.append(tags.get(i));
2567                 if (i<tags.size()-1)
2568                         tagBuffer.append(", ");
2569         }
2570         
2571         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2572                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2573                 if (modelIndex != null) {
2574                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2575                         String tableGuid =  (String)ix.values().toArray()[0];
2576                         if (tableGuid.equals(guid)) {
2577                                 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
2578                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2579                                 return;
2580                         }
2581                 }
2582         }
2583         logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
2584     }
2585     // Update a title for a specific note in the list
2586     @SuppressWarnings("unused")
2587         private void updateListAuthor(String guid, String author) {
2588         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2589
2590         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2591                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2592                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2593                 if (modelIndex != null) {
2594 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2595                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2596                         String tableGuid =  (String)ix.values().toArray()[0];
2597                         if (tableGuid.equals(guid)) {
2598                                 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
2599                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2600                                 return;
2601                         }       
2602                 }
2603         }
2604         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2605     }
2606         private void updateListNoteNotebook(String guid, String notebook) {
2607         logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
2608         listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
2609         logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
2610     }
2611     // Update a title for a specific note in the list
2612     @SuppressWarnings("unused")
2613         private void updateListSourceUrl(String guid, String url) {
2614         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2615
2616         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2617                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2618                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2619                 if (modelIndex != null) {
2620 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2621                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2622                         String tableGuid =  (String)ix.values().toArray()[0];
2623                         if (tableGuid.equals(guid)) {
2624                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2625                                 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
2626                                 return;
2627                         }       
2628                 }
2629         }
2630         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2631     }
2632         private void updateListGuid(String oldGuid, String newGuid) {
2633         logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2634
2635         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2636                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2637                 if (modelIndex != null) {
2638                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2639                         String tableGuid =  (String)ix.values().toArray()[0];
2640                         if (tableGuid.equals(oldGuid)) {
2641                                 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
2642                                 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2643                                 return;
2644                         }       
2645                 }
2646         }
2647         logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2648     }
2649         private void updateListTagName(String guid) {
2650         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2651                 
2652                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2653                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2654                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2655
2656                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2657                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2658                                         if (modelIndex != null) {
2659                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2660                                                 String noteGuid = (String)ix.values().toArray()[0];
2661                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2662                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2663                                                         //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2664                                                         i=listManager.getNoteTableModel().rowCount();
2665                                                 }
2666                                         }
2667                                 }
2668                         }
2669                 }       
2670         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2671     }
2672         private void removeListTagName(String guid) {
2673         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2674                 
2675                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2676                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2677                                 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
2678                                         if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
2679                                                 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
2680                                 }
2681                                 
2682                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2683                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2684                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2685                                         if (modelIndex != null) {
2686                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2687                                                 String noteGuid = (String)ix.values().toArray()[0];
2688                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2689                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2690 //                                                      listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2691                                                         i=listManager.getNoteTableModel().rowCount();
2692                                                 }
2693                                         }
2694                                 }
2695                         }
2696                 }       
2697         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2698     }
2699     private void updateListNotebookName(String oldName, String newName) {
2700         logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
2701
2702         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2703                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition); 
2704                 if (modelIndex != null) {
2705                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2706                         String tableName =  (String)ix.values().toArray()[0];
2707                         if (tableName.equalsIgnoreCase(oldName)) {
2708 //                              listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2709                                 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
2710                         }
2711                 }
2712         }
2713         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
2714     }
2715     @SuppressWarnings("unused")
2716         private void updateListDateCreated(String guid, QDateTime date) {
2717         logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
2718
2719         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2720                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2721                 if (modelIndex != null) {
2722                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2723                         String tableGuid =  (String)ix.values().toArray()[0];
2724                         if (tableGuid.equals(guid)) {
2725                                 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2726                                 return;
2727                         }
2728                 }
2729         }
2730         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2731     }
2732     @SuppressWarnings("unused")
2733         private void updateListDateSubject(String guid, QDateTime date) {
2734         logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
2735
2736         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2737                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2738                 if (modelIndex != null) {
2739                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2740                         String tableGuid =  (String)ix.values().toArray()[0];
2741                         if (tableGuid.equals(guid)) {
2742                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2743                                 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2744                                 return;
2745                         }
2746                 }
2747         }
2748         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2749     }
2750     @SuppressWarnings("unused")
2751         private void updateListDateChanged(String guid, QDateTime date) {
2752         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2753
2754         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2755                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2756                 if (modelIndex != null) {
2757                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2758                         String tableGuid =  (String)ix.values().toArray()[0];
2759                         if (tableGuid.equals(guid)) {
2760                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2761                                 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2762                                 return;
2763                         }
2764                 }
2765         }
2766         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2767     }
2768     private void updateListDateChanged() {
2769         logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2770         QDateTime date = new QDateTime(QDateTime.currentDateTime());
2771         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2772                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2773                 if (modelIndex != null) {
2774                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2775                         String tableGuid =  (String)ix.values().toArray()[0];
2776                         if (tableGuid.equals(currentNoteGuid)) {
2777                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2778                                 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2779                                 return;
2780                         }
2781                 }
2782         }
2783         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2784     }  
2785     // Redo scroll
2786     @SuppressWarnings("unused")
2787         private void scrollToCurrentGuid() {
2788         //scrollToGuid(currentNoteGuid);
2789         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2790         if (selections.size() == 0)
2791                 return;
2792         QModelIndex index = selections.get(0);
2793         int row = selections.get(0).row();
2794         String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
2795         scrollToGuid(guid);
2796     }
2797     // Scroll to a particular index item
2798     private void scrollToGuid(String guid) {
2799         if (currentNote == null || guid == null) 
2800                 return;
2801         if (currentNote.isActive() && Global.showDeleted) {
2802                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2803                         if (!listManager.getNoteIndex().get(i).isActive()) {
2804                                 currentNote = listManager.getNoteIndex().get(i);
2805                                 currentNoteGuid =  currentNote.getGuid();
2806                                 i = listManager.getNoteIndex().size();
2807                         }
2808                 }
2809         }
2810         
2811         if (!currentNote.isActive() && !Global.showDeleted) {
2812                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2813                         if (listManager.getNoteIndex().get(i).isActive()) {
2814                                 currentNote = listManager.getNoteIndex().get(i);
2815                                 currentNoteGuid =  currentNote.getGuid();
2816                                 i = listManager.getNoteIndex().size();
2817                         }
2818                 }
2819         }
2820         
2821         QModelIndex index; 
2822         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2823                 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
2824                 if (currentNoteGuid.equals(index.data())) {
2825 //                      noteTableView.setCurrentIndex(index);
2826                         noteTableView.selectRow(i);
2827                         noteTableView.scrollTo(index, ScrollHint.EnsureVisible);  // This should work, but it doesn't
2828                                 i=listManager.getNoteTableModel().rowCount();
2829                 }
2830         }
2831     }
2832     // Show/Hide columns
2833     private void showColumns() {
2834                 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
2835                 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
2836                 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
2837                 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
2838                 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
2839                 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
2840                 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
2841                 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
2842     }
2843     // Open a separate window
2844     @SuppressWarnings("unused")
2845         private void listDoubleClick() {
2846
2847     }
2848     // Title color has changed
2849     @SuppressWarnings("unused")
2850         private void titleColorChanged(Integer color) {
2851         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2852
2853         QColor backgroundColor = new QColor();
2854                 QColor foregroundColor = new QColor(QColor.black);
2855                 backgroundColor.setRgb(color);
2856                 
2857                 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
2858                         foregroundColor.setRgb(QColor.white.rgb());
2859         
2860                 if (selectedNoteGUIDs.size() == 0)
2861                         selectedNoteGUIDs.add(currentNoteGuid);
2862                 
2863         for (int j=0; j<selectedNoteGUIDs.size(); j++) {
2864                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2865                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2866                         if (modelIndex != null) {
2867                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2868                                 String tableGuid =  (String)ix.values().toArray()[0];
2869                                 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
2870                                         for (int k=0; k<Global.noteTableColumnCount; k++) {
2871                                                 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
2872                                                 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
2873                                                 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
2874                                         }
2875                                         i=listManager.getNoteTableModel().rowCount();
2876                                 }
2877                         }
2878                 }
2879         }
2880         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2881     }
2882     
2883     
2884     //***************************************************************
2885     //***************************************************************
2886     //** These functions deal with Note specific things
2887     //***************************************************************
2888     //***************************************************************    
2889     @SuppressWarnings("unused")
2890         private void setNoteDirty() {
2891                 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
2892                 
2893                 // If the note is dirty, then it is unsynchronized by default.
2894                 if (noteDirty) 
2895                         return;
2896                 
2897                 // Set the note as dirty and check if its status is synchronized in the display table
2898                 noteDirty = true;
2899                 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
2900                         if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
2901                                 return;
2902                 }
2903                 
2904                 // If this wasn't already marked as unsynchronized, then we need to update the table
2905                 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
2906 /*      listManager.getUnsynchronizedNotes().add(currentNoteGuid);
2907         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2908                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2909                 if (modelIndex != null) {
2910                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2911                         String tableGuid =  (String)ix.values().toArray()[0];
2912                         if (tableGuid.equals(currentNoteGuid)) {
2913                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2914                                 return;
2915                         }
2916                 }
2917         }
2918  */     
2919                 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
2920     }
2921     private void saveNote() {
2922                 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
2923         if (noteDirty) {
2924                         logger.log(logger.EXTREME, "Note is dirty.");
2925                 waitCursor(true);
2926                 
2927                         preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
2928                         preview.finished.connect(this, "saveThumbnail(String)");
2929                         preview.setContent(browserWindow.getContent());
2930                 
2931                         logger.log(logger.EXTREME, "Saving to cache");
2932                         QTextCodec codec = QTextCodec.codecForLocale();
2933 //              QTextDecoder decoder = codec.makeDecoder();
2934                         codec = QTextCodec.codecForName("UTF-8");
2935                 QByteArray unicode =  codec.fromUnicode(browserWindow.getContent());
2936                 noteCache.put(currentNoteGuid, unicode.toString());
2937                         
2938                 logger.log(logger.EXTREME, "updating list manager");
2939                 listManager.updateNoteContent(currentNoteGuid, browserWindow.getContent());
2940                 noteCache.put(currentNoteGuid, browserWindow.getContent());
2941                         logger.log(logger.EXTREME, "Updating title");
2942                 listManager.updateNoteTitle(currentNoteGuid, browserWindow.getTitle());
2943                 updateListDateChanged();
2944
2945                         logger.log(logger.EXTREME, "Looking through note index for refreshed note");
2946                 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2947                         if (listManager.getNoteIndex().get(i).getGuid().equals(currentNoteGuid)) {
2948                                 currentNote = listManager.getNoteIndex().get(i);
2949                                 i = listManager.getNoteIndex().size();
2950                         }
2951                 }
2952                 noteDirty = false;
2953                 waitCursor(false);
2954         }
2955     }
2956     // Get a note from Evernote (and put it in the browser)
2957         private void refreshEvernoteNote(boolean reload) {
2958                 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
2959                 if (Global.disableViewing) {
2960                         browserWindow.setEnabled(false);
2961                         return;
2962                 }
2963                 inkNote = false;
2964                 if (!Global.showDeleted)
2965                         browserWindow.setReadOnly(false);
2966                 Global.cryptCounter =0;
2967                 if (currentNoteGuid.equals("")) {
2968                         browserWindow.setReadOnly(true);
2969                         return;
2970                 }
2971                 if (!reload)
2972                         return;
2973                 
2974                 waitCursor(true);
2975                 browserWindow.loadingData(true);
2976
2977                 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
2978                 if (currentNote == null) 
2979                         return;
2980
2981                 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
2982                         QByteArray js = new QByteArray();
2983                         // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly 
2984                         js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");               
2985                         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>");
2986                         js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
2987                         js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
2988                         js.append("</head>");
2989                         js.append(rebuildNoteHTML(currentNoteGuid, currentNote.getContent()));
2990                         js.append("</HTML>");
2991                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
2992                         js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
2993                         js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
2994                         browserWindow.getBrowser().setContent(js);
2995                         noteCache.put(currentNoteGuid, js.toString());
2996                         if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
2997                                 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
2998                                 preview.finished.connect(this, "saveThumbnail(String)");
2999                                 preview.setContent(js.toString());
3000                         }
3001                 } else {
3002                         logger.log(logger.HIGH, "Note content is being pulled from the cache");
3003                         String cachedContent = modifyCachedTodoTags(noteCache.get(currentNoteGuid));
3004                         browserWindow.getBrowser().setContent(new QByteArray(cachedContent));
3005                 }
3006                 
3007                 browserWindow.getBrowser().page().setContentEditable(!inkNote);  // We don't allow editing of ink notes
3008                 browserWindow.setNote(currentNote);
3009                 
3010                 // Build a list of non-closed notebooks
3011                 List<Notebook> nbooks = new ArrayList<Notebook>();
3012                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3013                         boolean found=false;
3014                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3015                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) 
3016                                         found = true;
3017                         }
3018                         if (!found)
3019                                 nbooks.add(listManager.getNotebookIndex().get(i));
3020                 }
3021                 
3022                 browserWindow.setNotebookList(nbooks);
3023                 browserWindow.setTitle(currentNote.getTitle());
3024                 browserWindow.setTag(getTagNamesForNote(currentNote));
3025                 browserWindow.setAuthor(currentNote.getAttributes().getAuthor());
3026                 
3027                 browserWindow.setAltered(currentNote.getUpdated());
3028                 browserWindow.setCreation(currentNote.getCreated());
3029                 if (currentNote.getAttributes().getSubjectDate() > 0)
3030                         browserWindow.setSubjectDate(currentNote.getAttributes().getSubjectDate());
3031                 else
3032                         browserWindow.setSubjectDate(currentNote.getCreated());
3033                 browserWindow.setUrl(currentNote.getAttributes().getSourceURL());
3034                 browserWindow.setAllTags(listManager.getTagIndex());
3035                 browserWindow.setCurrentTags(currentNote.getTagNames());
3036                 noteDirty = false;
3037                 scrollToGuid(currentNoteGuid);
3038                 
3039                 browserWindow.loadingData(false);
3040                 if (thumbnailViewer.isActiveWindow())
3041                         thumbnailView();
3042                 waitCursor(false);
3043                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
3044         }
3045         // Save a generated thumbnail
3046         @SuppressWarnings("unused")
3047         private void saveThumbnail(String guid) {
3048                 QFile tFile = new QFile(Global.getFileManager().getResDirPath("thumbnail-" + guid + ".png"));
3049                 tFile.open(OpenModeFlag.ReadOnly);
3050                 QByteArray imgBytes = tFile.readAll();
3051                 tFile.close();
3052                 conn.getNoteTable().setThumbnail(guid, imgBytes);
3053                 conn.getNoteTable().setThumbnailNeeded(guid, false);
3054                 thumbnailViewer.setThumbnail(QImage.fromData(imgBytes));
3055                 if (thumbnailViewer.isVisible()) 
3056                         thumbnailViewer.showFullScreen();
3057                 
3058                 /*              
3059                 QByteArray img2 = new QByteArray(conn.getNoteTable().getThumbnail(guid));
3060                 QFile file = new QFile(Global.currentDir+"res/aaaa.png");
3061                 file.open(OpenModeFlag.WriteOnly);
3062                 file.write(img2);
3063                 file.close(); 
3064                 */
3065         }
3066     // Show/Hide note information
3067         @SuppressWarnings("unused")
3068         private void toggleNoteInformation() {
3069                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
3070         browserWindow.toggleInformation();
3071         menuBar.noteAttributes.setChecked(browserWindow.isExtended());
3072         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
3073     }
3074         // Listener triggered when a print button is pressed
3075     @SuppressWarnings("unused")
3076         private void printNote() {
3077                 logger.log(logger.HIGH, "Entering NeverNote.printNote");
3078
3079         QPrintDialog dialog = new QPrintDialog();
3080         if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
3081                 QPrinter printer = dialog.printer();
3082                 browserWindow.getBrowser().print(printer);
3083         }
3084                 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
3085
3086     }
3087     // Listener triggered when the email button is pressed
3088     @SuppressWarnings("unused")
3089         private void emailNote() {
3090         logger.log(logger.HIGH, "Entering NeverNote.emailNote");
3091         
3092         if (Desktop.isDesktopSupported()) {
3093             Desktop desktop = Desktop.getDesktop();
3094             
3095             String text2 = browserWindow.getContentsToEmail();
3096             QUrl url = new QUrl("mailto:");
3097             url.addQueryItem("subject", currentNote.getTitle());
3098             url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
3099             QDesktopServices.openUrl(url);
3100         }
3101 /*            
3102             
3103             if (desktop.isSupported(Desktop.Action.MAIL)) {
3104                 URI uriMailTo = null;
3105                 try {
3106                         //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
3107                         String text = browserWindow.getContentsToEmail();
3108                         //text = "<b>" +text +"</b>";
3109                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3110                                                         +"&BODY=" +text, null);
3111                                         uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3112                                                         +"&ATTACHMENT=d:/test.pdf", null);
3113                                         desktop.mail(uriMailTo);
3114                                 } catch (URISyntaxException e) {
3115                                         e.printStackTrace();
3116                                 } catch (IOException e) {
3117                                         e.printStackTrace();
3118                                 }
3119
3120             }
3121
3122         }     
3123  */     
3124         logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
3125     }
3126         // Reindex all notes
3127     @SuppressWarnings("unused")
3128         private void fullReindex() {
3129         logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
3130         // If we are deleting non-trash notes
3131         if (currentNote.getDeleted() == 0) { 
3132                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will cause all notes & attachments to be reindexed, "+
3133                                 "but please be aware that depending upon the size of your database updating all these records " +
3134                                 "can be time consuming and NeverNote will be unresponsive until it is complete.  Do you wish to continue?"),
3135                                 QMessageBox.StandardButton.Yes, 
3136                                         QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3137                                                                 return;
3138                 }
3139         }
3140         waitCursor(true);
3141         setMessage(tr("Marking notes for reindex."));
3142         conn.getNoteTable().reindexAllNotes();
3143         conn.getNoteTable().noteResourceTable.reindexAll(); 
3144         setMessage(tr("Database will be reindexed."));
3145         waitCursor(false);
3146         logger.log(logger.HIGH, "Leaving NeverNote.fullRefresh");
3147     }
3148     // Listener when a user wants to reindex a specific note
3149     @SuppressWarnings("unused")
3150         private void reindexNote() {
3151         logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
3152                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3153                         conn.getNoteTable().setIndexNeeded(selectedNoteGUIDs.get(i), true);
3154                 }
3155                 if (selectedNotebookGUIDs.size() > 1)
3156                         setMessage(tr("Notes will be reindexed."));
3157                 else
3158                         setMessage(tr("Note will be reindexed."));
3159         logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
3160     }
3161     // Delete the note
3162     @SuppressWarnings("unused")
3163         private void deleteNote() {
3164         logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
3165         if (currentNote == null) 
3166                 return;
3167         if (currentNoteGuid.equals(""))
3168                 return;
3169         
3170         // If we are deleting non-trash notes
3171         if (currentNote.isActive()) { 
3172                 if (Global.verifyDelete()) {
3173                         if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
3174                                         QMessageBox.StandardButton.Yes, 
3175                                         QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3176                                         return;
3177                         }
3178                 }
3179                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
3180                         selectedNoteGUIDs.add(currentNoteGuid);
3181                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3182                         listManager.deleteNote(selectedNoteGUIDs.get(i));
3183                 }
3184         } else { 
3185                 // If we are deleting from the trash.
3186                 if (Global.verifyDelete()) {
3187                         if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
3188                                 QMessageBox.StandardButton.Yes, 
3189                                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
3190                                         return;
3191                         }
3192                 }
3193                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
3194                         selectedNoteGUIDs.add(currentNoteGuid);
3195                 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
3196                         for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
3197                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
3198                         if (modelIndex != null) {
3199                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3200                                 String tableGuid =  (String)ix.values().toArray()[0];
3201                                 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
3202                                         listManager.getNoteTableModel().removeRow(j);
3203                                         j=-1;
3204                                 }
3205                         }
3206                 }
3207                         listManager.expungeNote(selectedNoteGUIDs.get(i));
3208                 }
3209         }
3210         currentNoteGuid = "";
3211         listManager.loadNotesIndex();
3212         noteIndexUpdated(false);
3213         refreshEvernoteNote(true);
3214         scrollToGuid(currentNoteGuid);
3215         logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
3216     }
3217     // Add a new note
3218     @SuppressWarnings("unused")
3219         private void addNote() {
3220         logger.log(logger.HIGH, "Inside NeverNote.addNote");
3221 //      browserWindow.setEnabled(true);
3222         browserWindow.setReadOnly(false);
3223         saveNote();
3224         Calendar currentTime = new GregorianCalendar();
3225         String noteString = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
3226                 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
3227                 "<en-note>\n<br clear=\"none\" /></en-note>");
3228         
3229         Long l = new Long(currentTime.getTimeInMillis());
3230         String randint = new String(Long.toString(l));          
3231         
3232         // Find a notebook.  We first look for a selected notebook (the "All Notebooks" one doesn't count).  
3233         // Then we look
3234         // for the first non-archived notebook.  Finally, if nothing else we 
3235         // pick the first notebook in the list.
3236         String notebook = null;
3237         listManager.getNotebookIndex().get(0).getGuid();
3238         List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
3239         if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
3240                 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
3241                 notebook = currentSelectedNotebook.text(2);
3242         } else {
3243                 boolean found = false;
3244                 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
3245                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3246                         boolean match = false;
3247                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3248                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
3249                                         match = true;
3250                                         j = listManager.getArchiveNotebookIndex().size();
3251                                 }
3252                         }
3253                         if (!match)
3254                                 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
3255                 }
3256                 // Now we have a list of good notebooks, so we can look for the default
3257                 found = false;
3258                 for (int i=0; i<goodNotebooks.size(); i++) {
3259                         if (goodNotebooks.get(i).isDefaultNotebook()) {
3260                                 notebook = goodNotebooks.get(i).getGuid();
3261                                 found = true;
3262                                 i = goodNotebooks.size();
3263                         }
3264                 }
3265                 
3266                 if (goodNotebooks.size() > 0 && !found)
3267                         notebook = goodNotebooks.get(0).getGuid();
3268      
3269                 if (notebook==null)
3270                         notebook = listManager.getNotebookIndex().get(0).getGuid();             
3271         }
3272         
3273         Note newNote = new Note();
3274         newNote.setUpdateSequenceNum(0);
3275         newNote.setGuid(randint);
3276         newNote.setNotebookGuid(notebook);
3277         newNote.setTitle("");
3278         newNote.setContent(noteString);
3279         newNote.setDeleted(0);
3280         newNote.setCreated(System.currentTimeMillis());
3281         newNote.setUpdated(System.currentTimeMillis());
3282         newNote.setActive(true);
3283         NoteAttributes na = new NoteAttributes();
3284         na.setLatitude(0.0);
3285         na.setLongitude(0.0);
3286         na.setAltitude(0.0);
3287         newNote.setAttributes(new NoteAttributes());
3288                 newNote.setTagGuids(new ArrayList<String>());
3289                 newNote.setTagNames(new ArrayList<String>());
3290         
3291         // If new notes are to be created based upon the selected tags, then we need to assign the tags
3292         if (Global.newNoteWithSelectedTags()) { 
3293                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
3294                 QTreeWidgetItem currentSelection;
3295                 for (int i=0; i<selections.size(); i++) {
3296                         currentSelection = selections.get(i);
3297                         newNote.getTagGuids().add(currentSelection.text(2));
3298                         newNote.getTagNames().add(currentSelection.text(0));
3299                 }
3300         }
3301         
3302         conn.getNoteTable().addNote(newNote, true);
3303         listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3304         listManager.addNote(newNote);
3305 //      noteTableView.insertRow(newNote, true, -1);
3306         
3307         currentNote = newNote;
3308         currentNoteGuid = currentNote.getGuid();
3309         refreshEvernoteNote(true);
3310         listManager.countNotebookResults(listManager.getNoteIndex());
3311         browserWindow.titleLabel.setFocus();
3312         browserWindow.titleLabel.selectAll();
3313 //      notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
3314         logger.log(logger.HIGH, "Leaving NeverNote.addNote");
3315     }
3316     // Restore a note from the trash;
3317     @SuppressWarnings("unused")
3318         private void restoreNote() {
3319         waitCursor(true);
3320                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
3321                         selectedNoteGUIDs.add(currentNoteGuid);
3322                 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3323                         listManager.restoreNote(selectedNoteGUIDs.get(i));
3324                 }
3325         currentNoteGuid = "";
3326         listManager.loadNotesIndex();
3327         noteIndexUpdated(false);
3328         waitCursor(false);
3329     }
3330     // Search a note for specific txt
3331     @SuppressWarnings("unused")
3332         private void findText() {
3333         find.show();
3334         find.setFocusOnTextField();
3335     }
3336     @SuppressWarnings("unused")
3337         private void doFindText() {
3338         browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
3339         find.setFocus();
3340     }
3341     // Signal received that note content has changed.  Normally we just need the guid to remove
3342     // it from the cache.
3343     @SuppressWarnings("unused")
3344         private void invalidateNoteCache(String guid, String content) {
3345         String v = noteCache.remove(guid);
3346         if (content != null) {
3347                 //noteCache.put(guid, content);
3348         }
3349     }
3350     // Signal received that a note guid has changed
3351     @SuppressWarnings("unused")
3352         private void noteGuidChanged(String oldGuid, String newGuid) {
3353         if (noteCache.containsKey(oldGuid)) {
3354                 String cache = noteCache.get(oldGuid);
3355                 noteCache.put(newGuid, cache);
3356                 noteCache.remove(oldGuid);
3357         }
3358         listManager.updateNoteGuid(oldGuid, newGuid, false);
3359         if (currentNoteGuid.equals(oldGuid)) {
3360                 if (currentNote != null)
3361                         currentNote.setGuid(newGuid);
3362                 currentNoteGuid = newGuid;
3363         }
3364         for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3365                 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
3366                         noteTableView.proxyModel.addGuid(newGuid);
3367                         i=listManager.getNoteIndex().size();
3368                 }
3369         }
3370                 updateListGuid(oldGuid, newGuid);
3371     }
3372     // Toggle the note editor button bar
3373     private void toggleEditorButtonBar() {
3374         if (browserWindow.buttonsVisible) {
3375                 browserWindow.hideButtons();
3376                 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
3377 //              Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3378         } else {
3379                 browserWindow.buttonsVisible = true;
3380                 showEditorButtons();
3381         }
3382         Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3383     }
3384     // Show editor buttons
3385     private void showEditorButtons() {
3386                 browserWindow.undoButton.setVisible(false);
3387                 browserWindow.redoButton.setVisible(false);
3388                 browserWindow.cutButton.setVisible(false);
3389                 browserWindow.copyButton.setVisible(false);
3390                 browserWindow.pasteButton.setVisible(false);
3391                 browserWindow.strikethroughButton.setVisible(false);
3392                 browserWindow.underlineButton.setVisible(false);
3393                 browserWindow.boldButton.setVisible(false);
3394                 browserWindow.italicButton.setVisible(false);
3395                 browserWindow.hlineButton.setVisible(false);
3396                 browserWindow.indentButton.setVisible(false);
3397                 browserWindow.outdentButton.setVisible(false);
3398                 browserWindow.fontList.setVisible(false);
3399                 browserWindow.fontSize.setVisible(false);
3400                 browserWindow.fontColor.setVisible(false);
3401                 browserWindow.fontHilight.setVisible(false);
3402                 browserWindow.leftAlignButton.setVisible(false);
3403                 browserWindow.centerAlignButton.setVisible(false);
3404                 browserWindow.rightAlignButton.setVisible(false);
3405                 browserWindow.indentButton.setVisible(false);
3406                 browserWindow.outdentButton.setVisible(false);
3407
3408                 browserWindow.undoButton.setVisible(Global.isEditorButtonVisible("undo"));
3409                 browserWindow.redoButton.setVisible(Global.isEditorButtonVisible("redo"));
3410                 browserWindow.cutButton.setVisible(Global.isEditorButtonVisible("cut"));
3411                 browserWindow.copyButton.setVisible(Global.isEditorButtonVisible("copy"));
3412                 browserWindow.pasteButton.setVisible(Global.isEditorButtonVisible("paste"));
3413                 browserWindow.strikethroughButton.setVisible(Global.isEditorButtonVisible("strikethrough"));
3414                 browserWindow.underlineButton.setVisible(Global.isEditorButtonVisible("underline"));
3415                 browserWindow.boldButton.setVisible(Global.isEditorButtonVisible("bold"));
3416                 browserWindow.italicButton.setVisible(Global.isEditorButtonVisible("italic"));
3417                 browserWindow.hlineButton.setVisible(Global.isEditorButtonVisible("hline"));
3418                 browserWindow.indentButton.setVisible(Global.isEditorButtonVisible("indent"));
3419                 browserWindow.outdentButton.setVisible(Global.isEditorButtonVisible("outdent"));
3420                 browserWindow.bulletListButton.setVisible(Global.isEditorButtonVisible("bulletList"));
3421                 browserWindow.numberListButton.setVisible(Global.isEditorButtonVisible("numberList"));
3422                 browserWindow.fontList.setVisible(Global.isEditorButtonVisible("font"));
3423                 browserWindow.fontSize.setVisible(Global.isEditorButtonVisible("fontSize"));
3424                 browserWindow.fontColor.setVisible(Global.isEditorButtonVisible("fontColor"));
3425                 browserWindow.fontHilight.setVisible(Global.isEditorButtonVisible("fontHilight"));
3426                 browserWindow.leftAlignButton.setVisible(Global.isEditorButtonVisible("alignLeft"));
3427                 browserWindow.centerAlignButton.setVisible(Global.isEditorButtonVisible("alignCenter"));
3428                 browserWindow.rightAlignButton.setVisible(Global.isEditorButtonVisible("alignRight"));
3429     }
3430     private void duplicateNote(String guid) {
3431                 
3432                 Calendar currentTime = new GregorianCalendar();
3433                 Long l = new Long(currentTime.getTimeInMillis());
3434                 String newGuid = new String(Long.toString(l));
3435                                         
3436                 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
3437                 Note newNote = oldNote.deepCopy();
3438                 newNote.setGuid(newGuid);
3439                 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
3440                 oldNote.setResources(resList);
3441                 duplicateNote(oldNote);
3442         }
3443         private void duplicateNote(Note oldNote) {
3444                 waitCursor(true);
3445                 // Now that we have a good notebook guid, we need to move the conflicting note
3446                 // to the local notebook
3447                 Calendar currentTime = new GregorianCalendar();
3448                 Long l = new Long(currentTime.getTimeInMillis());
3449                 String newGuid = new String(Long.toString(l));
3450                                         
3451                 Note newNote = oldNote.deepCopy();
3452                 newNote.setUpdateSequenceNum(0);
3453                 newNote.setGuid(newGuid);
3454                 newNote.setDeleted(0);
3455                 newNote.setActive(true);
3456                 List<Resource> resList = oldNote.getResources();
3457                 if (resList == null)
3458                         resList = new ArrayList<Resource>();
3459                 long prevGuid = 0;
3460                 for (int i=0; i<resList.size(); i++) {
3461                         l = prevGuid;
3462                         while (l == prevGuid) {
3463                                 currentTime = new GregorianCalendar();
3464                                 l = new Long(currentTime.getTimeInMillis());
3465                         }
3466                         prevGuid = l;
3467                         String newResGuid = new String(Long.toString(l));
3468                         resList.get(i).setNoteGuid(newGuid);
3469                         resList.get(i).setGuid(newResGuid);
3470                         resList.get(i).setUpdateSequenceNum(0);
3471                         resList.get(i).setActive(true);
3472                         conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
3473                 }
3474                 newNote.setResources(resList);
3475                 listManager.addNote(newNote);
3476                 conn.getNoteTable().addNote(newNote, true);
3477                 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3478                 noteTableView.insertRow(newNote, true, -1);
3479                 listManager.countNotebookResults(listManager.getNoteIndex());
3480                 waitCursor(false);
3481         }
3482         // Merge notes
3483         @SuppressWarnings("unused")
3484         private void mergeNotes() {
3485                 logger.log(logger.HIGH, "Merging notes");
3486                 waitCursor(true);
3487                 saveNote();
3488                 String masterGuid = null;
3489                 List<String> sources = new ArrayList<String>();
3490                 QModelIndex index;
3491                 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
3492                         int r = noteTableView.selectionModel().selectedRows().get(i).row();
3493                         index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
3494                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3495                 if (i == 0) 
3496                         masterGuid = (String)ix.values().toArray()[0];
3497                 else 
3498                         sources.add((String)ix.values().toArray()[0]);  
3499                 }
3500                 
3501                 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
3502                 logger.log(logger.EXTREME, "Children count: "+sources.size());
3503                 mergeNoteContents(masterGuid, sources);
3504                 currentNoteGuid = masterGuid;
3505                 noteIndexUpdated(false);
3506                 refreshEvernoteNote(true);
3507                 waitCursor(false);
3508         }
3509         private void mergeNoteContents(String targetGuid, List<String> sources) {
3510                 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
3511                 String newContent = target.getContent();
3512                 newContent = newContent.replace("</en-note>", "<br></br>");
3513                 
3514                 for (int i=0; i<sources.size(); i++) {
3515                         Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
3516                         if (source.isSetTitle()) {
3517                                 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
3518                         }
3519                         String sourceContent = source.getContent();
3520                         logger.log(logger.EXTREME, "Merging contents into note");
3521                         logger.log(logger.EXTREME, sourceContent);
3522                         logger.log(logger.EXTREME, "End of content");
3523                         int startOfNote = sourceContent.indexOf("<en-note>");
3524                         sourceContent = sourceContent.substring(startOfNote+9);
3525                         int endOfNote = sourceContent.indexOf("</en-note>");
3526                         sourceContent = sourceContent.substring(0,endOfNote);
3527                         newContent = newContent + sourceContent;
3528                         logger.log(logger.EXTREME, "New note content");
3529                         logger.log(logger.EXTREME, newContent);
3530                         logger.log(logger.EXTREME, "End of content");
3531                         for (int j=0; j<source.getResourcesSize(); j++) {
3532                                 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
3533                                 Resource r = source.getResources().get(j);
3534                                 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3535                                 
3536                                 Calendar currentTime = new GregorianCalendar();
3537                                 Long l = new Long(currentTime.getTimeInMillis());
3538                                                         
3539                                 long prevGuid = 0;
3540                                 l = prevGuid;
3541                                 while (l == prevGuid) {
3542                                         currentTime = new GregorianCalendar();
3543                                         l = new Long(currentTime.getTimeInMillis());
3544                                 }
3545                                 String newResGuid = new String(Long.toString(l));
3546                                 newRes.setNoteGuid(targetGuid);
3547                                 newRes.setGuid(newResGuid);
3548                                 newRes.setUpdateSequenceNum(0);
3549                                 newRes.setActive(true);
3550                                 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
3551                         }
3552                 }
3553                 logger.log(logger.EXTREME, "Updating note");
3554                 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
3555                 for (int i=0; i<sources.size(); i++) {
3556                         logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
3557                         listManager.deleteNote(sources.get(i));
3558                 }
3559                 logger.log(logger.EXTREME, "Exiting merge note");
3560         }
3561         // A resource within a note has had a guid change 
3562         @SuppressWarnings("unused")
3563         private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
3564                 if (!oldGuid.equals(newGuid))
3565                         Global.resourceMap.put(oldGuid, newGuid);
3566         }
3567         // View a thumbnail of the note
3568         public void thumbnailView() {
3569                 
3570                 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
3571                 QFile thumbnail = new QFile(thumbnailName);
3572                 if (!thumbnail.exists()) {
3573                         
3574                         QImage img = new QImage();
3575                         img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
3576                         thumbnailViewer.setThumbnail(img);
3577                 } else
3578                         thumbnailViewer.setThumbnail(thumbnailName);
3579                 if (!thumbnailViewer.isVisible()) 
3580                         thumbnailViewer.showFullScreen();
3581         }
3582         // An error happened while saving a note.  Inform the user
3583         @SuppressWarnings("unused")
3584         private void saveRunnerError(String guid, String msg) {
3585                 if (msg == null) {
3586                         String title = "*Unknown*";
3587                         for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
3588                                 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
3589                                         title = listManager.getMasterNoteIndex().get(i).getTitle();
3590                                         i=listManager.getMasterNoteIndex().size();
3591                                 }
3592                         }
3593                         msg = "An error has happened saving the note \"" +title+
3594                         "\". \nThis is probably due to a document that is too complex for Nevernote to process.  "+
3595                         "As a result, changes to the note may not be saved.\n\nPlease review the note for any potential problems.";
3596                         
3597                         QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
3598                 }
3599         }
3600         
3601         //**********************************************************
3602     //**********************************************************
3603     //* Online user actions
3604     //**********************************************************
3605     //**********************************************************
3606     private void setupOnlineMenu() {
3607         if (!Global.isConnected) {
3608                 menuBar.noteOnlineHistoryAction.setEnabled(false);
3609                 return;
3610         } else {
3611                 menuBar.noteOnlineHistoryAction.setEnabled(true);
3612         }
3613     }
3614     @SuppressWarnings("unused")
3615         private void viewNoteHistory() {
3616         if (currentNoteGuid == null || currentNoteGuid.equals("")) 
3617                 return;
3618         if (currentNote.getUpdateSequenceNum() == 0) {
3619                 setMessage(tr("Note has never been synchronized."));
3620                         QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
3621                         return;
3622         }
3623         
3624         setMessage(tr("Getting Note History"));
3625         waitCursor(true);
3626         Note currentOnlineNote = null;
3627         versions = null;
3628         try {
3629                 if (Global.isPremium())
3630                         versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
3631                 else
3632                         versions = new ArrayList<NoteVersionId>();
3633                 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
3634                 } catch (EDAMUserException e) {
3635                         setMessage("EDAMUserException: " +e.getMessage());
3636                         return;
3637                 } catch (EDAMSystemException e) {
3638                         setMessage("EDAMSystemException: " +e.getMessage());
3639                         return;
3640                 } catch (EDAMNotFoundException e) {
3641                         setMessage(tr("Note not found on server."));
3642                         QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
3643                         return;
3644                 } catch (TException e) {
3645                         setMessage("EDAMTransactionException: " +e.getMessage());
3646                         return;
3647                 }
3648                 
3649                 // If we've gotten this far, we have a good note.
3650                 if (historyWindow == null) {
3651                         historyWindow = new OnlineNoteHistory(conn);
3652                         historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
3653                         historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
3654                         historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
3655                 } else {
3656                         historyWindow.historyCombo.clear();
3657                 }
3658                 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
3659                 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
3660                         isDirty = true;
3661                 historyWindow.setCurrent(isDirty);
3662                 
3663                 loadHistoryWindowContent(currentOnlineNote);
3664                 historyWindow.load(versions);
3665                 setMessage(tr("History retrieved"));
3666                 waitCursor(false);
3667                 historyWindow.exec();
3668     }
3669     private Note reloadHistoryWindow(String selection) {
3670         waitCursor(true);
3671                 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
3672                 String dateTimeFormat = new String(fmt);
3673                 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
3674                 int index = -1;
3675                 int usn = 0;
3676                 
3677                 for (int i=0; i<versions.size(); i++) {
3678                         StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getServiceUpdated()));
3679                         if (versionDate.toString().equals(selection))
3680                                 index = i;
3681                 }
3682                 
3683                 if (index > -1 || selection.indexOf("Current") > -1) {
3684                         Note historyNote = null;
3685                         try {
3686                                 if (index > -1) {
3687                                         usn = versions.get(index).getUpdateSequenceNum();
3688                                         historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
3689                                 } else
3690                                         historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
3691                         } catch (EDAMUserException e) {
3692                                 setMessage("EDAMUserException: " +e.getMessage());
3693                                 waitCursor(false);
3694                                 return null;
3695                         } catch (EDAMSystemException e) {
3696                                 setMessage("EDAMSystemException: " +e.getMessage());
3697                                 waitCursor(false);
3698                                 return null;
3699                         } catch (EDAMNotFoundException e) {
3700                                 setMessage("EDAMNotFoundException: " +e.getMessage());
3701                                 waitCursor(false);
3702                                 return null;
3703                         } catch (TException e) {
3704                                 setMessage("EDAMTransactionException: " +e.getMessage());
3705                                 waitCursor(false);
3706                                 return null;
3707                         }
3708                         
3709                         waitCursor(false);
3710                         if (historyNote != null) 
3711                                 historyWindow.setContent(historyNote);
3712                         return historyNote;
3713                 }
3714                 waitCursor(false);
3715                 return null;
3716     }
3717     private void loadHistoryWindowContent(Note note) {
3718         note.setUpdateSequenceNum(0);
3719                 historyWindow.setContent(note); 
3720     }
3721     @SuppressWarnings("unused")
3722         private void restoreHistoryNoteAsNew() {
3723         setMessage(tr("Restoring as new note."));
3724         duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
3725         setMessage(tr("Note has been restored as a new note."));
3726     }
3727     @SuppressWarnings("unused")
3728         private void restoreHistoryNote() {
3729         setMessage(tr("Restoring note."));
3730         Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
3731         conn.getNoteTable().expungeNote(n.getGuid(), true, false);
3732         n.setActive(true);
3733         n.setDeleted(0);
3734                 for (int i=0; i<n.getResourcesSize(); i++) {
3735                         n.getResources().get(i).setActive(true);
3736                         conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
3737                 }
3738         listManager.addNote(n);
3739         conn.getNoteTable().addNote(n, true);
3740         refreshEvernoteNote(true);
3741         setMessage(tr("Note has been restored."));
3742     }
3743     
3744     
3745     
3746         //**********************************************************
3747         //**********************************************************
3748         //* XML Modifying methods
3749         //**********************************************************
3750         //**********************************************************
3751     // find the appropriate icon for an attachment
3752     private String findIcon(String appl) {
3753         logger.log(logger.HIGH, "Entering NeverNote.findIcon");
3754         appl = appl.toLowerCase();
3755         String relativePath = appl + ".png";
3756         File f = Global.getFileManager().getImageDirFile(relativePath);
3757         if (f.exists()) {
3758             return relativePath;
3759         }
3760         if (f.exists())
3761                 return appl+".png";
3762         logger.log(logger.HIGH, "Leaving NeverNote.findIcon");
3763         return "attachment.png";
3764     }
3765     // Modify the en-media tag into an attachment
3766     private void modifyApplicationTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {
3767         logger.log(logger.HIGH, "Entering NeverNote.modifyApplicationTags");
3768         if (appl.equalsIgnoreCase("vnd.evernote.ink"))
3769                 inkNote = true;
3770         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());
3771         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);
3772         if (r == null || r.getData() == null) 
3773                 resourceErrorMessage();
3774                 if (r!= null) {
3775                         if (r.getData()!=null) {
3776                                 // Did we get a generic applicaiton?  Then look at the file name to 
3777                                 // try and find a good application type for the icon
3778                                 if (appl.equalsIgnoreCase("octet-stream")) {
3779                                         if (r.getAttributes() != null && r.getAttributes().getFileName() != null) {
3780                                                 String fn = r.getAttributes().getFileName();
3781                                                 int pos = fn.lastIndexOf(".");
3782                                                 if (pos > -1) {
3783                                                         appl = fn.substring(pos+1);
3784                                                 }
3785                                         }
3786                                 }
3787                                 
3788                                 String fileDetails = null;
3789                                 if (r.getAttributes() != null && r.getAttributes().getFileName() != null && !r.getAttributes().getFileName().equals(""))
3790                                         fileDetails = r.getAttributes().getFileName();
3791                                 String contextFileName;
3792                                 FileManager fileManager = Global.getFileManager();
3793                 if (fileDetails != null && !fileDetails.equals("")) {
3794                                         enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +fileDetails);
3795                                         contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + fileDetails);
3796                                 } else { 
3797                                         enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +appl);
3798                                         contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + appl);
3799                                 }
3800                                 contextFileName = contextFileName.replace("\\", "/");
3801                                 enmedia.setAttribute("onContextMenu", "window.jambi.resourceContextMenu('" +contextFileName +"');");
3802                                 if (fileDetails == null || fileDetails.equals(""))
3803                                         fileDetails = "";
3804                                 enmedia.setAttribute("en-tag", "en-media");
3805                                 enmedia.setAttribute("guid", r.getGuid());
3806                                 enmedia.setTagName("a");
3807                                 QDomElement newText = doc.createElement("img");
3808                                 boolean goodPreview = false;
3809                                 String filePath = "";
3810                                 if (appl.equalsIgnoreCase("pdf") && Global.pdfPreview()) {
3811                                         String fileName;
3812                                         Resource res = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3813                                         if (res.getAttributes() != null && 
3814                                                         res.getAttributes().getFileName() != null && 
3815                                                         !res.getAttributes().getFileName().trim().equals(""))
3816                                                 fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();
3817                                         else
3818                                                 fileName = res.getGuid()+".pdf";
3819                                         QFile file = new QFile(fileManager.getResDirPath(fileName));
3820                                 QFile.OpenMode mode = new QFile.OpenMode();
3821                                 mode.set(QFile.OpenModeFlag.WriteOnly);
3822                                 file.open(mode);
3823                                 QDataStream out = new QDataStream(file);
3824                                 Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);
3825                                         QByteArray binData = new QByteArray(resBinary.getData().getBody());
3826                                         resBinary = null;
3827                                 out.writeBytes(binData.toByteArray());
3828                                 file.close();
3829                                 PDFPreview pdfPreview = new PDFPreview();
3830                                         goodPreview = pdfPreview.setupPreview(file.fileName(), appl,0);
3831                                         if (goodPreview) {
3832                                                 QDomElement span = doc.createElement("span");
3833                                                 QDomElement table = doc.createElement("table");
3834                                                 span.setAttribute("pdfNavigationTable", "true");
3835                                                 QDomElement tr = doc.createElement("tr");
3836                                                 QDomElement td = doc.createElement("td");
3837                                                 QDomElement left = doc.createElement("img");
3838                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3839                                                 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3840                                                 left.setAttribute("onMouseOver", "style.cursor='hand'");
3841                                                 QDomElement right = doc.createElement("img");
3842                                                 right.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3843                                                 left.setAttribute("onMouseDown", "window.jambi.previousPage('" +file.fileName() +"')");
3844                                                 // NFC TODO: should these be file:// URLs?
3845                                                 left.setAttribute("src", Global.getFileManager().getImageDirPath("small_left.png"));
3846                                                 right.setAttribute("src", Global.getFileManager().getImageDirPath("small_right.png"));
3847                                                 right.setAttribute("onMouseOver", "style.cursor='hand'");
3848                                                 
3849                                                 table.appendChild(tr);
3850                                                 tr.appendChild(td);
3851                                                 td.appendChild(left);
3852                                                 td.appendChild(right);
3853                                                 span.appendChild(table);
3854                                                 enmedia.parentNode().insertBefore(span, enmedia);
3855                                         } 
3856                                         filePath = fileName+".png";
3857                                 }
3858                                 String icon = findIcon(appl);
3859                                 if (icon.equals("attachment.png"))
3860                                         icon = findIcon(fileDetails.substring(fileDetails.indexOf(".")+1));
3861                                 // NFC TODO: should this be a 'file://' URL?
3862                                 newText.setAttribute("src", Global.getFileManager().getImageDirPath(icon));
3863                                 if (goodPreview) {
3864                                 // NFC TODO: should this be a 'file://' URL?
3865                                         newText.setAttribute("src", fileManager.getResDirPath(filePath));
3866                                         newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");
3867                                 }
3868                                 newText.setAttribute("title", fileDetails);
3869                                 enmedia.removeChild(enmedia.firstChild());
3870                                 
3871                                 enmedia.appendChild(newText);
3872                         }
3873                 }
3874                 logger.log(logger.HIGH, "Leaving NeverNote.modifyApplicationTags");
3875     }
3876     // Modify the en-to tag into an input field
3877     private void modifyTodoTags(QDomElement todo) {
3878         logger.log(logger.HIGH, "Entering NeverNote.modifyTodoTags");
3879                 todo.setAttribute("type", "checkbox");
3880                 String checked = todo.attribute("checked");
3881                 todo.removeAttribute("checked");
3882                 if (checked.equalsIgnoreCase("true"))
3883                         todo.setAttribute("checked", "");
3884                 else
3885                         todo.setAttribute("unchecked","");
3886                 todo.setAttribute("value", checked);
3887                 todo.setAttribute("onClick", "value=checked;window.jambi.contentChanged(); ");
3888                 todo.setTagName("input");
3889                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTodoTags");
3890     }
3891     // Modify any cached todo tags that may have changed
3892     private String modifyCachedTodoTags(String note) {
3893         logger.log(logger.HIGH, "Entering NeverNote.modifyCachedTodoTags");
3894         StringBuffer html = new StringBuffer(note);
3895                 for (int i=html.indexOf("<input", 0); i>-1; i=html.indexOf("<input", i)) {
3896                         int endPos =html.indexOf(">",i+1);
3897                         String input = html.substring(i,endPos);
3898                         if (input.indexOf("value=\"true\"") > 0) 
3899                                 input = input.replace(" unchecked=\"\"", " checked=\"\"");
3900                         else
3901                                 input = input.replace(" checked=\"\"", " unchecked=\"\"");
3902                         html.replace(i, endPos, input);
3903                         i++;
3904                 }
3905                 logger.log(logger.HIGH, "Leaving NeverNote.modifyCachedTodoTags");
3906                 return html.toString();
3907     }
3908     // Modify the en-media tag into an image tag so it can be displayed.
3909     private void modifyImageTags(QDomElement docElem, QDomElement enmedia, QDomAttr hash) {
3910         logger.log(logger.HIGH, "Entering NeverNote.modifyImageTags");
3911         String type = enmedia.attribute("type");
3912         if (type.startsWith("image/"))
3913                 type = "."+type.substring(6);
3914         else
3915                 type="";
3916         
3917         String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNoteGuid, hash.value());
3918         QFile tfile = new QFile(Global.getFileManager().getResDirPath(resGuid + type));
3919         if (!tfile.exists()) {
3920                 Resource r = null;
3921                 if (resGuid != null)
3922                         r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid,true);
3923                         if (r==null || r.getData() == null || r.getData().getBody().length == 0)
3924                                 resourceErrorMessage();
3925                         if (r!= null && r.getData() != null && r.getData().getBody().length > 0) {
3926                                 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));
3927                                 QByteArray binData = new QByteArray(r.getData().getBody());
3928                                 tfile.write(binData);
3929                                 tfile.close();
3930                                 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3931                                 enmedia.setAttribute("en-tag", "en-media");
3932                                 enmedia.setNodeValue("");
3933                         enmedia.setAttribute("guid", r.getGuid());
3934                         enmedia.setTagName("img");
3935                 }
3936         }
3937                 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3938                 enmedia.setAttribute("en-tag", "en-media");
3939                 enmedia.setAttribute("onContextMenu", "window.jambi.imageContextMenu('" +tfile.fileName()  +"');");
3940                 enmedia.setNodeValue("");
3941                 enmedia.setAttribute("guid", resGuid);
3942                 enmedia.setTagName("img");
3943
3944                 logger.log(logger.HIGH, "Leaving NeverNote.modifyImageTags");
3945     }
3946         // Modify tags from Evernote specific things to XHTML tags.
3947         private QDomDocument modifyTags(QDomDocument doc) {
3948                 logger.log(logger.HIGH, "Entering NeverNote.modifyTags");
3949                 if (tempFiles == null)
3950                         tempFiles = new ArrayList<QTemporaryFile>();
3951                 tempFiles.clear();
3952                 QDomElement docElem = doc.documentElement();
3953                 
3954                 // Modify en-media tags
3955                 QDomNodeList anchors = docElem.elementsByTagName("en-media");
3956                 int enMediaCount = anchors.length();
3957                 for (int i=enMediaCount-1; i>=0; i--) {
3958                         QDomElement enmedia = anchors.at(i).toElement();
3959                         if (enmedia.hasAttribute("type")) {
3960                                 QDomAttr attr = enmedia.attributeNode("type");
3961                                 QDomAttr hash = enmedia.attributeNode("hash");
3962                                 String[] type = attr.nodeValue().split("/");
3963                                 String appl = type[1];
3964                                 
3965                                 if (type[0] != null) {
3966                                         if (type[0].equals("image")) {
3967                                                 modifyImageTags(docElem, enmedia, hash);
3968                                         }
3969                                         if (!type[0].equals("image")) {
3970                                                 modifyApplicationTags(doc, docElem, enmedia, hash, appl);
3971                                         }
3972                                 }
3973                         }
3974                 }
3975                 
3976                 // Modify todo tags
3977                 anchors = docElem.elementsByTagName("en-todo");
3978                 int enTodoCount = anchors.length();
3979                 for (int i=enTodoCount-1; i>=0; i--) {
3980                         QDomElement enmedia = anchors.at(i).toElement();
3981                         modifyTodoTags(enmedia);
3982                 }
3983                 
3984                 // Modify en-crypt tags
3985                 anchors = docElem.elementsByTagName("en-crypt");
3986                 int enCryptLen = anchors.length();
3987                 for (int i=enCryptLen-1; i>=0; i--) {
3988                         QDomElement enmedia = anchors.at(i).toElement();
3989                         enmedia.setAttribute("contentEditable","false");
3990                         enmedia.setAttribute("src", Global.getFileManager().getImageDirPath("encrypt.png"));
3991                         enmedia.setAttribute("en-tag","en-crypt");
3992                         enmedia.setAttribute("alt", enmedia.text());
3993                         Global.cryptCounter++;
3994                         enmedia.setAttribute("id", "crypt"+Global.cryptCounter.toString());
3995                         String encryptedText = enmedia.text();
3996                         
3997                         // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
3998                         if (encryptedText.endsWith("\n"))
3999                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
4000                         if (encryptedText.endsWith("\r"))
4001                                 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
4002                         
4003                         // Add the commands
4004                         String hint = enmedia.attribute("hint");
4005                         hint = hint.replace("'","&apos;");
4006                         enmedia.setAttribute("onClick", "window.jambi.decryptText('crypt"+Global.cryptCounter.toString()+"', '"+encryptedText+"', '"+hint+"');");
4007                         enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
4008                         enmedia.setTagName("img");
4009                         enmedia.removeChild(enmedia.firstChild());   // Remove the actual encrypted text
4010                 }
4011
4012                 logger.log(logger.HIGH, "Leaving NeverNote.modifyTags");
4013                 return doc;
4014         }
4015         // Rebuild the note HTML to something usable
4016         private String rebuildNoteHTML(String noteGuid, String note) {
4017                 logger.log(logger.HIGH, "Entering NeverNote.rebuildNoteHTML");
4018                 logger.log(logger.EXTREME, "Note guid: " +noteGuid);
4019                 logger.log(logger.EXTREME, "Note Text:" +note);
4020                 QDomDocument doc = new QDomDocument();
4021                 QDomDocument.Result result = doc.setContent(note);
4022                 if (!result.success) {
4023                         logger.log(logger.MEDIUM, "Parse error when rebuilding HTML");
4024                         logger.log(logger.MEDIUM, "Note guid: " +noteGuid);
4025                         logger.log(logger.EXTREME, "Start of unmodified note HTML");
4026                         logger.log(logger.EXTREME, note);
4027                         logger.log(logger.EXTREME, "End of unmodified note HTML");
4028                         return note;
4029                 }
4030
4031                 if (tempFiles == null)
4032                         tempFiles = new ArrayList<QTemporaryFile>();
4033                 tempFiles.clear();
4034                 
4035                 doc = modifyTags(doc);
4036                 doc = addHilight(doc);
4037                 QDomElement docElem = doc.documentElement();
4038                 docElem.setTagName("Body");
4039 //              docElem.setAttribute("bgcolor", "green");
4040                 logger.log(logger.EXTREME, "Rebuilt HTML:");
4041                 logger.log(logger.EXTREME, doc.toString());     
4042                 logger.log(logger.HIGH, "Leaving NeverNote.rebuildNoteHTML");
4043                 // Fix the stupid problem where inserting an <img> tag after an <a> tag (which is done
4044                 // to get the <en-media> application tag to work properly) causes spaces to be inserted
4045                 // between the <a> & <img>.  This messes things up later.  This is an ugly hack.
4046                 StringBuffer html = new StringBuffer(doc.toString());
4047                 for (int i=html.indexOf("<a en-tag=\"en-media\" ", 0); i>-1; i=html.indexOf("<a en-tag=\"en-media\" ", i)) {
4048                         i=html.indexOf(">\n",i+1);
4049                         int z = html.indexOf("<img",i);
4050                         for (int j=z-1; j>i; j--) 
4051                                 html.deleteCharAt(j);
4052                         i=html.indexOf("/>", z+1);
4053                         z = html.indexOf("</a>",i);
4054                         for (int j=z-1; j>i+1; j--) 
4055                                 html.deleteCharAt(j);
4056                 } 
4057                 return html.toString();
4058         }       
4059         // Scan and do hilighting of words
4060         private QDomDocument addHilight(QDomDocument doc) {
4061                 EnSearch e = listManager.getEnSearch();
4062                 if (e.hilightWords == null || e.hilightWords.size() == 0)
4063                         return doc;
4064                 XMLInsertHilight hilight = new XMLInsertHilight(doc, listManager.getEnSearch().hilightWords);
4065                 return hilight.getDoc();
4066         }
4067
4068         // An error has happended fetching a resource.  let the user know
4069         private void resourceErrorMessage() {
4070                 if (inkNote)
4071                         return;
4072                 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4073                 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4074                 "In a perfect world this wouldn't happen, but it has.\n" +
4075                 "It is embarasing when a program like me, designed to save all your\n"+
4076                 "precious data, has a problem finding data.\n\n" +
4077                 "I guess life isn't fair, but I'll survive.  Somehow...\n\n" +
4078                 "In the mean time, I'm not going to let you make changes to this note.\n" +
4079                 "Don't get angry.  I'm doing it to prevent you from messing up\n"+
4080                 "this note on the Evernote servers.  Sorry."+
4081                 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4082                 inkNote = true;
4083 ////            browserWindow.setEnabled(false);
4084                 browserWindow.setReadOnly(true);
4085         }
4086
4087         
4088         
4089         
4090         //**********************************************************
4091         //**********************************************************
4092         //* Timer functions
4093         //**********************************************************
4094         //**********************************************************
4095         // We should now do a sync with Evernote
4096         private void syncTimer() {
4097                 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
4098                 syncRunner.syncNeeded = true;
4099                 syncRunner.disableUploads = Global.disableUploads;
4100                 syncStart();
4101                 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
4102         }
4103         private void syncStart() {
4104                 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
4105                 saveNote();
4106                 if (!syncRunning && Global.isConnected) {
4107                         syncRunner.setConnected(true);
4108                         syncRunner.setKeepRunning(Global.keepRunning);
4109                         syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
4110                         
4111                         if (syncThreadsReady > 0) {
4112                                 saveNoteIndexWidth();
4113                                 if (syncRunner.addWork("SYNC")) {
4114                                         syncRunning = true;
4115                                         syncRunner.syncNeeded = true;
4116                                         syncThreadsReady--;
4117                                 }                               
4118                         }
4119                 }
4120                 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
4121         }
4122         @SuppressWarnings("unused")
4123         private void syncThreadComplete(Boolean refreshNeeded) {
4124                 setMessage(tr("Finalizing Synchronization"));
4125                 syncThreadsReady++;
4126                 syncRunning = false;
4127                 syncRunner.syncNeeded = false;
4128                 synchronizeAnimationTimer.stop();
4129                 synchronizeButton.setIcon(synchronizeAnimation.get(0));
4130                 saveNote();
4131                 if (currentNote == null) {
4132                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
4133                 }
4134                 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
4135                 noteIndexUpdated(false);
4136                 noteTableView.selectionModel().blockSignals(true);
4137                 scrollToGuid(currentNoteGuid);
4138                 noteTableView.selectionModel().blockSignals(false);
4139                 refreshEvernoteNote(false);
4140                 scrollToGuid(currentNoteGuid);
4141                 waitCursor(false);
4142                 setMessage(tr("Synchronization Complete"));
4143                 logger.log(logger.MEDIUM, "Sync complete.");
4144         }   
4145         public void saveUploadAmount(long t) {
4146                 Global.saveUploadAmount(t);
4147         }
4148         public void saveUserInformation(User user) {
4149                 Global.saveUserInformation(user);
4150         }
4151         public void saveEvernoteUpdateCount(int i) {
4152                 Global.saveEvernoteUpdateCount(i);
4153         }
4154         public void refreshLists() {
4155                 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
4156                 updateQuotaBar();
4157                 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
4158                 tagIndexUpdated(true);
4159                 notebookIndexUpdated();
4160                 savedSearchIndexUpdated();
4161                 listManager.loadNotesIndex();
4162
4163                 noteTableView.selectionModel().blockSignals(true);
4164         noteIndexUpdated(true);
4165                 noteTableView.selectionModel().blockSignals(false);
4166                 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
4167         }
4168
4169         
4170         @SuppressWarnings("unused")
4171         private void authTimer() {
4172         Calendar cal = Calendar.getInstance();
4173                 
4174         // If we are not connected let's get out of here
4175         if (!Global.isConnected)
4176                 return;
4177                 
4178                 // If this is the first time through, then we need to set this
4179  //             if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime) 
4180 //                      syncRunner.authRefreshTime = cal.getTimeInMillis();
4181                 
4182 //              long now = new Date().getTime();
4183 //              if (now > Global.authRefreshTime && Global.isConnected) {
4184                         syncRunner.authRefreshNeeded = true;
4185                         syncStart();
4186 //              }
4187         }
4188         @SuppressWarnings("unused")
4189         private void authRefreshComplete(boolean goodSync) {
4190                 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
4191                 Global.isConnected = syncRunner.isConnected;
4192                 if (goodSync) {
4193 //                      authTimer.start((int)syncRunner.authTimeRemaining/4);
4194                         authTimer.start(1000*60*15);
4195                         logger.log(logger.LOW, "Authentication token has been renewed");
4196 //                      setMessage("Authentication token has been renewed.");
4197                 } else {
4198                         authTimer.start(1000*60*5);
4199                         logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
4200 //                      setMessage("Authentication token renew has failed - retry in 5 minutes.");
4201                 }
4202                 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
4203         }
4204         
4205         
4206         @SuppressWarnings("unused")
4207         private synchronized void indexTimer() {
4208                 logger.log(logger.EXTREME, "Index timer activated.  Sync running="+syncRunning);
4209                 if (syncRunning) 
4210                         return;
4211                 // Look for any unindexed notes.  We only refresh occasionally 
4212                 // and do one at a time to keep overhead down.
4213                 if (!indexDisabled && indexRunner.getWorkQueueSize() == 0) { 
4214                         List<String> notes = conn.getNoteTable().getNextUnindexed(1);
4215                         String unindexedNote = null;
4216                         if (notes.size() > 0)
4217                                 unindexedNote = notes.get(0);
4218                         if (unindexedNote != null && Global.keepRunning) {
4219                                 indexNoteContent(unindexedNote);
4220                         }
4221                         if (notes.size()>0) {
4222                                 indexTimer.setInterval(100);
4223                                 return;
4224                         }
4225                         List<String> unindexedResources = conn.getNoteTable().noteResourceTable.getNextUnindexed(1);
4226                         if (unindexedResources.size() > 0 && indexRunner.getWorkQueueSize() == 0) {
4227                                 String unindexedResource = unindexedResources.get(0);
4228                                 if (unindexedResource != null && Global.keepRunning) {
4229                                         indexNoteResource(unindexedResource);
4230                                 }
4231                         }
4232                         if (unindexedResources.size() > 0) {
4233                                 indexTimer.setInterval(100);
4234                                 return;
4235                         } else {
4236                                 indexTimer.setInterval(indexTime);
4237                         }
4238                         if (indexRunning) {
4239                                 setMessage(tr("Index completed."));
4240                                 logger.log(logger.LOW, "Indexing has completed.");
4241                                 indexRunning = false;
4242                                 indexTimer.setInterval(indexTime);
4243                         }
4244                 }
4245                 logger.log(logger.EXTREME, "Leaving neverNote index timer");
4246         }
4247         private synchronized void indexNoteContent(String unindexedNote) {
4248                 logger.log(logger.EXTREME, "Entering NeverNote.indexNoteContent()");
4249                 logger.log(logger.MEDIUM, "Unindexed Note found: "+unindexedNote);
4250                 indexRunner.setIndexType(indexRunner.CONTENT);
4251                 indexRunner.addWork("CONTENT "+unindexedNote);
4252                 if (!indexRunning) {
4253                         setMessage(tr("Indexing notes."));
4254                         logger.log(logger.LOW, "Beginning to index note contents.");
4255                         indexRunning = true;
4256                 }
4257                 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteContent()");
4258         }
4259         private synchronized void indexNoteResource(String unindexedResource) {
4260                 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4261                 indexRunner.addWork(new String("RESOURCE "+unindexedResource));
4262                 if (!indexRunning) {
4263                         setMessage(tr("Indexing notes."));
4264                         indexRunning = true;
4265                 }
4266                 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4267         }
4268         @SuppressWarnings("unused")
4269         private void indexThreadComplete(String guid) {
4270                 logger.log(logger.MEDIUM, "Index complete for "+guid);
4271         }
4272         @SuppressWarnings("unused")
4273         private synchronized void toggleNoteIndexing() {
4274                 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
4275                 indexDisabled = !indexDisabled;
4276                 if (!indexDisabled)
4277                         setMessage(tr("Indexing is now enabled."));
4278                 else
4279                         setMessage(tr("Indexing is now disabled."));
4280                 menuBar.disableIndexing.setChecked(indexDisabled);
4281         logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
4282     }  
4283         
4284         @SuppressWarnings("unused")
4285         private void threadMonitorCheck() {
4286                 int MAX=3;
4287                 
4288                 
4289                 boolean alive;
4290                 alive = listManager.threadCheck(Global.tagCounterThreadId);
4291                 if (!alive) {
4292                         tagDeadCount++;
4293                         if (tagDeadCount > MAX)
4294                                 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died.  I recommend "+
4295                                 "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
4296                 } else
4297                         tagDeadCount=0;
4298                 
4299                 alive = listManager.threadCheck(Global.notebookCounterThreadId);
4300                 if (!alive) {
4301                         notebookThreadDeadCount++;
4302                         QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died.  I recommend "+
4303                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
4304                 } else
4305                         notebookThreadDeadCount=0;
4306                 
4307                 alive = listManager.threadCheck(Global.trashCounterThreadId);
4308                 if (!alive) {
4309                         trashDeadCount++;
4310                         QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died.  I recommend "+
4311                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
4312                 } else
4313                         trashDeadCount = 0;
4314
4315                 alive = listManager.threadCheck(Global.saveThreadId);
4316                 if (!alive) {
4317                         saveThreadDeadCount++;
4318                         QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died.  I recommend "+
4319                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
4320                 } else
4321                         saveThreadDeadCount=0;
4322
4323                 if (!syncThread.isAlive()) {
4324                         syncThreadDeadCount++;
4325                         QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died.  I recommend "+
4326                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
4327                 } else
4328                         syncThreadDeadCount=0;
4329
4330                 if (!indexThread.isAlive()) {
4331                         indexThreadDeadCount++;
4332                         QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died.  I recommend "+
4333                         "checking stopping NeverNote, saving the logs for later viewing, and restarting.  Sorry."));
4334                 } else
4335                         indexThreadDeadCount=0;
4336
4337                 
4338         }
4339
4340         
4341         
4342         //**************************************************
4343         //* Backup & Restore
4344         //**************************************************
4345         @SuppressWarnings("unused")
4346         private void databaseBackup() {
4347                 QFileDialog fd = new QFileDialog(this);
4348                 fd.setFileMode(FileMode.AnyFile);
4349                 fd.setConfirmOverwrite(true);
4350                 fd.setWindowTitle(tr("Backup Database"));
4351                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4352                 fd.setAcceptMode(AcceptMode.AcceptSave);
4353                 fd.setDirectory(System.getProperty("user.home"));
4354                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4355                         return;
4356                 }
4357                 
4358                 
4359         waitCursor(true);
4360         setMessage(tr("Backing up database"));
4361         saveNote();
4362 //      conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
4363         
4364         ExportData noteWriter = new ExportData(conn, true);
4365         String fileName = fd.selectedFiles().get(0);
4366
4367         if (!fileName.endsWith(".nnex"))
4368                 fileName = fileName +".nnex";
4369         noteWriter.exportData(fileName);
4370         setMessage(tr("Database backup completed."));
4371  
4372
4373         waitCursor(false);
4374         }
4375         @SuppressWarnings("unused")
4376         private void databaseRestore() {
4377                 if (QMessageBox.question(this, tr("Confirmation"),
4378                                 tr("This is used to restore a database from backups.\n" +
4379                                 "It is HIGHLY recommened that this only be used to populate\n" +
4380                                 "an empty database.  Restoring into a database that\n already has data" +
4381                                 " can cause problems.\n\nAre you sure you want to continue?"),
4382                                 QMessageBox.StandardButton.Yes, 
4383                                 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4384                                         return;
4385                                 }
4386                 
4387                 
4388                 QFileDialog fd = new QFileDialog(this);
4389                 fd.setFileMode(FileMode.ExistingFile);
4390                 fd.setConfirmOverwrite(true);
4391                 fd.setWindowTitle(tr("Restore Database"));
4392                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4393                 fd.setAcceptMode(AcceptMode.AcceptOpen);
4394                 fd.setDirectory(System.getProperty("user.home"));
4395                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4396                         return;
4397                 }
4398                 
4399                 
4400                 waitCursor(true);
4401                 setMessage(tr("Restoring database"));
4402         ImportData noteReader = new ImportData(conn, true);
4403         noteReader.importData(fd.selectedFiles().get(0));
4404         
4405         if (noteReader.lastError != 0) {
4406                 setMessage(noteReader.getErrorMessage());
4407                 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
4408                 waitCursor(false);
4409                 return;
4410         }
4411         
4412         listManager.loadNoteTitleColors();
4413         refreshLists();
4414         refreshEvernoteNote(true);
4415         setMessage(tr("Database has been restored."));
4416         waitCursor(false);
4417         }
4418         @SuppressWarnings("unused")
4419         private void exportNotes() {
4420                 QFileDialog fd = new QFileDialog(this);
4421                 fd.setFileMode(FileMode.AnyFile);
4422                 fd.setConfirmOverwrite(true);
4423                 fd.setWindowTitle(tr("Backup Database"));
4424                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4425                 fd.setAcceptMode(AcceptMode.AcceptSave);
4426                 fd.setDirectory(System.getProperty("user.home"));
4427                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4428                         return;
4429                 }
4430                 
4431                 
4432         waitCursor(true);
4433         setMessage(tr("Exporting Notes"));
4434         saveNote();
4435         
4436                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
4437                         selectedNoteGUIDs.add(currentNoteGuid);
4438                 
4439         ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
4440         String fileName = fd.selectedFiles().get(0);
4441
4442         if (!fileName.endsWith(".nnex"))
4443                 fileName = fileName +".nnex";
4444         noteWriter.exportData(fileName);
4445         setMessage(tr("Export completed."));
4446  
4447
4448         waitCursor(false);
4449                 
4450         }
4451         @SuppressWarnings("unused")
4452         private void importNotes() {
4453                 QFileDialog fd = new QFileDialog(this);
4454                 fd.setFileMode(FileMode.ExistingFile);
4455                 fd.setConfirmOverwrite(true);
4456                 fd.setWindowTitle(tr("Import Notes"));
4457                 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4458                 fd.setAcceptMode(AcceptMode.AcceptOpen);
4459                 fd.setDirectory(System.getProperty("user.home"));
4460                 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4461                         return;
4462                 }
4463                 
4464                 
4465         waitCursor(true);
4466         setMessage("Importing Notes");
4467         saveNote();
4468         
4469                 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals("")) 
4470                         selectedNoteGUIDs.add(currentNoteGuid);
4471                 
4472         ImportData noteReader = new ImportData(conn, false);
4473         String fileName = fd.selectedFiles().get(0);
4474
4475         if (!fileName.endsWith(".nnex"))
4476                 fileName = fileName +".nnex";
4477         if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0) 
4478                 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
4479         else
4480                 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
4481   
4482         noteReader.importData(fileName);
4483         
4484         if (noteReader.lastError != 0) {
4485                 setMessage(noteReader.getErrorMessage());
4486                 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
4487                 waitCursor(false);
4488                 return;
4489         }
4490         
4491         listManager.loadNoteTitleColors();
4492         refreshLists();
4493         refreshEvernoteNote(false);
4494         setMessage(tr("Notes have been imported."));
4495         waitCursor(false);
4496         
4497         setMessage("Import completed.");
4498  
4499
4500         waitCursor(false);
4501                 
4502         }
4503         
4504         //**************************************************
4505         //* Duplicate a note 
4506         //**************************************************
4507         @SuppressWarnings("unused")
4508         private void duplicateNote() {
4509                 saveNote();
4510                 duplicateNote(currentNoteGuid);
4511         }
4512
4513         
4514         
4515         //**************************************************
4516         //* Folder Imports
4517         //**************************************************
4518         public void setupFolderImports() {
4519                 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
4520                 
4521                 if (importKeepWatcher == null)
4522                         importKeepWatcher = new QFileSystemWatcher();
4523                 if (importDeleteWatcher == null) {
4524                         importDeleteWatcher = new QFileSystemWatcher();
4525                         for (int i=0; i<records.size(); i++) {
4526                                 if (!records.get(i).keep)
4527                                         folderImportDelete(records.get(i).folder); 
4528                         }
4529                 }
4530
4531                                 
4532                 
4533 //              importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
4534                 for (int i=0; i<records.size(); i++) {
4535                         if (records.get(i).keep) 
4536                                 importKeepWatcher.addPath(records.get(i).folder);
4537                         else
4538                                 importDeleteWatcher.addPath(records.get(i).folder);
4539                 }
4540                 
4541                 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
4542                 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
4543                 
4544                 // Look at the files already there so we don't import them again if a new file is created
4545                 if (importedFiles == null) {
4546                         importedFiles = new ArrayList<String>();
4547                         for (int j=0; j<records.size(); j++) {
4548                                 QDir dir = new QDir(records.get(j).folder);
4549                                 List<QFileInfo> list = dir.entryInfoList();
4550                                 for (int k=0; k<list.size(); k++) {
4551                                         if (list.get(k).isFile())
4552                                                 importedFiles.add(list.get(k).absoluteFilePath());
4553                                 }
4554                         }
4555                 }
4556         }
4557         public void folderImport() {
4558                 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
4559                 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
4560                 dialog.exec();
4561                 if (!dialog.okClicked())
4562                         return;
4563                 
4564                 // We have some sort of update.
4565                 if (importKeepWatcher.directories().size() > 0)
4566                         importKeepWatcher.removePaths(importKeepWatcher.directories());
4567                 if (importDeleteWatcher.directories().size() > 0)
4568                         importDeleteWatcher.removePaths(importDeleteWatcher.directories());
4569                 
4570                 conn.getWatchFolderTable().expungeAll();
4571                 // Start building from the table
4572                 for (int i=0; i<dialog.table.rowCount(); i++) {
4573                         QTableWidgetItem item = dialog.table.item(i, 0);
4574                         String dir = item.text();
4575                         item = dialog.table.item(i, 1);
4576                         String notebook = item.text();
4577                         item = dialog.table.item(i, 2);
4578                         boolean keep;
4579                         if (item.text().equalsIgnoreCase("Keep"))
4580                                 keep = true;
4581                         else
4582                                 keep = false;
4583                         
4584                         String guid = conn.getNotebookTable().findNotebookByName(notebook);
4585                         conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
4586                 }
4587                 setupFolderImports();
4588         }
4589         
4590         public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
4591                 
4592                 String whichOS = System.getProperty("os.name");
4593                 if (whichOS.contains("Windows")) 
4594                         dirName = dirName.replace('/','\\');
4595                 
4596                 FileImporter importer = new FileImporter(logger, conn);
4597                 
4598                 QDir dir = new QDir(dirName);
4599                 List<QFileInfo> list = dir.entryInfoList();
4600                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4601
4602                 for (int i=0; i<list.size(); i++){
4603                         
4604                         boolean redundant = false;
4605                         // Check if we've already imported this one or if it existed before
4606                         for (int j=0; j<importedFiles.size(); j++) {
4607                                 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
4608                                         redundant = true;
4609                         }
4610                         
4611                         if (!redundant) {
4612                                 importer.setFileInfo(list.get(i));
4613                                 importer.setFileName(list.get(i).absoluteFilePath());
4614                         
4615                         
4616                                 if (list.get(i).isFile() && importer.isValidType()) {
4617                         
4618                                         if (!importer.importFile()) {
4619                                                 // If we can't get to the file, it is probably locked.  We'll try again later.
4620                                                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4621                                                 importFilesKeep.add(list.get(i).absoluteFilePath());
4622                                                 return;
4623                                         }
4624
4625                                         Note newNote = importer.getNote();
4626                                         newNote.setNotebookGuid(notebook);
4627                                         newNote.setTitle(dir.at(i));
4628                                         listManager.addNote(newNote);
4629                                         conn.getNoteTable().addNote(newNote, true);
4630                                         listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4631                                         noteTableView.insertRow(newNote, true, -1);
4632                                         listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4633                                         listManager.countNotebookResults(listManager.getNoteIndex());
4634                                         importedFiles.add(list.get(i).absoluteFilePath());
4635                                 }
4636                         }
4637                 }
4638         
4639         
4640         }
4641         
4642         public void folderImportDelete(String dirName) {
4643                 
4644                 String whichOS = System.getProperty("os.name");
4645                 if (whichOS.contains("Windows")) 
4646                         dirName = dirName.replace('/','\\');
4647                 
4648                 FileImporter importer = new FileImporter(logger, conn);
4649                 QDir dir = new QDir(dirName);
4650                 List<QFileInfo> list = dir.entryInfoList();
4651                 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4652                 
4653                 for (int i=0; i<list.size(); i++){
4654                         importer.setFileInfo(list.get(i));
4655                         importer.setFileName(list.get(i).absoluteFilePath());
4656                         
4657                         if (list.get(i).isFile() && importer.isValidType()) {
4658                 
4659                                 if (!importer.importFile()) {
4660                                         // If we can't get to the file, it is probably locked.  We'll try again later.
4661                                         logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4662                                         importFilesKeep.add(list.get(i).absoluteFilePath());
4663                                         return;
4664                                 }
4665                 
4666                                 Note newNote = importer.getNote();
4667                                 newNote.setNotebookGuid(notebook);
4668                                 newNote.setTitle(dir.at(i));
4669                                 listManager.addNote(newNote);
4670                                 conn.getNoteTable().addNote(newNote, true);
4671                                 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4672                                 noteTableView.insertRow(newNote, true, -1);
4673                                 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4674                                 listManager.countNotebookResults(listManager.getNoteIndex());
4675                                 dir.remove(dir.at(i));
4676                         }
4677                 }
4678         }
4679         
4680         
4681         //**************************************************
4682         //* External events
4683         //**************************************************
4684         private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
4685                 logger.log(logger.HIGH, "Entering exernalFileEdited");
4686
4687                 // Strip URL prefix and base dir path
4688                 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
4689                 String name = fileName.replace(dPath, "");
4690                 int pos = name.lastIndexOf('.');
4691                 String guid = name;
4692                 if (pos > -1) {
4693                         guid = guid.substring(0,pos);
4694                 }
4695                 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
4696                 if (pos > -1) {
4697                         guid = name.substring(0, pos);
4698                 }
4699                 
4700                 QFile file = new QFile(fileName);
4701         if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
4702                 // If we can't get to the file, it is probably locked.  We'll try again later.
4703                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4704                 externalFiles.add(fileName);
4705                 return;
4706                 }
4707                 QByteArray binData = file.readAll();
4708         file.close();
4709         if (binData.size() == 0) {
4710                 // If we can't get to the file, it is probably locked.  We'll try again later.
4711                 logger.log(logger.LOW, "Unable to save externally edited file.  Saving for later.");
4712                 externalFiles.add(fileName);
4713                 return;
4714         }
4715         
4716         Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
4717         if (r==null)
4718                 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
4719         if (r == null || r.getData() == null || r.getData().getBody() == null)
4720                 return;
4721         String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
4722         MessageDigest md = MessageDigest.getInstance("MD5");
4723                 md.update(binData.toByteArray());
4724                 byte[] hash = md.digest();
4725         String newHash = Global.byteArrayToHexString(hash);
4726         if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
4727                 updateResourceContentHash(r.getGuid(), oldHash, newHash);
4728         }
4729         conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
4730         Data data = r.getData();
4731         data.setBody(binData.toByteArray());
4732         data.setBodyHash(hash);
4733         logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
4734         r.setData(data);
4735         conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
4736         
4737         if (r.getNoteGuid().equals(currentNoteGuid)) {
4738                         QWebSettings.setMaximumPagesInCache(0);
4739                         QWebSettings.setObjectCacheCapacities(0, 0, 0);
4740                         refreshEvernoteNote(true);
4741                         browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
4742         }
4743         
4744                 logger.log(logger.HIGH, "Exiting externalFielEdited");
4745         }
4746         // This is a timer event that tries to save any external files that were edited.  This
4747         // is only needed if we couldn't save a file earlier.
4748         public void externalFileEditedSaver() {
4749                 for (int i=externalFiles.size()-1; i>=0; i--) {
4750                         try {
4751                                 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
4752                                 externalFileEdited(externalFiles.get(i));
4753                                 externalFiles.remove(i);
4754                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4755                 }
4756                 for (int i=0; i<importFilesKeep.size(); i++) {
4757                         try {
4758                                 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
4759                                 folderImportKeep(importFilesKeep.get(i));
4760                                 importFilesKeep.remove(i);
4761                         } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4762                 }
4763                 for (int i=0; i<importFilesDelete.size(); i++) {
4764                         logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
4765                         folderImportDelete(importFilesDelete.get(i));
4766                         importFilesDelete.remove(i);
4767                 }
4768         }
4769         
4770         
4771         
4772         
4773         // If an attachment on the current note was edited, we need to update the current notes's hash
4774         // Update a note content's hash.  This happens if a resource is edited outside of NN
4775         public void updateResourceContentHash(String guid, String oldHash, String newHash) {
4776                 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
4777                 int endPos;
4778                 for (;position>-1;) {
4779                         endPos = browserWindow.getContent().indexOf(">", position+1);
4780                         String oldSegment = browserWindow.getContent().substring(position,endPos);
4781                         int hashPos = oldSegment.indexOf("hash=\"");
4782                         int hashEnd = oldSegment.indexOf("\"", hashPos+7);
4783                         String hash = oldSegment.substring(hashPos+6, hashEnd);
4784                         if (hash.equalsIgnoreCase(oldHash)) {
4785                                 String newSegment = oldSegment.replace(oldHash, newHash);
4786                                 String content = browserWindow.getContent().substring(0,position) +
4787                                                  newSegment +
4788                                                  browserWindow.getContent().substring(endPos);
4789                                 browserWindow.getBrowser().setContent(new QByteArray(content));;
4790                         }
4791                         
4792                         position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
4793                 }
4794         }
4795
4796
4797         
4798         
4799         //*************************************************
4800         //* Check database userid & passwords
4801         //*************************************************
4802         private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
4803                         Connection connection;
4804                         
4805                         try {
4806                                 Class.forName("org.h2.Driver");
4807                         } catch (ClassNotFoundException e1) {
4808                                 e1.printStackTrace();
4809                                 System.exit(16);
4810                         }
4811
4812                         try {
4813                                 String passwordString = null;
4814                                 if (cypherPassword==null || cypherPassword.trim().equals(""))
4815                                         passwordString = userPassword;
4816                                 else
4817                                         passwordString = cypherPassword+" "+userPassword;
4818                                 connection = DriverManager.getConnection(url,userid,passwordString);
4819                         } catch (SQLException e) {
4820                                 return false;
4821                         }
4822                         try {
4823                                 connection.close();
4824                         } catch (SQLException e) {
4825                                 e.printStackTrace();
4826                         }
4827                         return true;
4828         }
4829
4830 }