OSDN Git Service

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