OSDN Git Service

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