OSDN Git Service

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