OSDN Git Service

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