OSDN Git Service

Correct problem where images may not be pasted properly due to ' character messing...
[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.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
26 import java.sql.Connection;
27 import java.sql.DriverManager;
28 import java.sql.SQLException;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Calendar;
32 import java.util.Collections;
33 import java.util.Comparator;
34 import java.util.Date;
35 import java.util.GregorianCalendar;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.SortedMap;
39 import java.util.Vector;
40
41 import org.apache.thrift.TException;
42
43 import com.evernote.edam.error.EDAMNotFoundException;
44 import com.evernote.edam.error.EDAMSystemException;
45 import com.evernote.edam.error.EDAMUserException;
46 import com.evernote.edam.notestore.NoteFilter;
47 import com.evernote.edam.notestore.NoteVersionId;
48 import com.evernote.edam.type.Data;
49 import com.evernote.edam.type.Note;
50 import com.evernote.edam.type.NoteAttributes;
51 import com.evernote.edam.type.Notebook;
52 import com.evernote.edam.type.QueryFormat;
53 import com.evernote.edam.type.Resource;
54 import com.evernote.edam.type.SavedSearch;
55 import com.evernote.edam.type.Tag;
56 import com.evernote.edam.type.User;
57 import com.trolltech.qt.QThread;
58 import com.trolltech.qt.core.QByteArray;
59 import com.trolltech.qt.core.QDataStream;
60 import com.trolltech.qt.core.QDateTime;
61 import com.trolltech.qt.core.QDir;
62 import com.trolltech.qt.core.QFile;
63 import com.trolltech.qt.core.QFileInfo;
64 import com.trolltech.qt.core.QFileSystemWatcher;
65 import com.trolltech.qt.core.QIODevice;
66 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
67 import com.trolltech.qt.core.QLocale;
68 import com.trolltech.qt.core.QModelIndex;
69 import com.trolltech.qt.core.QSize;
70 import com.trolltech.qt.core.QTemporaryFile;
71 import com.trolltech.qt.core.QTextCodec;
72 import com.trolltech.qt.core.QThreadPool;
73 import com.trolltech.qt.core.QTimer;
74 import com.trolltech.qt.core.QTranslator;
75 import com.trolltech.qt.core.QUrl;
76 import com.trolltech.qt.core.Qt;
77 import com.trolltech.qt.core.Qt.SortOrder;
78 import com.trolltech.qt.core.Qt.WidgetAttribute;
79 import com.trolltech.qt.gui.QAbstractItemView;
80 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
81 import com.trolltech.qt.gui.QAction;
82 import com.trolltech.qt.gui.QApplication;
83 import com.trolltech.qt.gui.QCloseEvent;
84 import com.trolltech.qt.gui.QColor;
85 import com.trolltech.qt.gui.QComboBox;
86 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
87 import com.trolltech.qt.gui.QCursor;
88 import com.trolltech.qt.gui.QDesktopServices;
89 import com.trolltech.qt.gui.QDialog;
90 import com.trolltech.qt.gui.QFileDialog;
91 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
92 import com.trolltech.qt.gui.QFileDialog.FileMode;
93 import com.trolltech.qt.gui.QGridLayout;
94 import com.trolltech.qt.gui.QHBoxLayout;
95 import com.trolltech.qt.gui.QIcon;
96 import com.trolltech.qt.gui.QImage;
97 import com.trolltech.qt.gui.QLabel;
98 import com.trolltech.qt.gui.QListWidget;
99 import com.trolltech.qt.gui.QMainWindow;
100 import com.trolltech.qt.gui.QMenu;
101 import com.trolltech.qt.gui.QMessageBox;
102 import com.trolltech.qt.gui.QMessageBox.StandardButton;
103 import com.trolltech.qt.gui.QPixmap;
104 import com.trolltech.qt.gui.QPrintDialog;
105 import com.trolltech.qt.gui.QPrinter;
106 import com.trolltech.qt.gui.QProgressBar;
107 import com.trolltech.qt.gui.QSizePolicy;
108 import com.trolltech.qt.gui.QSizePolicy.Policy;
109 import com.trolltech.qt.gui.QSpinBox;
110 import com.trolltech.qt.gui.QSplashScreen;
111 import com.trolltech.qt.gui.QSplitter;
112 import com.trolltech.qt.gui.QStatusBar;
113 import com.trolltech.qt.gui.QSystemTrayIcon;
114 import com.trolltech.qt.gui.QTableWidgetItem;
115 import com.trolltech.qt.gui.QTextEdit;
116 import com.trolltech.qt.gui.QToolBar;
117 import com.trolltech.qt.gui.QTreeWidgetItem;
118 import com.trolltech.qt.webkit.QWebPage.WebAction;
119 import com.trolltech.qt.webkit.QWebSettings;
120 import com.trolltech.qt.xml.QDomAttr;
121 import com.trolltech.qt.xml.QDomDocument;
122 import com.trolltech.qt.xml.QDomElement;
123 import com.trolltech.qt.xml.QDomNodeList;
124
125 import cx.fbn.nevernote.config.FileManager;
126 import cx.fbn.nevernote.config.InitializationException;
127 import cx.fbn.nevernote.config.StartupConfig;
128 import cx.fbn.nevernote.dialog.AccountDialog;
129 import cx.fbn.nevernote.dialog.ConfigDialog;
130 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
131 import cx.fbn.nevernote.dialog.DatabaseStatus;
132 import cx.fbn.nevernote.dialog.FindDialog;
133 import cx.fbn.nevernote.dialog.LoginDialog;
134 import cx.fbn.nevernote.dialog.NotebookArchive;
135 import cx.fbn.nevernote.dialog.NotebookEdit;
136 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
137 import cx.fbn.nevernote.dialog.SavedSearchEdit;
138 import cx.fbn.nevernote.dialog.TagEdit;
139 import cx.fbn.nevernote.dialog.ThumbnailViewer;
140 import cx.fbn.nevernote.dialog.WatchFolder;
141 import cx.fbn.nevernote.filters.EnSearch;
142 import cx.fbn.nevernote.gui.AttributeTreeWidget;
143 import cx.fbn.nevernote.gui.BrowserWindow;
144 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
145 import cx.fbn.nevernote.gui.MainMenuBar;
146 import cx.fbn.nevernote.gui.NotebookTreeWidget;
147 import cx.fbn.nevernote.gui.PDFPreview;
148 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
149 import cx.fbn.nevernote.gui.TableView;
150 import cx.fbn.nevernote.gui.TagTreeWidget;
151 import cx.fbn.nevernote.gui.Thumbnailer;
152 import cx.fbn.nevernote.gui.TrashTreeWidget;
153 import cx.fbn.nevernote.sql.DatabaseConnection;
154 import cx.fbn.nevernote.sql.WatchFolderRecord;
155 import cx.fbn.nevernote.threads.IndexRunner;
156 import cx.fbn.nevernote.threads.SyncRunner;
157 import cx.fbn.nevernote.utilities.AESEncrypter;
158 import cx.fbn.nevernote.utilities.ApplicationLogger;
159 import cx.fbn.nevernote.utilities.FileImporter;
160 import cx.fbn.nevernote.utilities.FileUtils;
161 import cx.fbn.nevernote.utilities.ListManager;
162 import cx.fbn.nevernote.utilities.SyncTimes;
163 import cx.fbn.nevernote.xml.ExportData;
164 import cx.fbn.nevernote.xml.ImportData;
165 import cx.fbn.nevernote.xml.XMLInsertHilight;
166
167
168 public class NeverNote extends QMainWindow{
169         
170         QStatusBar                              statusBar;                                      // Application status bar
171         
172         DatabaseConnection              conn;
173         
174         MainMenuBar                             menuBar;                                        // Main menu bar
175         FindDialog                              find;                                           // Text search in note dialog
176         List<String>                    emitLog;                                        // Messages displayed in the status bar;
177         QSystemTrayIcon                 trayIcon;                                       // little tray icon
178         QMenu                                   trayMenu;                                       // System tray menu
179         QAction                                 trayExitAction;                         // Exit the application
180         QAction                                 trayShowAction;                         // toggle the show/hide action          
181         QAction                                 trayAddNoteAction;                      // Add a note from the system tray
182         
183     NotebookTreeWidget          notebookTree;                           // List of notebooks
184     AttributeTreeWidget         attributeTree;                          // List of note attributes
185     TagTreeWidget                       tagTree;                                        // list of user created tags
186     SavedSearchTreeWidget       savedSearchTree;                        // list of saved searches
187     TrashTreeWidget                     trashTree;                                      // Trashcan
188     TableView                           noteTableView;                          //      List of notes (the widget).
189
190     public BrowserWindow        browserWindow;                          // Window containing browser & labels
191     QToolBar                            toolBar;                                        // The tool bar under the menu
192 //    QLineEdit                                 searchField;                            // The search filter bar on the toolbar
193     QComboBox                           searchField;                            // search filter bar on the toolbar;
194     boolean                                     searchPerformed = false;        // Search was done?
195     QProgressBar                        quotaBar;                                       // The current quota usage
196     
197     ApplicationLogger           logger;
198     List<String>                        selectedNotebookGUIDs;          // List of notebook GUIDs
199     List<String>                        selectedTagGUIDs;                       // List of selected tag GUIDs
200     List<String>                        selectedNoteGUIDs;                      // List of selected notes
201     String                                      selectedSavedSearchGUID;        // Currently selected saved searches
202     
203     NoteFilter                          filter;                                         // Note filter
204     String                                      currentNoteGuid;                        // GUID of the current note 
205     Note                                        currentNote;                            // The currently viewed note
206     boolean                                     noteDirty;                                      // Has the note been changed?
207     boolean                             inkNote;                    // if this is an ink note, it is read only
208   
209     ListManager                         listManager;                                    // DB runnable task
210     
211     List<QTemporaryFile>        tempFiles;                                      // Array of temporary files;
212     
213     QTimer                                      indexTimer;                                     // timer to start the index thread
214     IndexRunner                         indexRunner;                            // thread to index notes
215     QThread                                     indexThread;
216     
217     QTimer                                      syncTimer;                                      // Sync on an interval
218     QTimer                                      syncDelayTimer;                         // Sync delay to free up database
219     SyncRunner                          syncRunner;                                     // thread to do a sync.
220     QThread                                     syncThread;
221     QTimer                                      saveTimer;                                      // Timer to save note contents
222     
223     QTimer                                      authTimer;                                      // Refresh authentication
224     QTimer                                      externalFileSaveTimer;          // Save files altered externally
225     List<String>                        externalFiles;                          // External files to save later
226     List<String>                        importFilesKeep;                        // Auto-import files to save later
227     List<String>                        importFilesDelete;                      // Auto-import files to save later
228     
229     int                                         indexTime;                                      // how often to try and index
230     boolean                                     indexRunning;                           // Is indexing running?
231     boolean                                     indexDisabled;                          // Is indexing disabled?
232     
233     int                                         syncThreadsReady;                       // number of sync threads that are free
234     int                                         syncTime;                                       // Sync interval
235     boolean                                     syncRunning;                            // Is sync running?
236     boolean                                     automaticSync;                          // do sync automatically?
237     QTreeWidgetItem                     attributeTreeSelected;
238
239     QAction                             prevButton;                                     // Go to the previous item viewed
240     QAction                             nextButton;                                     // Go to the next item in the history
241     QAction                             downButton;                                     // Go to the next item in the list
242     QAction                             upButton;                                       // Go to the prev. item in the list;
243     QAction                             synchronizeButton;                      // Synchronize with Evernote
244     List<QIcon>                 synchronizeAnimation;           // Synchronize movie
245     QTimer                              synchronizeAnimationTimer;      // Timer to change animation button
246     int                                 synchronizeFrame;                       // Current frame being viewed
247     QAction                     printButton;                            // Print Button
248     QAction                             tagButton;                                      // Tag edit button
249     QAction                             attributeButton;                        // Attribute information button
250     QAction                     emailButton;                            // Email button
251     QAction                     deleteButton;                           // Delete button
252     QAction                             newButton;                                      // new Note Button;
253     QSpinBox                    zoomSpinner;                            // Zoom zoom
254     QAction                             searchClearButton;                      // Clear the search field
255     
256     QSplitter                   mainLeftRightSplitter;          // main splitter for left/right side
257     QSplitter                   leftSplitter1;                          // first left hand splitter
258     QSplitter                   browserIndexSplitter;           // splitter between note index & note text
259     
260     QFileSystemWatcher  importKeepWatcher;                      // Watch & keep auto-import
261     QFileSystemWatcher  importDeleteWatcher;            // Watch & Delete auto-import
262     List<String>                importedFiles;                          // History of imported files (so we don't import twice)
263     
264     OnlineNoteHistory   historyWindow;                          // online history window 
265     List<NoteVersionId> versions;                                       // history versions
266     
267     QTimer                              threadMonitorTimer;                     // Timer to watch threads.
268     int                                 dbThreadDeadCount=0;            // number of consecutive dead times for the db thread
269     int                                 syncThreadDeadCount=0;          // number of consecutive dead times for the sync thread
270     int                                 indexThreadDeadCount=0;         // number of consecutive dead times for the index thread
271     int                                 notebookThreadDeadCount=0;      // number of consecutive dead times for the notebook thread
272     int                                 tagDeadCount=0;                         // number of consecutive dead times for the tag thread
273     int                                 trashDeadCount=0;                       // number of consecutive dead times for the trash thread
274     int                                 saveThreadDeadCount=0;          // number of consecutive dead times for the save thread
275     
276     HashMap<String, String>             noteCache;                      // Cash of note content 
277     List<String>                historyGuids;                           // GUIDs of previously viewed items
278     int                                 historyPosition;                        // Position within the viewed items
279     boolean                             fromHistory;                            // Is this from the history queue?
280     String                              trashNoteGuid;                          // Guid to restore / set into or out of trash to save position
281     Thumbnailer                 preview;                                        // generate preview image
282     ThumbnailViewer             thumbnailViewer;                        // View preview thumbnail; 
283     
284     String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
285         
286         
287     //***************************************************************
288     //***************************************************************
289     //** Constructor & main entry point
290     //***************************************************************
291     //***************************************************************
292     // Application Constructor  
293         public NeverNote(DatabaseConnection dbConn)  {
294                 conn = dbConn;          
295
296                 thread().setPriority(Thread.MAX_PRIORITY);
297                 
298                 logger = new ApplicationLogger("nevernote.log");
299                 logger.log(logger.HIGH, "Starting Application");
300
301                 conn.checkDatabaseVersion();
302                 
303                 // Start building the invalid XML tables
304                 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
305                 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
306                 
307                 for (int i=0; i<elements.size(); i++) {
308                         Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
309                 }
310                 
311                 logger.log(logger.EXTREME, "Starting GUI build");
312
313                 QTranslator qtTranslator = new QTranslator();
314                 qtTranslator.load("classpath:/translations/qt_" + QLocale.system().name() + ".qm");
315                 QApplication.instance().installTranslator(qtTranslator);
316
317                 QTranslator nevernoteTranslator = new QTranslator();
318                 nevernoteTranslator.load("classpath:/translations/nevernote_"+QLocale.system().name()+ ".qm");
319                 QApplication.instance().installTranslator(nevernoteTranslator);
320
321                 Global.originalPalette = QApplication.palette();
322                 QApplication.setStyle(Global.getStyle());
323                 if (Global.useStandardPalette())
324                         QApplication.setPalette(QApplication.style().standardPalette());
325         setWindowTitle("NeverNote");
326         
327         mainLeftRightSplitter = new QSplitter();
328         setCentralWidget(mainLeftRightSplitter);
329         leftSplitter1 = new QSplitter();
330         leftSplitter1.setOrientation(Qt.Orientation.Vertical);
331                 
332         browserIndexSplitter = new QSplitter();
333         browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
334         
335         //* Setup threads & thread timers
336         int indexRunnerCount = Global.getIndexThreads();
337         indexRunnerCount = 1;
338         QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5);     // increase max thread count
339
340                 logger.log(logger.EXTREME, "Building list manager");
341         listManager = new ListManager(conn, logger);
342         
343                 logger.log(logger.EXTREME, "Building index runners & timers");
344         indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
345                 indexThread = new QThread(indexRunner, "Index Thread");
346                 indexThread.start();
347                 
348         synchronizeAnimationTimer = new QTimer();
349         synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
350         
351                 indexTimer = new QTimer();
352                 indexTime = 1000*60*5;     // look for unindexed every 5 minutes
353 //              indexTime = 1000*5;
354                 indexTimer.start(indexTime);  // Start indexing timer
355                 indexTimer.timeout.connect(this, "indexTimer()");
356                 indexDisabled = false;
357                 indexRunning = false;
358                                 
359                 logger.log(logger.EXTREME, "Setting sync thread & timers");
360                 syncThreadsReady=1;
361                 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
362                 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
363                 syncTimer = new QTimer();
364                 syncTimer.timeout.connect(this, "syncTimer()");
365         syncRunner.status.message.connect(this, "setMessage(String)");
366         syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
367         syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
368         syncRunning = false;    
369                 if (syncTime > 0) {
370                         automaticSync = true;
371                         syncTimer.start(syncTime*60*1000);
372                 } else {
373                         automaticSync = false;
374                         syncTimer.stop();
375                 }
376                 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
377                 syncThread = new QThread(syncRunner, "Synchronization Thread");
378                 syncThread.start();
379                 
380                 
381                 logger.log(logger.EXTREME, "Starting authentication timer");
382                 authTimer = new QTimer();
383                 authTimer.timeout.connect(this, "authTimer()");
384                 authTimer.start(1000*60*15);
385                 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
386                 
387                 logger.log(logger.EXTREME, "Setting save note timer");
388                 saveTimer = new QTimer();
389                 saveTimer.timeout.connect(this, "saveNote()");
390                 if (Global.getAutoSaveInterval() > 0) {
391                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval()); 
392 //                      saveTimer.setInterval(1000*10); // auto save every 20 seconds;
393                         saveTimer.start();
394                 }
395                 
396                 logger.log(logger.EXTREME, "Starting external file monitor timer");
397                 externalFileSaveTimer = new QTimer();
398                 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
399                 externalFileSaveTimer.setInterval(1000*5);   // save every 5 seconds;
400                 externalFiles = new ArrayList<String>();
401                 importFilesDelete = new ArrayList<String>();
402                 importFilesKeep = new ArrayList<String>();
403                 externalFileSaveTimer.start();
404                 
405         notebookTree = new NotebookTreeWidget();
406         attributeTree = new AttributeTreeWidget();
407         tagTree = new TagTreeWidget(conn);
408         savedSearchTree = new SavedSearchTreeWidget();
409         trashTree = new TrashTreeWidget();
410         noteTableView = new TableView(logger, listManager);
411         
412         QGridLayout leftGrid = new QGridLayout();
413         leftSplitter1.setLayout(leftGrid);
414         leftGrid.addWidget(notebookTree, 1, 1);
415         leftGrid.addWidget(tagTree,2,1);
416         leftGrid.addWidget(attributeTree,3,1);
417         leftGrid.addWidget(savedSearchTree,4,1);
418         leftGrid.addWidget(trashTree, 5, 1);
419         
420         // Setup the browser window
421         noteCache = new HashMap<String,String>();
422         browserWindow = new BrowserWindow(conn);
423
424         browserIndexSplitter.addWidget(noteTableView);
425         browserIndexSplitter.addWidget(browserWindow);
426         
427         mainLeftRightSplitter.addWidget(leftSplitter1);
428         mainLeftRightSplitter.addWidget(browserIndexSplitter);
429
430         searchField = new QComboBox();
431         searchField.setEditable(true);
432         searchField.activatedIndex.connect(this, "searchFieldChanged()");
433         searchField.setDuplicatesEnabled(false);
434         searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
435         
436         quotaBar = new QProgressBar();
437         
438         // Setup the thumbnail viewer
439         thumbnailViewer = new ThumbnailViewer();
440         thumbnailViewer.upArrow.connect(this, "upAction()");
441         thumbnailViewer.downArrow.connect(this, "downAction()");
442         thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
443         thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
444
445         listManager.loadNotesIndex();
446         initializeNotebookTree();
447         initializeTagTree();
448         initializeSavedSearchTree();
449         attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
450         attributeTreeSelected = null;
451         initializeNoteTable();    
452
453                 selectedNoteGUIDs = new ArrayList<String>();
454                 statusBar = new QStatusBar();
455                 setStatusBar(statusBar);
456                 menuBar = new MainMenuBar(this);
457                 emitLog = new ArrayList<String>();
458                 
459                 tagTree.setDeleteAction(menuBar.tagDeleteAction);
460                 tagTree.setEditAction(menuBar.tagEditAction);
461                 tagTree.setAddAction(menuBar.tagAddAction);
462                 tagTree.setVisible(Global.isWindowVisible("tagTree"));
463                 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
464                 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
465                 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
466         
467                 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
468                 notebookTree.setEditAction(menuBar.notebookEditAction);
469                 notebookTree.setAddAction(menuBar.notebookAddAction);
470                 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
471                 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
472                 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
473
474                 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
475                 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
476                 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
477                 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
478                 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
479                 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
480                         
481                 noteTableView.setAddAction(menuBar.noteAdd);
482                 noteTableView.setDeleteAction(menuBar.noteDelete);
483                 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
484                 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
485                 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
486                 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
487                 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
488                 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
489                 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
490                 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
491                 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
492                 trashTree.load();
493         trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
494                 trashTree.setEmptyAction(menuBar.emptyTrashAction);
495                 trashTree.setVisible(Global.isWindowVisible("trashTree"));
496                 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
497                 trashTree.updateCounts(listManager.getTrashCount());
498
499                 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
500                 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
501
502                 noteTableView.setVisible(Global.isWindowVisible("noteList"));
503                 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
504                 
505                 if (!Global.isWindowVisible("editorButtonBar"))
506                         toggleEditorButtonBar();
507                 if (!Global.isWindowVisible("leftPanel"))
508                         menuBar.hideLeftSide.setChecked(true);
509                 
510                 setMenuBar(menuBar);
511                 setupToolBar();
512                 find = new FindDialog();
513                 find.getOkButton().clicked.connect(this, "doFindText()");
514                 
515                 // Setup the tray icon menu bar
516                 trayShowAction = new QAction("Show/Hide", this);
517                 trayExitAction = new QAction("Exit", this);
518                 trayAddNoteAction = new QAction("Add Note", this);
519                 
520                 trayExitAction.triggered.connect(this, "close()");
521                 trayAddNoteAction.triggered.connect(this, "addNote()");
522                 trayShowAction.triggered.connect(this, "trayToggleVisible()");
523                 
524                 trayMenu = new QMenu(this);
525                 trayMenu.addAction(trayAddNoteAction);
526                 trayMenu.addAction(trayShowAction);
527                 trayMenu.addAction(trayExitAction);
528                 
529                 
530                 trayIcon = new QSystemTrayIcon(this);
531                 trayIcon.setToolTip("NeverNote");
532                 trayIcon.setContextMenu(trayMenu);
533                 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
534
535                 currentNoteGuid="";
536                 currentNoteGuid = Global.getLastViewedNoteGuid();
537         historyGuids = new ArrayList<String>();
538         historyPosition = 0;
539         fromHistory = false;
540                 noteDirty = false;
541                 if (!currentNoteGuid.trim().equals("")) {
542                         currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
543                 }
544                 
545                 noteIndexUpdated(true);
546                 showColumns();
547                 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
548                 if (menuBar.showEditorBar.isChecked())
549                 showEditorButtons();
550                 tagIndexUpdated(true);
551                 savedSearchIndexUpdated();
552                 notebookIndexUpdated();
553                 updateQuotaBar();
554         setupSyncSignalListeners();        
555         setupBrowserSignalListeners();
556         setupIndexListeners();
557               
558         
559         tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
560         tagTree.showAllTags(true);
561
562                 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
563         setWindowIcon(appIcon);
564         trayIcon.setIcon(appIcon);
565         if (Global.showTrayIcon())
566                 trayIcon.show();
567         else
568                 trayIcon.hide();
569         
570         scrollToGuid(currentNoteGuid);
571         if (Global.automaticLogin()) {
572                 remoteConnect();
573                 if (Global.isConnected)
574                         syncTimer();
575         }
576         setupFolderImports();
577         
578         loadStyleSheet();
579         restoreWindowState();
580         
581         if (Global.mimicEvernoteInterface) {
582                 notebookTree.selectGuid("");
583         }
584         
585         threadMonitorTimer = new QTimer();
586         threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
587         threadMonitorTimer.start(1000*10);  // Check for threads every 10 seconds;              
588         
589         historyGuids.add(currentNoteGuid);
590         historyPosition = 1;
591         
592         int sortCol = Global.getSortColumn();
593                 int sortOrder = Global.getSortOrder();
594                 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
595         }
596
597         
598         // Main entry point
599         public static void main(String[] args) {
600                 QApplication.initialize(args);
601                 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
602                 QSplashScreen splash = new QSplashScreen(pixmap);
603                 boolean showSplash;
604                 
605                 DatabaseConnection dbConn;
606
607         try {
608             initializeGlobalSettings(args);
609
610             showSplash = Global.isWindowVisible("SplashScreen");
611             if (showSplash)
612                 splash.show();
613
614             dbConn = setupDatabaseConnection();
615
616             // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
617             Global.getFileManager().purgeResDirectory();
618
619         } catch (InitializationException e) {
620             // Fatal
621             e.printStackTrace();
622             QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
623             return;
624         }
625
626         NeverNote application = new NeverNote(dbConn);
627
628                 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
629                 if (Global.wasWindowMaximized())
630                         application.showMaximized();
631                 else
632                         application.show();
633                 if (showSplash)
634                         splash.finish(application);
635                 QApplication.exec();
636                 System.out.println("Goodbye.");
637                 QApplication.exit();
638         }
639
640     /**
641      * Open the internal database, or create if not present
642      *
643      * @throws InitializationException when opening the database fails, e.g. because another process has it locked
644      */
645     private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
646         ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
647         DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
648
649         if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
650             boolean goodCheck = false;
651             while (!goodCheck) {
652                 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
653                 dialog.exec();
654                 if (!dialog.okPressed())
655                     System.exit(0);
656                 Global.cipherPassword = dialog.getPassword();
657                 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
658                         Global.getDatabaseUserPassword(), Global.cipherPassword);
659             }
660         }
661         return dbConn;
662     }
663
664         private static void initializeGlobalSettings(String[] args) throws InitializationException {
665                 StartupConfig startupConfig = new StartupConfig();
666
667                 for (String arg : args) {
668                         String lower = arg.toLowerCase();
669                         if (lower.startsWith("--name="))
670                                 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
671                         if (lower.startsWith("--home="))
672                                 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
673                         if (lower.startsWith("--disable-viewing"))
674                                 startupConfig.setDisableViewing(true);
675                 }
676
677                 Global.setup(startupConfig);
678         }
679
680     // Exit point
681         @Override
682         public void closeEvent(QCloseEvent event) {     
683                 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
684                 waitCursor(true);
685                 
686                 if (currentNote!= null & browserWindow!=null) {
687                         if (!currentNote.getTitle().equals(browserWindow.getTitle()))
688                                 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
689                 }
690                 saveNote();
691                 setMessage(tr("Beginning shutdown."));
692
693                 externalFileEditedSaver();
694                 if (Global.isConnected && Global.synchronizeOnClose()) {
695                         setMessage(tr("Performing synchronization before closing."));
696                         syncRunner.addWork("SYNC");
697                 }
698                 setMessage("Closing Program.");
699                 threadMonitorTimer.stop();
700
701                 syncRunner.addWork("STOP");
702                 indexRunner.addWork("STOP");
703                 saveNote();
704                 listManager.stop();
705                 saveWindowState();
706
707                 if (tempFiles != null)
708                         tempFiles.clear();
709
710                 browserWindow.noteSignal.tagsChanged.disconnect();
711                 browserWindow.noteSignal.titleChanged.disconnect();
712                 browserWindow.noteSignal.noteChanged.disconnect();
713                 browserWindow.noteSignal.notebookChanged.disconnect();
714                 browserWindow.noteSignal.createdDateChanged.disconnect();
715                 browserWindow.noteSignal.alteredDateChanged.disconnect();
716                 syncRunner.searchSignal.listChanged.disconnect();
717                 syncRunner.tagSignal.listChanged.disconnect();
718         syncRunner.notebookSignal.listChanged.disconnect();
719         syncRunner.noteIndexSignal.listChanged.disconnect();
720
721
722                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
723                 Global.setColumnPosition("noteTableCreationPosition", position);
724                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
725                 Global.setColumnPosition("noteTableTagPosition", position);
726                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
727                 Global.setColumnPosition("noteTableNotebookPosition", position);
728                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
729                 Global.setColumnPosition("noteTableChangedPosition", position);
730                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
731                 Global.setColumnPosition("noteTableAuthorPosition", position);
732                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
733                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
734                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
735                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
736                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
737                 Global.setColumnPosition("noteTableTitlePosition", position);
738                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
739                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
740                 
741                 saveNoteIndexWidth();
742                 
743                 int width = notebookTree.columnWidth(0);
744                 Global.setColumnWidth("notebookTreeName", width);
745                 width = tagTree.columnWidth(0);
746                 Global.setColumnWidth("tagTreeName", width);
747                 
748                 Global.saveWindowMaximized(isMaximized());
749                 Global.saveCurrentNoteGuid(currentNoteGuid);
750                         
751                 int sortCol = noteTableView.proxyModel.sortColumn();
752                 int sortOrder = noteTableView.proxyModel.sortOrder().value();
753                 Global.setSortColumn(sortCol);
754                 Global.setSortOrder(sortOrder);
755                 
756                 hide();
757                 trayIcon.hide();
758                 Global.keepRunning = false;
759                 try {
760                         logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
761                         indexRunner.thread().join(50);
762                         logger.log(logger.MEDIUM, "Index thread has stopped");
763                 } catch (InterruptedException e1) {
764                         e1.printStackTrace();
765                 }
766                 if (!syncRunner.isIdle()) {
767                         try {
768                                 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
769                                 syncThread.join();
770                                 logger.log(logger.MEDIUM, "Sync thread has stopped");
771                         } catch (InterruptedException e1) {
772                                 e1.printStackTrace();
773                         }
774                 }
775
776                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
777         }
778
779         public void setMessage(String s) {
780                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
781                 logger.log(logger.HIGH, "Message: " +s);
782                 statusBar.showMessage(s);
783                 emitLog.add(s);
784                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
785         }
786                 
787         private void waitCursor(boolean wait) {
788                 if (wait)
789                         QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
790                 else
791                         QApplication.restoreOverrideCursor();
792         }
793         
794         private void setupIndexListeners() {
795                 indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
796                 indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
797 //                      indexRunner.threadSignal.indexNeeded.connect(listManager, "setIndexNeeded(String, String, Boolean)");
798         }
799         private void setupSyncSignalListeners() {
800                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
801         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
802         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
803         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
804         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
805         
806                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
807                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
808                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
809                 
810                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
811                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
812                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
813                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
814                 
815                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
816         }
817         
818         private void setupBrowserSignalListeners() {
819                 
820                 browserWindow.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
821                 browserWindow.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
822             browserWindow.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
823                 browserWindow.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
824             browserWindow.noteSignal.noteChanged.connect(this, "setNoteDirty()");
825             browserWindow.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
826 //          browserWindow.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
827             browserWindow.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
828             browserWindow.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
829             browserWindow.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
830             browserWindow.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
831             browserWindow.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
832             browserWindow.noteSignal.geoChanged.connect(this, "setNoteDirty()");
833             browserWindow.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
834             browserWindow.focusLost.connect(this, "saveNote()");
835             browserWindow.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
836         }
837
838         
839
840         //***************************************************************
841         //***************************************************************
842         //* Settings and look & feel
843         //***************************************************************
844         //***************************************************************
845         @SuppressWarnings("unused")
846         private void settings() {
847                 logger.log(logger.HIGH, "Entering NeverNote.settings");
848         ConfigDialog settings = new ConfigDialog(this);
849         String dateFormat = Global.getDateFormat();
850         String timeFormat = Global.getTimeFormat();
851         
852         settings.exec();
853         if (Global.showTrayIcon())
854                 trayIcon.show();
855         else
856                 trayIcon.hide();
857         showColumns();
858         if (menuBar.showEditorBar.isChecked())
859                 showEditorButtons();
860         
861         // Reset the save timer
862         if (Global.getAutoSaveInterval() > 0)
863                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
864         else
865                 saveTimer.stop();
866         
867         // This is a hack to force a reload of the index in case the date or time changed.
868 //        if (!dateFormat.equals(Global.getDateFormat()) ||
869 //                      !timeFormat.equals(Global.getTimeFormat())) {
870                 noteCache.clear();
871                 noteIndexUpdated(true);
872 //        }
873         
874         logger.log(logger.HIGH, "Leaving NeverNote.settings");
875         }
876         // Restore things to the way they were
877         private void restoreWindowState() {
878                 // We need to name things or this doesn't work.
879                 setObjectName("NeverNote");
880                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
881                 browserIndexSplitter.setObjectName("browserIndexSplitter");
882                 leftSplitter1.setObjectName("leftSplitter1");   
883                 
884                 // Restore the actual positions.
885                 restoreGeometry(Global.restoreGeometry(objectName()));
886         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
887         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
888         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
889        
890         }
891         // Save window positions for the next start
892         private void saveWindowState() {
893                 Global.saveGeometry(objectName(), saveGeometry());
894                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
895                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
896                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
897         }    
898         // Load the style sheet
899         private void loadStyleSheet() {
900                 String fileName = Global.getFileManager().getQssDirPath("default.qss");
901                 QFile file = new QFile(fileName);
902                 file.open(OpenModeFlag.ReadOnly);
903                 String styleSheet = file.readAll().toString();
904                 file.close();
905                 setStyleSheet(styleSheet);
906         }
907         // Save column widths for the next time
908         private void saveNoteIndexWidth() {
909                 int width;
910         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
911         Global.setColumnWidth("noteTableCreationPosition", width);
912                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
913                 Global.setColumnWidth("noteTableChangedPosition", width);
914                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
915                 Global.setColumnWidth("noteTableGuidPosition", width);
916                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
917                 Global.setColumnWidth("noteTableNotebookPosition", width);
918                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
919                 Global.setColumnWidth("noteTableTagPosition", width);
920                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
921                 Global.setColumnWidth("noteTableTitlePosition", width);
922                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
923                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
924                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
925                 Global.setColumnWidth("noteTableAuthorPosition", width);
926                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
927                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
928                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
929                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
930         }
931         
932         
933     //***************************************************************
934     //***************************************************************
935     //** These functions deal with Notebook menu items
936     //***************************************************************
937     //***************************************************************
938     // Setup the tree containing the user's notebooks.
939     private void initializeNotebookTree() {       
940         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
941         notebookTree.itemSelectionChanged.connect(this, "notebookTreeSelection()");
942         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
943  //     notebookTree.resize(Global.getSize("notebookTree"));
944         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
945     }   
946     // Listener when a notebook is selected
947         private void notebookTreeSelection() {
948                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
949
950                 clearTrashFilter();
951                 clearAttributeFilter();
952                 clearSavedSearchFilter();
953                 if (Global.mimicEvernoteInterface) {
954                         clearTagFilter();
955                         searchField.clear();
956                 }
957                 menuBar.noteRestoreAction.setVisible(false);            
958         menuBar.notebookEditAction.setEnabled(true);
959         menuBar.notebookDeleteAction.setEnabled(true);
960         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
961         QTreeWidgetItem currentSelection;
962         selectedNotebookGUIDs.clear();
963         if (!Global.mimicEvernoteInterface) {
964                 for (int i=0; i<selections.size(); i++) {
965                         currentSelection = selections.get(i);
966                         selectedNotebookGUIDs.add(currentSelection.text(2));
967                 }
968         
969                 
970                 // There is the potential for no notebooks to be selected if this 
971                 // happens then we make it look like all notebooks were selecetd.
972                 // If that happens, just select the "all notebooks"
973                 selections = notebookTree.selectedItems();
974                 if (selections.size()==0) {
975                         selectedNotebookGUIDs.clear();
976                         menuBar.notebookEditAction.setEnabled(false);
977                         menuBar.notebookDeleteAction.setEnabled(false);
978                 }
979         } else {
980                 String guid = "";
981                 if (selections.size() > 0)
982                         guid = (selections.get(0).text(2));
983                 if (!guid.equals(""))
984                         selectedNotebookGUIDs.add(guid);
985         }
986         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
987         listManager.loadNotesIndex();
988         noteIndexUpdated(false);
989                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
990
991     }
992     private void clearNotebookFilter() {
993         notebookTree.blockSignals(true);
994         notebookTree.clearSelection();
995                 menuBar.noteRestoreAction.setVisible(false);
996         menuBar.notebookEditAction.setEnabled(false);
997         menuBar.notebookDeleteAction.setEnabled(false);
998         selectedNotebookGUIDs.clear();
999         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1000         notebookTree.blockSignals(false);
1001     }
1002         // Triggered when the notebook DB has been updated
1003         private void notebookIndexUpdated() {
1004                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1005                 if (selectedNotebookGUIDs == null)
1006                         selectedNotebookGUIDs = new ArrayList<String>();
1007                 List<Notebook> books = conn.getNotebookTable().getAll();
1008                 for (int i=books.size()-1; i>=0; i--) {
1009                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1010                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1011                                         books.remove(i);
1012                                         j=listManager.getArchiveNotebookIndex().size();
1013                                 }
1014                         }
1015                 }
1016                 
1017                 
1018                 listManager.countNotebookResults(listManager.getNoteIndex());
1019                 notebookTree.blockSignals(true);
1020         notebookTree.load(books, listManager.getLocalNotebooks());
1021         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1022                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1023                 if (!found)
1024                         selectedNotebookGUIDs.remove(i);
1025         }
1026         notebookTree.blockSignals(false);
1027         
1028                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1029     }
1030     // Show/Hide note information
1031         private void toggleNotebookWindow() {
1032                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1033         if (notebookTree.isVisible())
1034                 notebookTree.hide();
1035         else
1036                 notebookTree.show();
1037         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1038         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1039         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1040     }   
1041         // Add a new notebook
1042         @SuppressWarnings("unused")
1043         private void addNotebook() {
1044                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1045                 NotebookEdit edit = new NotebookEdit();
1046                 edit.setNotebooks(listManager.getNotebookIndex());
1047                 edit.exec();
1048         
1049                 if (!edit.okPressed())
1050                         return;
1051         
1052                 Calendar currentTime = new GregorianCalendar();
1053                 Long l = new Long(currentTime.getTimeInMillis());
1054                 String randint = new String(Long.toString(l));
1055         
1056                 Notebook newBook = new Notebook();
1057                 newBook.setUpdateSequenceNum(0);
1058                 newBook.setGuid(randint);
1059                 newBook.setName(edit.getNotebook());
1060                 newBook.setServiceCreated(new Date().getTime());
1061                 newBook.setServiceUpdated(new Date().getTime());
1062                 newBook.setDefaultNotebook(false);
1063                 newBook.setPublished(false);
1064                 
1065                 listManager.getNotebookIndex().add(newBook);
1066                 if (edit.isLocal())
1067                         listManager.getLocalNotebooks().add(newBook.getGuid());
1068                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1069                 notebookIndexUpdated();
1070                 listManager.countNotebookResults(listManager.getNoteIndex());
1071 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1072                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1073         }
1074         // Edit an existing notebook
1075         @SuppressWarnings("unused")
1076         private void editNotebook() {
1077                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1078                 NotebookEdit edit = new NotebookEdit();
1079                 edit.setTitle(tr("Edit Notebook"));
1080                 edit.setLocalCheckboxEnabled(false);
1081                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1082                 QTreeWidgetItem currentSelection;
1083                 currentSelection = selections.get(0);
1084                 edit.setNotebook(currentSelection.text(0));
1085                 edit.setNotebooks(listManager.getNotebookIndex());
1086                 edit.exec();
1087         
1088                 if (!edit.okPressed())
1089                         return;
1090         
1091                 String guid = currentSelection.text(2);
1092                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1093                 currentSelection.setText(0, edit.getNotebook());
1094                 
1095                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1096                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1097                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1098                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1099                                 i=listManager.getNotebookIndex().size();
1100                         }
1101                 }
1102                 
1103                 // Build a list of non-closed notebooks
1104                 List<Notebook> nbooks = new ArrayList<Notebook>();
1105                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1106                         boolean found=false;
1107                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1108                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1109                                         found = true;
1110                         }
1111                         if (!found)
1112                                 nbooks.add(listManager.getNotebookIndex().get(i));
1113                 }
1114                 
1115                 browserWindow.setNotebookList(nbooks);
1116                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1117         }
1118         // Delete an existing notebook
1119         @SuppressWarnings("unused")
1120         private void deleteNotebook() {
1121                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1122                 boolean assigned = false;
1123                 // Check if any notes have this notebook
1124                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1125         for (int i=0; i<selections.size(); i++) {
1126                 QTreeWidgetItem currentSelection;
1127                 currentSelection = selections.get(i);
1128                 String guid = currentSelection.text(2);
1129                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1130                         String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1131                         if (noteGuid.equals(guid)) {
1132                                 assigned = true;
1133                                 j=listManager.getNoteIndex().size();
1134                                 i=selections.size();
1135                         }
1136                 }
1137         }
1138                 if (assigned) {
1139                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1140                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1141                         return;
1142                 }
1143                 
1144                 if (conn.getNotebookTable().getAll().size() == 1) {
1145                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1146                         return;
1147                 }
1148         
1149         // If all notebooks are clear, verify the delete
1150                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected notebooks?"),
1151                         QMessageBox.StandardButton.Yes, 
1152                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1153                         return;
1154                 }
1155                 
1156                 // If confirmed, delete the notebook
1157         for (int i=selections.size()-1; i>=0; i--) {
1158                 QTreeWidgetItem currentSelection;
1159                 currentSelection = selections.get(i);
1160                 String guid = currentSelection.text(2);
1161                 conn.getNotebookTable().expungeNotebook(guid, true);
1162                 listManager.deleteNotebook(guid);
1163         }
1164 //        for (int i=<dbRunner.getLocalNotebooks().size()-1; i>=0; i--) {
1165  //             if (dbRunner.getLocalNotebooks().get(i).equals(arg0))
1166  //       }
1167         notebookTreeSelection();
1168         notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1169         listManager.countNotebookResults(listManager.getNoteIndex());
1170 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1171         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1172         }
1173         // A note's notebook has been updated
1174         @SuppressWarnings("unused")
1175         private void updateNoteNotebook(String guid, String notebookGuid) {
1176                 
1177                 // Update the list manager
1178                 listManager.updateNoteNotebook(guid, notebookGuid);
1179                 listManager.countNotebookResults(listManager.getNoteIndex());
1180 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1181                 
1182                 // Find the name of the notebook
1183                 String notebookName = null;
1184                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1185                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1186                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1187                                 i=listManager.getNotebookIndex().size();
1188                         }
1189                 }
1190                 
1191                 // If we found the name, update the browser window
1192                 if (notebookName != null) {
1193                         updateListNoteNotebook(guid, notebookName);
1194                         if (guid.equals(currentNoteGuid)) {
1195                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1196                                 if (pos >=0)
1197                                         browserWindow.notebookBox.setCurrentIndex(pos);
1198                         }
1199                 }
1200                 
1201                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1202                 if (guid.equals(currentNoteGuid)) {
1203                         if (currentNote != null) {
1204                                 currentNote.setNotebookGuid(notebookGuid);
1205                         }
1206                 }
1207         }
1208         // Open/close notebooks
1209         @SuppressWarnings("unused")
1210         private void closeNotebooks() {
1211                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1212                 na.exec();
1213                 if (!na.okClicked())
1214                         return;
1215                 
1216                 waitCursor(true);
1217                 listManager.getArchiveNotebookIndex().clear();
1218                 
1219                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1220                         String text = na.getClosedBookList().takeItem(i).text();
1221                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1222                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1223                                         Notebook n = listManager.getNotebookIndex().get(j);
1224                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1225                                         listManager.getArchiveNotebookIndex().add(n);
1226                                         j=listManager.getNotebookIndex().size();
1227                                 }
1228                         }
1229                 }
1230                 
1231                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1232                         String text = na.getOpenBookList().takeItem(i).text();
1233                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1234                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1235                                         Notebook n = listManager.getNotebookIndex().get(j);
1236                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1237                                         j=listManager.getNotebookIndex().size();
1238                                 }
1239                         }
1240                 }
1241                 notebookTreeSelection();
1242                 listManager.loadNotesIndex();
1243                 notebookIndexUpdated();
1244                 noteIndexUpdated(false);
1245 //              noteIndexUpdated(false);
1246                 
1247                 // Build a list of non-closed notebooks
1248                 List<Notebook> nbooks = new ArrayList<Notebook>();
1249                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1250                         boolean found=false;
1251                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1252                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1253                                         found = true;
1254                         }
1255                         if (!found)
1256                                 nbooks.add(listManager.getNotebookIndex().get(i));
1257                 }
1258                 waitCursor(false);
1259                 browserWindow.setNotebookList(nbooks);
1260         }
1261
1262         
1263         
1264         
1265         
1266     //***************************************************************
1267     //***************************************************************
1268     //** These functions deal with Tag menu items
1269     //***************************************************************
1270     //***************************************************************
1271         // Add a new notebook
1272         @SuppressWarnings("unused")
1273         private void addTag() {
1274                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1275                 TagEdit edit = new TagEdit();
1276                 edit.setTagList(listManager.getTagIndex());
1277                 edit.exec();
1278         
1279                 if (!edit.okPressed())
1280                         return;
1281         
1282                 Calendar currentTime = new GregorianCalendar();
1283                 Long l = new Long(currentTime.getTimeInMillis());
1284                 String randint = new String(Long.toString(l));
1285         
1286                 Tag newTag = new Tag();
1287                 newTag.setUpdateSequenceNum(0);
1288                 newTag.setGuid(randint);
1289                 newTag.setName(edit.getTag());
1290                 conn.getTagTable().addTag(newTag, true);
1291                 listManager.getTagIndex().add(newTag);
1292                 reloadTagTree();
1293                 
1294                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1295         }
1296         private void reloadTagTree() {
1297                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1298                 tagIndexUpdated(false);
1299                 boolean filter = false;
1300                 listManager.countTagResults(listManager.getNoteIndex());
1301                 if (notebookTree.selectedItems().size() > 0 
1302                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1303                                                   filter = true;
1304                 if (tagTree.selectedItems().size() > 0)
1305                         filter = true;
1306                 tagTree.showAllTags(!filter);
1307                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1308         }
1309         // Edit an existing tag
1310         @SuppressWarnings("unused")
1311         private void editTag() {
1312                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1313                 TagEdit edit = new TagEdit();
1314                 edit.setTitle("Edit Tag");
1315                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1316                 QTreeWidgetItem currentSelection;
1317                 currentSelection = selections.get(0);
1318                 edit.setTag(currentSelection.text(0));
1319                 edit.setTagList(listManager.getTagIndex());
1320                 edit.exec();
1321         
1322                 if (!edit.okPressed())
1323                         return;
1324         
1325                 String guid = currentSelection.text(2);
1326                 currentSelection.setText(0,edit.getTag());
1327                 
1328                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1329                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1330                                 listManager.getTagIndex().get(i).setName(edit.getTag());
1331                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1332                                 updateListTagName(guid);
1333                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1334                                         browserWindow.setTag(getTagNamesForNote(currentNote));
1335                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1336                                 return;
1337                         }
1338                 }
1339                 browserWindow.setTag(getTagNamesForNote(currentNote));
1340                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1341         }
1342         // Delete an existing tag
1343         @SuppressWarnings("unused")
1344         private void deleteTag() {
1345                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1346                 
1347                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1348                         QMessageBox.StandardButton.Yes, 
1349                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1350                                                         return;
1351                 }
1352                 
1353                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1354         for (int i=selections.size()-1; i>=0; i--) {
1355                 QTreeWidgetItem currentSelection;
1356                 currentSelection = selections.get(i);                   
1357                 removeTagItem(currentSelection.text(2));
1358         }
1359         tagIndexUpdated(true);
1360         tagTreeSelection();
1361         listManager.countTagResults(listManager.getNoteIndex());
1362 //              tagTree.updateCounts(listManager.getTagCounter());
1363         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1364         }
1365         // Remove a tag tree item.  Go recursively down & remove the children too
1366         private void removeTagItem(String guid) {
1367         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
1368                 String parent = listManager.getTagIndex().get(j).getParentGuid();
1369                 if (parent != null && parent.equals(guid)) {            
1370                         //Remove this tag's children
1371                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
1372                 }
1373         }
1374         //Now, remove this tag
1375         removeListTagName(guid);
1376         conn.getTagTable().expungeTag(guid, true);                      
1377         for (int a=0; a<listManager.getTagIndex().size(); a++) {
1378                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1379                         listManager.getTagIndex().remove(a);
1380                         return;
1381                 }
1382         }
1383         }
1384         // Setup the tree containing the user's tags
1385     private void initializeTagTree() {
1386         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1387         tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1388         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1389         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1390     }
1391     // Listener when a tag is selected
1392         private void tagTreeSelection() {
1393         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1394                 
1395         clearTrashFilter();
1396         clearAttributeFilter();
1397         clearSavedSearchFilter();
1398         
1399                 menuBar.noteRestoreAction.setVisible(false);
1400                 
1401         List<QTreeWidgetItem> selections = tagTree.selectedItems();
1402         QTreeWidgetItem currentSelection;
1403         selectedTagGUIDs.clear();
1404         for (int i=0; i<selections.size(); i++) {
1405                 currentSelection = selections.get(i);
1406                 selectedTagGUIDs.add(currentSelection.text(2));
1407         }
1408         if (selections.size() > 0) {
1409                 menuBar.tagEditAction.setEnabled(true);
1410                 menuBar.tagDeleteAction.setEnabled(true);
1411         }
1412         else {
1413                 menuBar.tagEditAction.setEnabled(false);
1414                 menuBar.tagDeleteAction.setEnabled(false);
1415         }
1416         listManager.setSelectedTags(selectedTagGUIDs);
1417         listManager.loadNotesIndex();
1418         noteIndexUpdated(false);
1419         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1420     }
1421     // trigger the tag index to be refreshed
1422     @SuppressWarnings("unused")
1423         private void tagIndexUpdated() {
1424         tagIndexUpdated(true);
1425     }
1426     private void tagIndexUpdated(boolean reload) {
1427         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1428                 if (selectedTagGUIDs == null)
1429                         selectedTagGUIDs = new ArrayList<String>();
1430 //              selectedTagGUIDs.clear();  // clear out old entries
1431
1432                 tagTree.blockSignals(true);
1433                 if (reload)
1434                         tagTree.load(listManager.getTagIndex());
1435         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1436                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1437                 if (!found)
1438                         selectedTagGUIDs.remove(i);
1439         }
1440         tagTree.blockSignals(false);
1441         
1442                 browserWindow.setTag(getTagNamesForNote(currentNote));
1443         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1444     }   
1445     // Show/Hide note information
1446         private void toggleTagWindow() {
1447                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1448         if (tagTree.isVisible())
1449                 tagTree.hide();
1450         else
1451                 tagTree.show();
1452         menuBar.hideTags.setChecked(tagTree.isVisible());
1453         Global.saveWindowVisible("tagTree", tagTree.isVisible());
1454         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1455     }   
1456         // A note's tags have been updated
1457         @SuppressWarnings("unused")
1458         private void updateNoteTags(String guid, List<String> tags) {
1459                 // Save any new tags.  We'll need them later.
1460                 List<String> newTags = new ArrayList<String>();
1461                 for (int i=0; i<tags.size(); i++) {
1462                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
1463                                 newTags.add(tags.get(i));
1464                 }
1465                 
1466                 listManager.saveNoteTags(guid, tags);
1467                 listManager.countTagResults(listManager.getNoteIndex());
1468                 StringBuffer names = new StringBuffer("");
1469                 for (int i=0; i<tags.size(); i++) {
1470                         names = names.append(tags.get(i));
1471                         if (i<tags.size()-1) {
1472                                 names.append(Global.tagDelimeter + " ");
1473                         }
1474                 }
1475                 browserWindow.setTag(names.toString());
1476                 noteDirty = true;
1477                 
1478                 // Now, we need to add any new tags to the tag tree
1479                 for (int i=0; i<newTags.size(); i++) 
1480                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
1481         }
1482         // Get a string containing all tag names for a note
1483         private String getTagNamesForNote(Note n) {
1484                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
1485                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
1486                         return "";
1487                 StringBuffer buffer = new StringBuffer(100);
1488                 Vector<String> v = new Vector<String>();
1489                 List<String> guids = n.getTagGuids();
1490                 
1491                 if (guids == null) 
1492                         return "";
1493                 
1494                 for (int i=0; i<guids.size(); i++) {
1495                         v.add(listManager.getTagNameByGuid(guids.get(i)));
1496                 }
1497                 Comparator<String> comparator = Collections.reverseOrder();
1498                 Collections.sort(v,comparator);
1499                 Collections.reverse(v);
1500                 
1501                 for (int i = 0; i<v.size(); i++) {
1502                         if (i>0) 
1503                                 buffer.append(", ");
1504                         buffer.append(v.get(i));
1505                 }
1506                 
1507                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
1508                 return buffer.toString();
1509         }       
1510         // Tags were added via dropping notes from the note list
1511         @SuppressWarnings("unused")
1512         private void tagsAdded(String noteGuid, String tagGuid) {
1513                 String tagName = null;
1514                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1515                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
1516                                 tagName = listManager.getTagIndex().get(i).getName();
1517                                 i=listManager.getTagIndex().size();
1518                         }
1519                 }
1520                 if (tagName == null)
1521                         return;
1522                 
1523                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
1524                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
1525                                 List<String> tagNames = new ArrayList<String>();
1526                                 tagNames.add(new String(tagName));
1527                                 Note n = listManager.getMasterNoteIndex().get(i);
1528                                 for (int j=0; j<n.getTagNames().size(); j++) {
1529                                         tagNames.add(new String(n.getTagNames().get(j)));
1530                                 }
1531                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
1532                                 if (n.getGuid().equals(currentNoteGuid)) {
1533                                         Collections.sort(tagNames);
1534                                         String display = "";
1535                                         for (int j=0; j<tagNames.size(); j++) {
1536                                                 display = display+tagNames.get(j);
1537                                                 if (j+2<tagNames.size()) 
1538                                                         display = display+Global.tagDelimeter+" ";
1539                                         }
1540                                         browserWindow.setTag(display);
1541                                 }
1542                                 i=listManager.getMasterNoteIndex().size();
1543                         }
1544                 }
1545                 
1546                 
1547                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
1548         }
1549         private void clearTagFilter() {
1550                 tagTree.blockSignals(true);
1551                 tagTree.clearSelection();
1552                 menuBar.noteRestoreAction.setVisible(false);
1553                 menuBar.tagEditAction.setEnabled(false);
1554                 menuBar.tagDeleteAction.setEnabled(false);
1555                 selectedTagGUIDs.clear();
1556         listManager.setSelectedTags(selectedTagGUIDs);
1557         tagTree.blockSignals(false);
1558         }
1559         
1560         
1561     //***************************************************************
1562     //***************************************************************
1563     //** These functions deal with Saved Search menu items
1564     //***************************************************************
1565     //***************************************************************
1566         // Add a new notebook
1567         @SuppressWarnings("unused")
1568         private void addSavedSearch() {
1569                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
1570                 SavedSearchEdit edit = new SavedSearchEdit();
1571                 edit.setSearchList(listManager.getSavedSearchIndex());
1572                 edit.exec();
1573         
1574                 if (!edit.okPressed())
1575                         return;
1576         
1577                 Calendar currentTime = new GregorianCalendar();         
1578                 Long l = new Long(currentTime.getTimeInMillis());
1579                 String randint = new String(Long.toString(l));
1580         
1581                 SavedSearch search = new SavedSearch();
1582                 search.setUpdateSequenceNum(0);
1583                 search.setGuid(randint);
1584                 search.setName(edit.getName());
1585                 search.setQuery(edit.getQuery());
1586                 search.setFormat(QueryFormat.USER);
1587                 listManager.getSavedSearchIndex().add(search);
1588                 conn.getSavedSearchTable().addSavedSearch(search, true);
1589                 savedSearchIndexUpdated();
1590                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
1591         }
1592         // Edit an existing tag
1593         @SuppressWarnings("unused")
1594         private void editSavedSearch() {
1595                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
1596                 SavedSearchEdit edit = new SavedSearchEdit();
1597                 edit.setTitle("Edit Search");
1598                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1599                 QTreeWidgetItem currentSelection;
1600                 currentSelection = selections.get(0);
1601                 String guid = currentSelection.text(1);
1602                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
1603                 edit.setName(currentSelection.text(0));
1604                 edit.setQuery(s.getQuery());
1605                 edit.setSearchList(listManager.getSavedSearchIndex());
1606                 edit.exec();
1607         
1608                 if (!edit.okPressed())
1609                         return;
1610         
1611                 List<SavedSearch> list = listManager.getSavedSearchIndex();
1612                 SavedSearch search = null;
1613                 boolean found = false;
1614                 for (int i=0; i<list.size(); i++) {
1615                         search = list.get(i);
1616                         if (search.getGuid().equals(guid)) {
1617                                 i=list.size();
1618                                 found = true;
1619                         }
1620                 }
1621                 if (!found)
1622                         return;
1623                 search.setName(edit.getName());
1624                 search.setQuery(edit.getQuery());
1625                 conn.getSavedSearchTable().updateSavedSearch(search, true);
1626                 savedSearchIndexUpdated();
1627                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
1628         }
1629         // Delete an existing tag
1630         @SuppressWarnings("unused")
1631         private void deleteSavedSearch() {
1632                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
1633                 
1634                 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
1635                         QMessageBox.StandardButton.Yes, 
1636                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1637                                                         return;
1638                 }
1639                 
1640                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1641         for (int i=selections.size()-1; i>=0; i--) {
1642                 QTreeWidgetItem currentSelection;
1643                 currentSelection = selections.get(i);
1644                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
1645                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
1646                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
1647                                 listManager.getSavedSearchIndex().remove(j);
1648                                 j=listManager.getSavedSearchIndex().size()+1;
1649                         }
1650                 }
1651                 selections.remove(i);
1652         }
1653         savedSearchIndexUpdated();
1654         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
1655         }
1656     // Setup the tree containing the user's tags
1657     private void initializeSavedSearchTree() {
1658         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
1659         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
1660         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
1661     }
1662     // Listener when a tag is selected
1663     @SuppressWarnings("unused")
1664         private void savedSearchTreeSelection() {
1665         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
1666
1667         clearNotebookFilter();
1668         clearTagFilter();
1669         clearTrashFilter();
1670         clearAttributeFilter();
1671         
1672         String currentGuid = selectedSavedSearchGUID;
1673         menuBar.savedSearchEditAction.setEnabled(true);
1674         menuBar.savedSearchDeleteAction.setEnabled(true);
1675         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1676         QTreeWidgetItem currentSelection;
1677         selectedSavedSearchGUID = "";
1678         for (int i=0; i<selections.size(); i++) {
1679                 currentSelection = selections.get(i);
1680                 if (currentSelection.text(1).equals(currentGuid)) {
1681                         currentSelection.setSelected(false);
1682                 } else {
1683                         selectedSavedSearchGUID = currentSelection.text(1);
1684                 }
1685 //              i = selections.size() +1;
1686         }
1687         
1688         // There is the potential for no notebooks to be selected if this 
1689         // happens then we make it look like all notebooks were selecetd.
1690         // If that happens, just select the "all notebooks"
1691         if (selections.size()==0) {
1692                 clearSavedSearchFilter();
1693         }
1694         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1695         
1696         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
1697     }
1698     private void clearSavedSearchFilter() {
1699         menuBar.savedSearchEditAction.setEnabled(false);
1700         menuBar.savedSearchDeleteAction.setEnabled(false);
1701         savedSearchTree.blockSignals(true);
1702         savedSearchTree.clearSelection();
1703         savedSearchTree.blockSignals(false);
1704         selectedSavedSearchGUID = "";
1705         searchField.setEditText("");
1706         searchPerformed = false;
1707         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1708     }
1709     // trigger the tag index to be refreshed
1710         private void savedSearchIndexUpdated() { 
1711                 if (selectedSavedSearchGUID == null)
1712                         selectedSavedSearchGUID = new String();
1713                 savedSearchTree.blockSignals(true);
1714         savedSearchTree.load(listManager.getSavedSearchIndex());
1715         savedSearchTree.selectGuid(selectedSavedSearchGUID);
1716         savedSearchTree.blockSignals(false);
1717     }
1718     // trigger when the saved search selection changes
1719     @SuppressWarnings("unused")
1720         private void updateSavedSearchSelection() {
1721                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
1722                 
1723         menuBar.savedSearchEditAction.setEnabled(true);
1724         menuBar.savedSearchDeleteAction.setEnabled(true);
1725         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1726
1727         if (selections.size() > 0) {
1728                 menuBar.savedSearchEditAction.setEnabled(true);
1729                 menuBar.savedSearchDeleteAction.setEnabled(true);
1730                 selectedSavedSearchGUID = selections.get(0).text(1);
1731                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
1732                 searchField.setEditText(s.getQuery());
1733         } else { 
1734                 menuBar.savedSearchEditAction.setEnabled(false);
1735                 menuBar.savedSearchDeleteAction.setEnabled(false);
1736                 selectedSavedSearchGUID = "";
1737                 searchField.setEditText("");
1738         }
1739         searchFieldChanged();
1740         
1741                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
1742
1743         
1744     }
1745     // Show/Hide note information
1746         private void toggleSavedSearchWindow() {
1747                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
1748         if (savedSearchTree.isVisible())
1749                 savedSearchTree.hide();
1750         else
1751                 savedSearchTree.show();
1752         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
1753                                 
1754                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
1755         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
1756     }
1757         
1758         
1759         
1760         
1761     //***************************************************************
1762     //***************************************************************
1763     //** These functions deal with Help menu & tool menu items
1764     //***************************************************************
1765     //***************************************************************
1766         // Show database status
1767         @SuppressWarnings("unused")
1768         private void databaseStatus() {
1769                 waitCursor(true);
1770                 int dirty = conn.getNoteTable().getDirtyCount();
1771                 int unindexed = conn.getNoteTable().getUnindexedCount();
1772                 DatabaseStatus status = new DatabaseStatus();
1773                 status.setUnsynchronized(dirty);
1774                 status.setUnindexed(unindexed);
1775                 status.setNoteCount(conn.getNoteTable().getNoteCount());
1776                 status.setNotebookCount(listManager.getNotebookIndex().size());
1777                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
1778                 status.setTagCount(listManager.getTagIndex().size());
1779                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
1780                 status.setWordCount(conn.getWordsTable().getWordCount());
1781                 waitCursor(false);
1782                 status.exec();
1783         }
1784         // Compact the database
1785         @SuppressWarnings("unused")
1786         private void compactDatabase() {
1787         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
1788                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
1789                                 "but please be aware that depending upon the size of your database this can be time consuming " +
1790                                 "and NeverNote will be unresponsive until it is complete.  Do you wish to continue?"),
1791                                 QMessageBox.StandardButton.Yes, 
1792                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
1793                                                         return;
1794                 }
1795                 setMessage("Compacting database.");
1796                 waitCursor(true);
1797                 listManager.compactDatabase();
1798                 waitCursor(false);
1799                 setMessage("Database compact is complete.");            
1800         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
1801     }
1802         @SuppressWarnings("unused")
1803         private void accountInformation() {
1804                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
1805                 AccountDialog dialog = new AccountDialog();
1806                 dialog.show();
1807                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
1808         }
1809         @SuppressWarnings("unused")
1810         private void releaseNotes() {
1811                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
1812                 QDialog dialog = new QDialog(this);
1813                 QHBoxLayout layout = new QHBoxLayout();
1814                 QTextEdit textBox = new QTextEdit();
1815                 layout.addWidget(textBox);
1816                 textBox.setReadOnly(true);
1817                 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
1818                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
1819                 QIODevice.OpenModeFlag.Text)))
1820                         return;
1821                 textBox.setText(file.readAll().toString());
1822                 file.close();
1823                 dialog.setWindowTitle(tr("Release Notes"));
1824                 dialog.setLayout(layout);
1825                 dialog.show();
1826                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
1827         }
1828         // Called when user picks Log from the help menu
1829         @SuppressWarnings("unused")
1830         private void logger() {
1831                 logger.log(logger.HIGH, "Entering NeverNote.logger");
1832                 QDialog dialog = new QDialog(this);
1833                 QHBoxLayout layout = new QHBoxLayout();
1834                 QListWidget textBox = new QListWidget();
1835                 layout.addWidget(textBox);
1836                 textBox.addItems(emitLog);
1837                 
1838                 dialog.setLayout(layout);
1839                 dialog.setWindowTitle(tr("Mesasge Log"));
1840                 dialog.show();
1841                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
1842         }
1843         // Menu option "help/about" was selected
1844         @SuppressWarnings("unused")
1845         private void about() {
1846                 logger.log(logger.HIGH, "Entering NeverNote.about");
1847                 QMessageBox.about(this, 
1848                                                 tr("About NeverNote"),
1849                                                 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
1850                                                 +Global.version
1851                                                 +tr("<hr></center>Evernote"
1852                                                                 +" Generic client.<br><br>" 
1853                                                                 +"Licensed under GPL v2.  <br><hr><br>"
1854                                                                 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
1855                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
1856                                                                 +"PDFRenderer is licened under the LGPL<br>"
1857                                                                 +"Jazzy is licened under the LGPL<br>"
1858                                                                 +"Java is a registered trademark of Sun Microsystems.<br><hr>"));       
1859                 logger.log(logger.HIGH, "Leaving NeverNote.about");
1860         }
1861         // Hide the entire left hand side
1862         @SuppressWarnings("unused")
1863         private void toggleLeftSide() {
1864                 boolean hidden;
1865                 
1866                 hidden = !menuBar.hideLeftSide.isChecked();
1867                 menuBar.hideLeftSide.setChecked(!hidden);
1868                 
1869                 if (notebookTree.isVisible() != hidden)
1870                         toggleNotebookWindow();
1871                 if (savedSearchTree.isVisible() != hidden)
1872                         toggleSavedSearchWindow();
1873                 if (tagTree.isVisible() != hidden)
1874                         toggleTagWindow();
1875                 if (attributeTree.isVisible() != hidden)
1876                         toggleAttributesWindow();
1877                 if (trashTree.isVisible() != hidden)
1878                         toggleTrashWindow();
1879                 
1880                 Global.saveWindowVisible("leftPanel", hidden);
1881                 
1882         }
1883                         
1884         
1885     //***************************************************************
1886     //***************************************************************
1887     //** These functions deal with the Toolbar
1888     //***************************************************************
1889     //***************************************************************  
1890         // Text in the search bar has been cleared
1891         private void searchFieldCleared() {
1892                 searchField.setEditText("");
1893                 saveNoteIndexWidth();
1894         }
1895         // text in the search bar changed.  We only use this to tell if it was cleared, 
1896         // otherwise we trigger off searchFieldChanged.
1897         @SuppressWarnings("unused")
1898         private void searchFieldTextChanged(String text) {
1899                 if (text.trim().equals("")) {
1900                         searchFieldCleared();
1901                         if (searchPerformed) {
1902                                 noteCache.clear();
1903                                 listManager.setEnSearch("");
1904 /////                           listManager.clearNoteIndexSearch();
1905                                 //noteIndexUpdated(true);
1906                                 listManager.loadNotesIndex();
1907                                 refreshEvernoteNote(true);
1908                                 noteIndexUpdated(false);
1909                         }
1910                         searchPerformed = false;
1911                 }
1912         }
1913     // Text in the toolbar has changed
1914     private void searchFieldChanged() {
1915         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
1916         noteCache.clear();
1917         saveNoteIndexWidth();
1918         String text = searchField.currentText();
1919         listManager.setEnSearch(text.trim());
1920         listManager.loadNotesIndex();
1921 //--->>>        noteIndexUpdated(true);
1922         noteIndexUpdated(false);
1923         refreshEvernoteNote(true);
1924         searchPerformed = true;
1925         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
1926     }
1927     // Build the window tool bar
1928     private void setupToolBar() {
1929         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
1930         toolBar = addToolBar(tr("toolBar"));    
1931
1932         prevButton = toolBar.addAction("Previous");
1933         QIcon prevIcon = new QIcon(iconPath+"back.png");
1934         prevButton.setIcon(prevIcon);
1935         prevButton.triggered.connect(this, "previousViewedAction()");   
1936         
1937         nextButton = toolBar.addAction("Next");
1938         QIcon nextIcon = new QIcon(iconPath+"forward.png");
1939         nextButton.setIcon(nextIcon);
1940         nextButton.triggered.connect(this, "nextViewedAction()");       
1941         
1942         upButton = toolBar.addAction("Up");
1943         QIcon upIcon = new QIcon(iconPath+"up.png");
1944         upButton.setIcon(upIcon);
1945         upButton.triggered.connect(this, "upAction()");         
1946         
1947         downButton = toolBar.addAction("Down");
1948         QIcon downIcon = new QIcon(iconPath+"down.png");
1949         downButton.setIcon(downIcon);
1950         downButton.triggered.connect(this, "downAction()");
1951         
1952         synchronizeButton = toolBar.addAction("Synchronize");
1953         synchronizeAnimation = new ArrayList<QIcon>();
1954         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-0.png"));
1955         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-1.png"));
1956         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-2.png"));
1957         synchronizeAnimation.add(new QIcon(iconPath+"synchronize-3.png"));
1958         synchronizeButton.setIcon(synchronizeAnimation.get(0));
1959         synchronizeFrame = 0;
1960         synchronizeButton.triggered.connect(this, "evernoteSync()");
1961         
1962         printButton = toolBar.addAction("Print");
1963         QIcon printIcon = new QIcon(iconPath+"print.png");
1964         printButton.setIcon(printIcon);
1965         printButton.triggered.connect(this, "printNote()");
1966         
1967         tagButton = toolBar.addAction("Tag"); 
1968         QIcon tagIcon = new QIcon(iconPath+"tag.png");
1969         tagButton.setIcon(tagIcon);
1970         tagButton.triggered.connect(browserWindow, "modifyTags()");
1971         
1972         attributeButton = toolBar.addAction("Attributes"); 
1973         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
1974         attributeButton.setIcon(attributeIcon);
1975         attributeButton.triggered.connect(this, "toggleNoteInformation()");
1976                 
1977         emailButton = toolBar.addAction("Email");
1978         QIcon emailIcon = new QIcon(iconPath+"email.png");
1979         emailButton.setIcon(emailIcon);
1980         emailButton.triggered.connect(this, "emailNote()");
1981         
1982         deleteButton = toolBar.addAction("Delete");     
1983         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
1984         deleteButton.setIcon(deleteIcon);
1985         deleteButton.triggered.connect(this, "deleteNote()");
1986                 
1987         newButton = toolBar.addAction("New");
1988         QIcon newIcon = new QIcon(iconPath+"new.png");
1989         newButton.triggered.connect(this, "addNote()");
1990         newButton.setIcon(newIcon);
1991         toolBar.addSeparator();
1992         toolBar.addWidget(new QLabel("Quota:"));
1993         toolBar.addWidget(quotaBar);
1994         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
1995         updateQuotaBar();
1996         
1997         // Setup the zoom
1998         zoomSpinner = new QSpinBox();
1999         zoomSpinner.setMinimum(10);
2000         zoomSpinner.setMaximum(1000);
2001         zoomSpinner.setAccelerated(true);
2002         zoomSpinner.setSingleStep(10);
2003         zoomSpinner.setValue(100);
2004         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2005         toolBar.addWidget(new QLabel("Zoom"));
2006         toolBar.addWidget(zoomSpinner);
2007         
2008         //toolBar.addWidget(new QLabel("                    "));
2009         toolBar.addSeparator();
2010         toolBar.addWidget(new QLabel("  Search:"));
2011         toolBar.addWidget(searchField);
2012         QSizePolicy sizePolicy = new QSizePolicy();
2013         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2014         searchField.setSizePolicy(sizePolicy);
2015         searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2016
2017         searchClearButton = toolBar.addAction("Search Clear");
2018         QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2019         searchClearButton.setIcon(searchClearIcon);
2020         searchClearButton.triggered.connect(this, "searchFieldCleared()");
2021         
2022         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2023     }
2024     // Update the sychronize button picture
2025     @SuppressWarnings("unused")
2026         private void updateSyncButton() {
2027         synchronizeFrame++;
2028         if (synchronizeFrame == 4) 
2029                 synchronizeFrame = 0;
2030         synchronizeButton.setIcon(synchronizeAnimation.get(synchronizeFrame));
2031     }
2032     // Synchronize with Evernote
2033         @SuppressWarnings("unused")
2034         private void evernoteSync() {
2035         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2036         if (!Global.isConnected)
2037                 remoteConnect();
2038         if (Global.isConnected)
2039                 synchronizeAnimationTimer.start(200);
2040         syncTimer();
2041         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2042     }
2043     private void updateQuotaBar() {
2044         long limit = Global.getUploadLimit();
2045         long amount = Global.getUploadAmount();
2046         if (amount>0 && limit>0) {
2047                 int percent =(int)(amount*100/limit);
2048                 quotaBar.setValue(percent);
2049         } else 
2050                 quotaBar.setValue(0);
2051     }
2052         // Zoom changed
2053     @SuppressWarnings("unused")
2054         private void zoomChanged() {
2055         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2056     }
2057
2058     //****************************************************************
2059     //****************************************************************
2060     //* System Tray functions
2061     //****************************************************************
2062     //****************************************************************
2063         private void trayToggleVisible() {
2064         if (isVisible()) {
2065                 hide();
2066         } else {
2067                 show();
2068                 raise();
2069         }
2070     }
2071     @SuppressWarnings("unused")
2072         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2073         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2074                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2075                 trayToggleVisible();
2076         }
2077     }
2078     
2079     
2080     //***************************************************************
2081     //***************************************************************
2082     //** These functions deal with the trash tree
2083     //***************************************************************
2084     //***************************************************************    
2085     // Setup the tree containing the trash.
2086     @SuppressWarnings("unused")
2087         private void trashTreeSelection() {     
2088         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2089         
2090         clearNotebookFilter();
2091         clearTagFilter();
2092         clearAttributeFilter();
2093         clearSavedSearchFilter();
2094         
2095         String tempGuid = currentNoteGuid;
2096         
2097 //      currentNoteGuid = "";
2098         currentNote = new Note();
2099         selectedNoteGUIDs.clear();
2100         listManager.getSelectedNotebooks().clear();
2101         listManager.getSelectedTags().clear();
2102         listManager.setSelectedSavedSearch("");
2103         browserWindow.clear();
2104     
2105         // toggle the add buttons
2106         newButton.setEnabled(!newButton.isEnabled());
2107         menuBar.noteAdd.setEnabled(newButton.isEnabled());
2108         menuBar.noteAdd.setVisible(true);
2109         
2110         List<QTreeWidgetItem> selections = trashTree.selectedItems();
2111         if (selections.size() == 0) {
2112                 currentNoteGuid = trashNoteGuid;
2113                         trashNoteGuid = tempGuid;
2114                 Global.showDeleted = false;
2115                 menuBar.noteRestoreAction.setEnabled(false);
2116                 menuBar.noteRestoreAction.setVisible(false);
2117         }
2118         else {
2119                 currentNoteGuid = trashNoteGuid;
2120                         trashNoteGuid = tempGuid;
2121                 menuBar.noteRestoreAction.setEnabled(true);
2122                 menuBar.noteRestoreAction.setVisible(true);
2123                 Global.showDeleted = true;
2124         }
2125         listManager.loadNotesIndex();
2126         noteIndexUpdated(false);
2127 ////            browserWindow.setEnabled(newButton.isEnabled());
2128         browserWindow.setReadOnly(!newButton.isEnabled());
2129         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2130     }
2131     // Empty the trash file
2132     @SuppressWarnings("unused")
2133         private void emptyTrash() {
2134 //      browserWindow.clear();
2135         listManager.emptyTrash();
2136         if (trashTree.selectedItems().size() > 0) {
2137                 listManager.getSelectedNotebooks().clear();
2138                 listManager.getSelectedTags().clear();
2139                 listManager.setSelectedSavedSearch("");
2140                 newButton.setEnabled(!newButton.isEnabled());
2141                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2142                 menuBar.noteAdd.setVisible(true);
2143                 browserWindow.clear();
2144                 
2145                 clearTagFilter();
2146                 clearNotebookFilter();
2147                 clearSavedSearchFilter();
2148                 clearAttributeFilter();
2149                         
2150                 Global.showDeleted = false;
2151                 menuBar.noteRestoreAction.setEnabled(false);
2152                 menuBar.noteRestoreAction.setVisible(false);
2153                 
2154                 listManager.loadNotesIndex();
2155 //--->>>                noteIndexUpdated(true);
2156                 noteIndexUpdated(false);
2157         }       
2158    }
2159     // Show/Hide trash window
2160         private void toggleTrashWindow() {
2161                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2162         if (trashTree.isVisible())
2163                 trashTree.hide();
2164         else
2165                 trashTree.show();
2166         menuBar.hideTrash.setChecked(trashTree.isVisible());
2167         
2168                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2169         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2170     }    
2171         private void clearTrashFilter() {
2172                 Global.showDeleted = false;
2173         newButton.setEnabled(true);
2174         menuBar.noteAdd.setEnabled(true);
2175         menuBar.noteAdd.setVisible(true);
2176                 trashTree.blockSignals(true);
2177                 trashTree.clearSelection();
2178                 trashTree.blockSignals(false);
2179                 
2180         }
2181     
2182    
2183     //***************************************************************
2184     //***************************************************************
2185     //** These functions deal with connection settings
2186     //***************************************************************
2187     //***************************************************************
2188         // SyncRunner had a problem and things are disconnected
2189         @SuppressWarnings("unused")
2190         private void remoteErrorDisconnect() {
2191                 menuBar.connectAction.setText("Connect");
2192                 menuBar.connectAction.setToolTip("Connect to Evernote");
2193                 menuBar.synchronizeAction.setEnabled(false);
2194                 synchronizeAnimationTimer.stop();
2195                 return;
2196         }
2197         // Do a manual connect/disconnect
2198     private void remoteConnect() {
2199         logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2200
2201         if (Global.isConnected) {
2202                 Global.isConnected = false;
2203                 syncRunner.enDisconnect();
2204                 setupConnectMenuOptions();
2205                 setupOnlineMenu();
2206                 return;
2207         }
2208         
2209         AESEncrypter aes = new AESEncrypter();
2210         try {
2211                         aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
2212                 } catch (FileNotFoundException e) {
2213                         // File not found, so we'll just get empty strings anyway. 
2214                 }
2215                 String userid = aes.getUserid();
2216                 String password = aes.getPassword();
2217                 if (!userid.equals("") && !password.equals("")) {
2218                 Global.username = userid;
2219                 Global.password = password;
2220                 }               
2221
2222         // Show the login dialog box
2223                 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
2224                         LoginDialog login = new LoginDialog();
2225                         login.exec();
2226                 
2227                         if (!login.okPressed()) {
2228                                 return;
2229                         }
2230         
2231                         Global.username = login.getUserid();
2232                         Global.password = login.getPassword();
2233                 }
2234                 syncRunner.username = Global.username;
2235                 syncRunner.password = Global.password;
2236                 syncRunner.userStoreUrl = Global.userStoreUrl;
2237                 syncRunner.noteStoreUrl = Global.noteStoreUrl;
2238                 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
2239                 syncRunner.enConnect();
2240                 Global.isConnected = syncRunner.isConnected;
2241                 setupOnlineMenu();
2242                 setupConnectMenuOptions();
2243                 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
2244     }
2245     private void setupConnectMenuOptions() {
2246         logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
2247                 if (!Global.isConnected) {
2248                         menuBar.connectAction.setText("Connect");
2249                         menuBar.connectAction.setToolTip("Connect to Evernote");
2250                         menuBar.synchronizeAction.setEnabled(false);
2251                 } else {
2252                         menuBar.connectAction.setText("Disconnect");
2253                         menuBar.connectAction.setToolTip("Disconnect from Evernote");
2254                         menuBar.synchronizeAction.setEnabled(true);
2255                 }
2256                 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
2257     }
2258     
2259     
2260     
2261     //***************************************************************
2262     //***************************************************************
2263     //** These functions deal with the GUI Attribute tree
2264     //***************************************************************
2265     //***************************************************************    
2266     @SuppressWarnings("unused")
2267         private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
2268         
2269         clearTagFilter();
2270         clearNotebookFilter();
2271         clearTrashFilter();
2272         clearSavedSearchFilter();
2273
2274         if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
2275                 if (item.childCount() > 0) {
2276                         item.setSelected(false);
2277                 } else {
2278                 Global.createdBeforeFilter.reset();
2279                 Global.createdSinceFilter.reset();
2280                 Global.changedBeforeFilter.reset();
2281                 Global.changedSinceFilter.reset();
2282                 Global.containsFilter.reset();
2283                         attributeTreeSelected = item;
2284                         DateAttributeFilterTable f = null;
2285                         f = findDateAttributeFilterTable(item.parent());
2286                         if (f!=null)
2287                                 f.select(item.text(0));
2288                         else {
2289                                 String text = item.text(0);
2290                                 Global.containsFilter.select(text);
2291                         }
2292                 }
2293                 listManager.loadNotesIndex();
2294                 noteIndexUpdated(false);
2295                 return;
2296         }
2297                 attributeTreeSelected = null;
2298                 item.setSelected(false);
2299         Global.createdBeforeFilter.reset();
2300         Global.createdSinceFilter.reset();
2301         Global.changedBeforeFilter.reset();
2302         Global.changedSinceFilter.reset();
2303         Global.containsFilter.reset();
2304         listManager.loadNotesIndex();
2305                 noteIndexUpdated(false); 
2306     }
2307     // This determines what attribute filter we need, depending upon the selection
2308     private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
2309                 if (w.parent() != null && w.childCount() > 0) {
2310                         QTreeWidgetItem parent = w.parent();
2311                         if (parent.text(0).equalsIgnoreCase("created") && 
2312                                 w.text(0).equalsIgnoreCase("since"))
2313                                         return Global.createdSinceFilter;
2314                         if (parent.text(0).equalsIgnoreCase("created") && 
2315                         w.text(0).equalsIgnoreCase("before"))
2316                                         return Global.createdBeforeFilter;
2317                         if (parent.text(0).equalsIgnoreCase("last modified") && 
2318                         w.text(0).equalsIgnoreCase("since"))
2319                                         return Global.changedSinceFilter;
2320                 if (parent.text(0).equalsIgnoreCase("last modified") && 
2321                         w.text(0).equalsIgnoreCase("before"))
2322                                                 return Global.changedBeforeFilter;
2323                 }
2324                 return null;
2325     }
2326     // Show/Hide attribute search window
2327         private void toggleAttributesWindow() {
2328                 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
2329         if (attributeTree.isVisible())
2330                 attributeTree.hide();
2331         else
2332                 attributeTree.show();
2333         menuBar.hideAttributes.setChecked(attributeTree.isVisible());
2334         
2335                 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
2336         logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
2337     }    
2338         private void clearAttributeFilter() {
2339         Global.createdBeforeFilter.reset();
2340         Global.createdSinceFilter.reset();
2341         Global.changedBeforeFilter.reset();
2342         Global.changedSinceFilter.reset();
2343         Global.containsFilter.reset();
2344         attributeTreeSelected = null;
2345                 attributeTree.blockSignals(true);
2346                 attributeTree.clearSelection();
2347                 attributeTree.blockSignals(false);
2348         }
2349     
2350         
2351     //***************************************************************
2352     //***************************************************************
2353     //** These functions deal with the GUI Note index table
2354     //***************************************************************
2355     //***************************************************************    
2356     // Initialize the note list table
2357         private void initializeNoteTable() {
2358                 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
2359                 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
2360                 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
2361                 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
2362         }       
2363     // Show/Hide trash window
2364         @SuppressWarnings("unused")
2365         private void toggleNoteListWindow() {
2366                 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
2367         if (noteTableView.isVisible())
2368                 noteTableView.hide();
2369         else
2370                 noteTableView.show();
2371         menuBar.hideNoteList.setChecked(noteTableView.isVisible());
2372         
2373                 Global.saveWindowVisible("noteList", noteTableView.isVisible());
2374         logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
2375     }   
2376         // Handle the event that a user selects a note from the table
2377     @SuppressWarnings("unused")
2378         private void noteTableSelection() {
2379                 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
2380                 saveNote();
2381                 if (historyGuids.size() == 0) {
2382                         historyGuids.add(currentNoteGuid);
2383                         historyPosition = 1;
2384                 }
2385         noteTableView.showColumn(Global.noteTableGuidPosition);
2386         
2387         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2388         noteTableView.hideColumn(Global.noteTableGuidPosition);
2389         
2390         if (selections.size() > 0) {
2391                 QModelIndex index;
2392                 menuBar.noteDuplicateAction.setEnabled(true);
2393                 menuBar.noteOnlineHistoryAction.setEnabled(true);
2394                 menuBar.noteMergeAction.setEnabled(true);
2395                 selectedNoteGUIDs.clear();
2396                 if (selections.size() != 1 || Global.showDeleted) {
2397                         menuBar.noteDuplicateAction.setEnabled(false);
2398                 }
2399                 if (selections.size() != 1 || !Global.isConnected) {
2400                         menuBar.noteOnlineHistoryAction.setEnabled(false);
2401                 }
2402                 if (selections.size() == 1) {
2403                         menuBar.noteMergeAction.setEnabled(false);
2404                 }
2405                 for (int i=0; i<selections.size(); i++) {
2406                         int row = selections.get(i).row();
2407                         if (row == 0) 
2408                                 upButton.setEnabled(false);
2409                         else
2410                                 upButton.setEnabled(true);
2411                         if (row < listManager.getNoteTableModel().rowCount()-1)
2412                                 downButton.setEnabled(true);
2413                         else
2414                                 downButton.setEnabled(false);
2415                         index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
2416                         SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
2417                         currentNoteGuid = (String)ix.values().toArray()[0];
2418                         selectedNoteGUIDs.add(currentNoteGuid);
2419                 }
2420         }
2421         
2422         nextButton.setEnabled(true);
2423                 prevButton.setEnabled(true);
2424         if (!fromHistory) {
2425                 int endPosition = historyGuids.size()-1;
2426                 for (int j=historyPosition; j<=endPosition; j++) {
2427                         historyGuids.remove(historyGuids.size()-1);
2428                 }
2429                 historyGuids.add(currentNoteGuid);
2430                 historyPosition = historyGuids.size();
2431         } 
2432         if (historyPosition <= 1)
2433                 prevButton.setEnabled(false);
2434         if (historyPosition == historyGuids.size())
2435                 nextButton.setEnabled(false);
2436                 
2437         fromHistory = false;
2438         scrollToGuid(currentNoteGuid);
2439         refreshEvernoteNote(true);
2440                 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
2441     }    
2442         // Trigger a refresh when the note db has been updated
2443         private void noteIndexUpdated(boolean reload) {
2444                 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
2445                 saveNote();
2446         refreshEvernoteNoteList();
2447         logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
2448         noteTableView.load(reload);
2449         scrollToGuid(currentNoteGuid);
2450                 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
2451     }
2452         // Called when the list of notes is updated
2453     private void refreshEvernoteNoteList() {
2454         logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
2455         browserWindow.setDisabled(false);
2456                 if (selectedNoteGUIDs == null)
2457                         selectedNoteGUIDs = new ArrayList<String>();
2458                 selectedNoteGUIDs.clear();  // clear out old entries
2459                 
2460                 String saveCurrentNoteGuid = new String();
2461                 String tempNoteGuid = new String();
2462                                 
2463                 historyGuids.clear();
2464                 historyPosition = 0;
2465                 prevButton.setEnabled(false);
2466                 nextButton.setEnabled(false);
2467                 
2468                 if (currentNoteGuid == null) 
2469                         currentNoteGuid = new String();
2470                 
2471                 for (Note note : listManager.getNoteIndex()) {
2472                         tempNoteGuid = note.getGuid();
2473                         if (currentNoteGuid.equals(tempNoteGuid)) {
2474                                 saveCurrentNoteGuid = new String(tempNoteGuid);
2475                         }
2476                 }
2477                 
2478                 if (listManager.getNoteIndex().size() == 0) {
2479                         currentNoteGuid = "";
2480                         currentNote = null;
2481                         browserWindow.clear();
2482                         browserWindow.setDisabled(true);
2483                 } 
2484                 
2485                 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() >0) {
2486                         currentNoteGuid = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1).getGuid();
2487                         currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
2488                         refreshEvernoteNote(true);
2489                 } else {
2490                         refreshEvernoteNote(false);
2491                 }
2492                 reloadTagTree();
2493
2494                 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
2495         } 
2496     // Called when the previous arrow button is clicked 
2497     @SuppressWarnings("unused")
2498         private void previousViewedAction() {
2499         if (!prevButton.isEnabled())
2500                 return;
2501         if (historyPosition == 0)
2502                 return;
2503                 historyPosition--;
2504         if (historyPosition <= 0)
2505                 return;
2506         String historyGuid = historyGuids.get(historyPosition-1);
2507         fromHistory = true;
2508         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2509                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
2510                 if (modelIndex != null) {
2511                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2512                         String tableGuid =  (String)ix.values().toArray()[0];
2513                         if (tableGuid.equals(historyGuid)) {
2514                                 noteTableView.selectRow(i);
2515                                 return;
2516                         }       
2517                 }
2518         }
2519     }
2520     @SuppressWarnings("unused")
2521         private void nextViewedAction() {
2522         if (!nextButton.isEnabled())
2523                 return;
2524         String historyGuid = historyGuids.get(historyPosition);
2525         historyPosition++;
2526         fromHistory = true;
2527         for (int i=0; i<noteTableView.model().rowCount(); i++) {
2528                 QModelIndex modelIndex =  noteTableView.model().index(i, Global.noteTableGuidPosition);
2529                 if (modelIndex != null) {
2530                         SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2531                         String tableGuid =  (String)ix.values().toArray()[0];
2532                         if (tableGuid.equals(historyGuid)) {
2533                                 noteTableView.selectRow(i);
2534                                 return;
2535                         }       
2536                 }
2537         }       
2538     }
2539     // Called when the up arrow is clicked 
2540     @SuppressWarnings("unused")
2541         private void upAction() {
2542         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2543         int row = selections.get(0).row();
2544         if (row > 0) {
2545                 noteTableView.selectRow(row-1);
2546         }
2547     }
2548     // Called when the down arrow is clicked 
2549     @SuppressWarnings("unused")
2550         private void downAction() {
2551         List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2552         int row = selections.get(0).row();
2553         int max = listManager.getNoteTableModel().rowCount();
2554         if (row < max-1) {
2555                 noteTableView.selectRow(row+1);
2556         }
2557     }
2558     // Update a tag string for a specific note in the list
2559     @SuppressWarnings("unused")
2560         private void updateListTags(String guid, List<String> tags) {
2561         logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
2562         StringBuffer tagBuffer = new StringBuffer();
2563         for (int i=0; i<tags.size(); i++) {
2564                 tagBuffer.append(tags.get(i));
2565                 if (i<tags.size()-1)
2566                         tagBuffer.append(", ");
2567         }
2568         
2569         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2570                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2571                 if (modelIndex != null) {
2572                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2573                         String tableGuid =  (String)ix.values().toArray()[0];
2574                         if (tableGuid.equals(guid)) {
2575                                 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
2576                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2577                                 return;
2578                         }
2579                 }
2580         }
2581         logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
2582     }
2583     // Update a title for a specific note in the list
2584     @SuppressWarnings("unused")
2585         private void updateListAuthor(String guid, String author) {
2586         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2587
2588         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2589                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2590                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2591                 if (modelIndex != null) {
2592 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2593                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2594                         String tableGuid =  (String)ix.values().toArray()[0];
2595                         if (tableGuid.equals(guid)) {
2596                                 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
2597                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2598                                 return;
2599                         }       
2600                 }
2601         }
2602         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2603     }
2604         private void updateListNoteNotebook(String guid, String notebook) {
2605         logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
2606         listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
2607         logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
2608     }
2609     // Update a title for a specific note in the list
2610     @SuppressWarnings("unused")
2611         private void updateListSourceUrl(String guid, String url) {
2612         logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2613
2614         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2615                 //QModelIndex modelIndex =  noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2616                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2617                 if (modelIndex != null) {
2618 //                      SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2619                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2620                         String tableGuid =  (String)ix.values().toArray()[0];
2621                         if (tableGuid.equals(guid)) {
2622                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2623                                 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
2624                                 return;
2625                         }       
2626                 }
2627         }
2628         logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2629     }
2630         private void updateListGuid(String oldGuid, String newGuid) {
2631         logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2632
2633         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2634                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2635                 if (modelIndex != null) {
2636                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2637                         String tableGuid =  (String)ix.values().toArray()[0];
2638                         if (tableGuid.equals(oldGuid)) {
2639                                 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
2640                                 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2641                                 return;
2642                         }       
2643                 }
2644         }
2645         logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2646     }
2647         private void updateListTagName(String guid) {
2648         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2649                 
2650                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2651                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2652                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2653
2654                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2655                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2656                                         if (modelIndex != null) {
2657                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2658                                                 String noteGuid = (String)ix.values().toArray()[0];
2659                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2660                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2661                                                         //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2662                                                         i=listManager.getNoteTableModel().rowCount();
2663                                                 }
2664                                         }
2665                                 }
2666                         }
2667                 }       
2668         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2669     }
2670         private void removeListTagName(String guid) {
2671         logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2672                 
2673                 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2674                         if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2675                                 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
2676                                         if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
2677                                                 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
2678                                 }
2679                                 
2680                                 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2681                                 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2682                                         QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2683                                         if (modelIndex != null) {
2684                                                 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2685                                                 String noteGuid = (String)ix.values().toArray()[0];
2686                                                 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2687                                                         listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2688 //                                                      listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2689                                                         i=listManager.getNoteTableModel().rowCount();
2690                                                 }
2691                                         }
2692                                 }
2693                         }
2694                 }       
2695         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2696     }
2697     private void updateListNotebookName(String oldName, String newName) {
2698         logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
2699
2700         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2701                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition); 
2702                 if (modelIndex != null) {
2703                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2704                         String tableName =  (String)ix.values().toArray()[0];
2705                         if (tableName.equalsIgnoreCase(oldName)) {
2706 //                              listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2707                                 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
2708                         }
2709                 }
2710         }
2711         logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
2712     }
2713     @SuppressWarnings("unused")
2714         private void updateListDateCreated(String guid, QDateTime date) {
2715         logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
2716
2717         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2718                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2719                 if (modelIndex != null) {
2720                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2721                         String tableGuid =  (String)ix.values().toArray()[0];
2722                         if (tableGuid.equals(guid)) {
2723                                 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2724                                 return;
2725                         }
2726                 }
2727         }
2728         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2729     }
2730     @SuppressWarnings("unused")
2731         private void updateListDateSubject(String guid, QDateTime date) {
2732         logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
2733
2734         for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2735                 QModelIndex modelIndex =  listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2736                 if (modelIndex != null) {
2737                         SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2738                         String tableGuid =  (String)ix.values().toArray()[0];
2739                         if (tableGuid.equals(guid)) {
2740                                 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2741                                 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2742                                 return;
2743                         }
2744                 }
2745         }
2746         logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");