OSDN Git Service

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