OSDN Git Service

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