OSDN Git Service

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