OSDN Git Service

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