OSDN Git Service

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