OSDN Git Service

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