OSDN Git Service

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