OSDN Git Service

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