OSDN Git Service

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