OSDN Git Service

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