OSDN Git Service

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