OSDN Git Service

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