OSDN Git Service

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