OSDN Git Service

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