OSDN Git Service

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