OSDN Git Service

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