OSDN Git Service

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