OSDN Git Service

Cleanup selection behavior on tag & notebook trees.
[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                         indexRunner.thread().join(50);
956                         logger.log(logger.MEDIUM, "Index thread has stopped");
957                 } catch (InterruptedException e1) {
958                         e1.printStackTrace();
959                 }
960                 if (!syncRunner.isIdle()) {
961                         try {
962                                 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
963                                 syncThread.join();
964                                 logger.log(logger.MEDIUM, "Sync thread has stopped");
965                         } catch (InterruptedException e1) {
966                                 e1.printStackTrace();
967                         }
968                 }
969
970                 if (encryptOnShutdown) {
971                         encryptOnShutdown();
972                 }
973                 if (decryptOnShutdown) {
974                         decryptOnShutdown();
975                 }
976                 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
977         }
978
979         @SuppressWarnings("unused")
980         private void closeNeverNote() {
981                 closeAction = true;
982                 close();
983         }
984         public void setMessage(String s) {
985                 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
986                 logger.log(logger.HIGH, "Message: " +s);
987                 statusBar.showMessage(s);
988                 emitLog.add(s);
989                 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
990         }
991                 
992         private void waitCursor(boolean wait) {
993                 if (wait) {
994                         if (QApplication.overrideCursor() == null)
995                                 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
996                 }
997                 else {
998                         while (QApplication.overrideCursor() != null)
999                                 QApplication.restoreOverrideCursor();
1000                 }
1001         }
1002         
1003         private void setupIndexListeners() {
1004 //              indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1005 //              indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1006                 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1007                 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1008         }
1009         private void setupSyncSignalListeners() {
1010                 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1011         syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1012         syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1013         syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1014         syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1015         
1016                 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1017                 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1018                 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1019                 
1020                 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1021                 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1022                 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1023                 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1024                 
1025                 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1026         }
1027         
1028         private void setupBrowserSignalListeners() {
1029                 setupBrowserWindowListeners(browserWindow, true);
1030         }
1031
1032         private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1033                 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1034                 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1035             browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1036             if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1037             browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1038             browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1039             browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1040             browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1041             browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1042             browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1043             browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1044             browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1045             browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1046             browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1047             if (master) browser.focusLost.connect(this, "saveNote()");
1048             browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1049         }
1050
1051         //***************************************************************
1052         //***************************************************************
1053         //* Settings and look & feel
1054         //***************************************************************
1055         //***************************************************************
1056         @SuppressWarnings("unused")
1057         private void settings() {
1058                 logger.log(logger.HIGH, "Entering NeverNote.settings");
1059                 saveNoteColumnPositions();
1060                 saveNoteIndexWidth();
1061                 showColumns();
1062         ConfigDialog settings = new ConfigDialog(this);
1063         String dateFormat = Global.getDateFormat();
1064         String timeFormat = Global.getTimeFormat();
1065         
1066                 indexTime = 1000*Global.getIndexThreadSleepInterval();  
1067                 indexTimer.start(indexTime);  // reset indexing timer
1068         
1069         settings.exec();
1070         indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1071         if (Global.showTrayIcon())
1072                 trayIcon.show();
1073         else
1074                 trayIcon.hide();
1075         showColumns();
1076         if (menuBar.showEditorBar.isChecked())
1077                 showEditorButtons(browserWindow);
1078         
1079         // Reset the save timer
1080         if (Global.getAutoSaveInterval() > 0)
1081                         saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1082         else
1083                 saveTimer.stop();
1084         
1085         // This is a hack to force a reload of the index in case the date or time changed.
1086 //        if (!dateFormat.equals(Global.getDateFormat()) ||
1087 //                      !timeFormat.equals(Global.getTimeFormat())) {
1088                 noteCache.clear();
1089                 readOnlyCache.clear();
1090                 inkNoteCache.clear();
1091                 noteIndexUpdated(true);
1092 //        }
1093         
1094         logger.log(logger.HIGH, "Leaving NeverNote.settings");
1095         }
1096         // Restore things to the way they were
1097         private void restoreWindowState(boolean mainWindow) {
1098                 // We need to name things or this doesn't work.
1099                 setObjectName("NeverNote");
1100                 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1101                 browserIndexSplitter.setObjectName("browserIndexSplitter");
1102                 leftSplitter1.setObjectName("leftSplitter1");   
1103                 
1104                 // Restore the actual positions.
1105                 if (mainWindow)
1106                         restoreGeometry(Global.restoreGeometry(objectName()));
1107         mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1108         browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1109         leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1110        
1111         }
1112         // Save window positions for the next start
1113         private void saveWindowState() {
1114                 Global.saveGeometry(objectName(), saveGeometry());
1115                 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1116                 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1117                 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1118         }    
1119         // Load the style sheet
1120         private void loadStyleSheet() {
1121                 String fileName = Global.getFileManager().getQssDirPath("default.qss");
1122                 QFile file = new QFile(fileName);
1123                 file.open(OpenModeFlag.ReadOnly);
1124                 String styleSheet = file.readAll().toString();
1125                 file.close();
1126                 setStyleSheet(styleSheet);
1127         }
1128         // Save column positions for the next time
1129         private void saveNoteColumnPositions() {
1130                 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1131                 Global.setColumnPosition("noteTableCreationPosition", position);
1132                 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1133                 Global.setColumnPosition("noteTableTagPosition", position);
1134                 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1135                 Global.setColumnPosition("noteTableNotebookPosition", position);
1136                 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1137                 Global.setColumnPosition("noteTableChangedPosition", position);
1138                 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1139                 Global.setColumnPosition("noteTableAuthorPosition", position);
1140                 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1141                 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1142                 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1143                 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1144                 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1145                 Global.setColumnPosition("noteTableTitlePosition", position);
1146                 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1147                 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1148                 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1149                 Global.setColumnPosition("noteTableGuidPosition", position);
1150                 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1151                 Global.setColumnPosition("noteTableThumbnailPosition", position);
1152
1153         }
1154         // Save column widths for the next time
1155         private void saveNoteIndexWidth() {
1156                 int width;
1157         width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1158         Global.setColumnWidth("noteTableCreationPosition", width);
1159                 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1160                 Global.setColumnWidth("noteTableChangedPosition", width);
1161                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1162                 Global.setColumnWidth("noteTableGuidPosition", width);
1163                 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1164                 Global.setColumnWidth("noteTableNotebookPosition", width);
1165                 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1166                 Global.setColumnWidth("noteTableTagPosition", width);
1167                 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1168                 Global.setColumnWidth("noteTableTitlePosition", width);
1169                 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1170                 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1171                 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1172                 Global.setColumnWidth("noteTableAuthorPosition", width);
1173                 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1174                 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1175                 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1176                 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1177                 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1178                 Global.setColumnWidth("noteTableThumbnailPosition", width);
1179                 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1180                 Global.setColumnWidth("noteTableGuidPosition", width);
1181         }
1182         
1183         
1184     //***************************************************************
1185     //***************************************************************
1186     //** These functions deal with Notebook menu items
1187     //***************************************************************
1188     //***************************************************************
1189     // Setup the tree containing the user's notebooks.
1190     private void initializeNotebookTree() {       
1191         logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1192 //      notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1193         notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1194         listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1195         logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1196     }   
1197     // Listener when a notebook is selected
1198         private void notebookTreeSelection() {
1199                 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1200
1201                 clearTrashFilter();
1202                 clearAttributeFilter();
1203                 clearSavedSearchFilter();
1204                 if (Global.mimicEvernoteInterface) {
1205                         clearTagFilter();
1206                         searchField.clear();
1207                 }
1208                 menuBar.noteRestoreAction.setVisible(false);            
1209         menuBar.notebookEditAction.setEnabled(true);
1210         menuBar.notebookDeleteAction.setEnabled(true);
1211         menuBar.notebookPublishAction.setEnabled(true);
1212         menuBar.notebookShareAction.setEnabled(true);
1213         menuBar.notebookIconAction.setEnabled(true);
1214         menuBar.notebookStackAction.setEnabled(true);
1215         List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1216         selectedNotebookGUIDs.clear();
1217                 String guid = "";
1218                 String stackName = "";
1219                 if (selections.size() > 0) {
1220                 guid = (selections.get(0).text(2));
1221                 stackName = selections.get(0).text(0);
1222         }
1223         if (!guid.equals("") && !guid.equals("STACK")) {
1224                 selectedNotebookGUIDs.add(guid);
1225                 menuBar.notebookIconAction.setEnabled(true);
1226         }
1227         else {
1228                 menuBar.notebookIconAction.setEnabled(true);
1229                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1230                                 Notebook book = listManager.getNotebookIndex().get(j);
1231                                 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1232                                         selectedNotebookGUIDs.add(book.getGuid());
1233                         }
1234         }
1235         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1236         listManager.loadNotesIndex();
1237         noteIndexUpdated(false);
1238                 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1239
1240     }
1241     private void clearNotebookFilter() {
1242         notebookTree.blockSignals(true);
1243         notebookTree.clearSelection();
1244                 menuBar.noteRestoreAction.setVisible(false);
1245         menuBar.notebookEditAction.setEnabled(false);
1246         menuBar.notebookDeleteAction.setEnabled(false);
1247         selectedNotebookGUIDs.clear();
1248         listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1249         notebookTree.blockSignals(false);
1250     }
1251         // Triggered when the notebook DB has been updated
1252         private void notebookIndexUpdated() {
1253                 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1254         
1255                 // Get the possible icons
1256                 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1257         notebookTree.setIcons(icons);
1258         
1259         if (selectedNotebookGUIDs == null)
1260                         selectedNotebookGUIDs = new ArrayList<String>();
1261                 List<Notebook> books = conn.getNotebookTable().getAll();
1262                 for (int i=books.size()-1; i>=0; i--) {
1263                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1264                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1265                                         books.remove(i);
1266                                         j=listManager.getArchiveNotebookIndex().size();
1267                                 }
1268                         }
1269                 }
1270                 
1271                 
1272                 listManager.countNotebookResults(listManager.getNoteIndex());
1273                 notebookTree.blockSignals(true);
1274         notebookTree.load(books, listManager.getLocalNotebooks());
1275         for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1276                 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1277                 if (!found)
1278                         selectedNotebookGUIDs.remove(i);
1279         }
1280         notebookTree.blockSignals(false);
1281         
1282                 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1283     }
1284     // Show/Hide note information
1285         private void toggleNotebookWindow() {
1286                 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1287         if (notebookTree.isVisible())
1288                 notebookTree.hide();
1289         else
1290                 notebookTree.show();
1291         menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1292         Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1293         logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1294     }   
1295         // Add a new notebook
1296         @SuppressWarnings("unused")
1297         private void addNotebook() {
1298                 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1299                 NotebookEdit edit = new NotebookEdit();
1300                 edit.setNotebooks(listManager.getNotebookIndex());
1301                 edit.exec();
1302         
1303                 if (!edit.okPressed())
1304                         return;
1305         
1306                 Calendar currentTime = new GregorianCalendar();
1307                 Long l = new Long(currentTime.getTimeInMillis());
1308                 String randint = new String(Long.toString(l));
1309         
1310                 Notebook newBook = new Notebook();
1311                 newBook.setUpdateSequenceNum(0);
1312                 newBook.setGuid(randint);
1313                 newBook.setName(edit.getNotebook());
1314                 newBook.setServiceCreated(new Date().getTime());
1315                 newBook.setServiceUpdated(new Date().getTime());
1316                 newBook.setDefaultNotebook(false);
1317                 newBook.setPublished(false);
1318                 
1319                 listManager.getNotebookIndex().add(newBook);
1320                 if (edit.isLocal())
1321                         listManager.getLocalNotebooks().add(newBook.getGuid());
1322                 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1323                 notebookIndexUpdated();
1324                 listManager.countNotebookResults(listManager.getNoteIndex());
1325 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1326                 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1327         }
1328         // Edit an existing notebook
1329         @SuppressWarnings("unused")
1330         private void stackNotebook() {
1331                 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1332                 StackNotebook edit = new StackNotebook();
1333                 
1334                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1335                 QTreeWidgetItem currentSelection;
1336                 for (int i=0; i<selections.size(); i++) {
1337                         currentSelection = selections.get(0);
1338                         String guid = currentSelection.text(2);
1339                         if (guid.equalsIgnoreCase("")) {
1340                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1341                                  return;
1342                         }
1343                         if (guid.equalsIgnoreCase("STACK")) {
1344                                  QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1345                                  return;
1346                         }
1347                 }
1348
1349                 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1350
1351                 
1352                 edit.exec();
1353         
1354                 if (!edit.okPressed())
1355                         return;
1356         
1357                 String stack = edit.getStackName();
1358                 
1359                 for (int i=0; i<selections.size(); i++) {
1360                         currentSelection = selections.get(i);
1361                         String guid = currentSelection.text(2);
1362                         listManager.updateNotebookStack(guid, stack);
1363                 }
1364                 notebookIndexUpdated();
1365                 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1366         }
1367         // Edit an existing notebook
1368         @SuppressWarnings("unused")
1369         private void editNotebook() {
1370                 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1371                 NotebookEdit edit = new NotebookEdit();
1372                 
1373                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1374                 QTreeWidgetItem currentSelection;
1375                 currentSelection = selections.get(0);
1376                 edit.setNotebook(currentSelection.text(0));
1377                 
1378                 String guid = currentSelection.text(2);
1379                 if (!guid.equalsIgnoreCase("STACK")) {
1380                         edit.setTitle(tr("Edit Notebook"));
1381                         edit.setNotebooks(listManager.getNotebookIndex());
1382                         edit.setLocalCheckboxEnabled(false);
1383                         for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1384                                 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1385                                         edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1386                                         i=listManager.getNotebookIndex().size();
1387                                 }
1388                         }
1389                 } else {
1390                         edit.setTitle(tr("Edit Stack"));
1391                         edit.setStacks(conn.getNotebookTable().getAllStackNames());
1392                         edit.hideLocalCheckbox();
1393                         edit.hideDefaultCheckbox();
1394                 }
1395                 
1396                 edit.exec();
1397         
1398                 if (!edit.okPressed())
1399                         return;
1400         
1401                 
1402                 if (guid.equalsIgnoreCase("STACK")) {
1403                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1404                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1405                                 if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1406                                                 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1407                         }
1408                         conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1409                         currentSelection.setText(0, edit.getNotebook());
1410                         return;
1411                 }
1412                 
1413                 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1414                 currentSelection.setText(0, edit.getNotebook());
1415                 
1416                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1417                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1418                                 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1419                                 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1420                                         for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1421                                                 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1422                                         listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1423                                         conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1424                                 }
1425                                 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1426                                 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1427                                         LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1428                                         linkedNotebook.setShareName(edit.getNotebook());
1429                                         conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1430                                 }
1431                                 i=listManager.getNotebookIndex().size();
1432                         }
1433                 }
1434                 
1435                 // Build a list of non-closed notebooks
1436                 List<Notebook> nbooks = new ArrayList<Notebook>();
1437                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1438                         boolean found=false;
1439                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1440                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1441                                         found = true;
1442                         }
1443                         if (!found)
1444                                 nbooks.add(listManager.getNotebookIndex().get(i));
1445                 }
1446                 
1447                 browserWindow.setNotebookList(nbooks);
1448                 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1449         }
1450         // Publish a notebook
1451         @SuppressWarnings("unused")
1452         private void publishNotebook() {
1453                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1454                 QTreeWidgetItem currentSelection;
1455                 currentSelection = selections.get(0);
1456                 String guid = currentSelection.text(2);
1457
1458                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1459                         return;
1460                 
1461                 Notebook n = null;
1462                 int position = 0;
1463                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1464                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1465                                 n = listManager.getNotebookIndex().get(i);
1466                                 position = i;
1467                                 i = listManager.getNotebookIndex().size();
1468                         }
1469                 }
1470                 if (n == null)
1471                         return;
1472                 
1473                 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1474                 publish.exec();
1475                 
1476                 if (!publish.okClicked()) 
1477                         return;
1478                 
1479                 Publishing p = publish.getPublishing();
1480                 boolean isPublished = !publish.isStopPressed();
1481                 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1482                 n.setPublished(isPublished);
1483                 n.setPublishing(p);
1484                 listManager.getNotebookIndex().set(position, n);
1485                 notebookIndexUpdated();
1486         }
1487         // Publish a notebook
1488         @SuppressWarnings("unused")
1489         private void shareNotebook() {
1490                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1491                 QTreeWidgetItem currentSelection;
1492                 currentSelection = selections.get(0);
1493                 String guid = currentSelection.text(2);
1494
1495                 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1496                         return;
1497                 
1498                 Notebook n = null;;
1499                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1500                         if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1501                                 n = listManager.getNotebookIndex().get(i);
1502                                 i = listManager.getNotebookIndex().size();
1503                         }
1504                 }
1505                                 
1506                 String authToken = null;
1507                 if (syncRunner.isConnected)
1508                         authToken = syncRunner.authToken;
1509                 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1510                 share.exec();
1511                 
1512         }
1513
1514         // Delete an existing notebook
1515         @SuppressWarnings("unused")
1516         private void deleteNotebook() {
1517                 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1518                 boolean stacksFound = false;
1519                 boolean notebooksFound = false;
1520                 boolean assigned = false;
1521                 // Check if any notes have this notebook
1522                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1523         for (int i=0; i<selections.size(); i++) {
1524                 QTreeWidgetItem currentSelection;
1525                 currentSelection = selections.get(i);
1526                 String guid = currentSelection.text(2);
1527                 if (!guid.equalsIgnoreCase("STACK")) {
1528                         notebooksFound = true;
1529                         for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1530                                 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1531                                 if (noteGuid.equals(guid)) {
1532                                         assigned = true;
1533                                         j=listManager.getNoteIndex().size();
1534                                         i=selections.size();
1535                                 }
1536                         }
1537                 } else {
1538                         stacksFound = true;
1539                 }
1540         }
1541                 if (assigned) {
1542                         QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1543                                         "Please delete the notes or move them to another notebook before deleting any notebooks."));
1544                         return;
1545                 }
1546                 
1547                 if (conn.getNotebookTable().getAll().size() == 1) {
1548                         QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1549                         return;
1550                 }
1551         
1552         // If all notebooks are clear, verify the delete
1553                 String msg1 = new String(tr("Delete selected notebooks?"));
1554                 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1555                 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1556                                 " not deleted unless selected?"));
1557                 String msg = "";
1558                 if (stacksFound && notebooksFound)
1559                         msg = msg3;
1560                 if (!stacksFound && notebooksFound)
1561                         msg = msg1;
1562                 if (stacksFound && !notebooksFound)
1563                         msg = msg2;
1564                 if (QMessageBox.question(this, tr("Confirmation"), msg,
1565                         QMessageBox.StandardButton.Yes, 
1566                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1567                         return;
1568                 }
1569                 
1570                 // If confirmed, delete the notebook
1571         for (int i=selections.size()-1; i>=0; i--) {
1572                 QTreeWidgetItem currentSelection;
1573                 currentSelection = selections.get(i);
1574                 String guid = currentSelection.text(2);
1575                 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1576                         conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1577                         listManager.renameStack(currentSelection.text(0), "");
1578                 } else {
1579                         conn.getNotebookTable().expungeNotebook(guid, true);
1580                         listManager.deleteNotebook(guid);
1581                 }
1582         }
1583
1584         notebookTreeSelection();
1585         notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1586         listManager.countNotebookResults(listManager.getNoteIndex());
1587         logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1588         }
1589         // A note's notebook has been updated
1590         @SuppressWarnings("unused")
1591         private void updateNoteNotebook(String guid, String notebookGuid) {
1592                 
1593                 // Update the list manager
1594                 listManager.updateNoteNotebook(guid, notebookGuid);
1595                 listManager.countNotebookResults(listManager.getNoteIndex());
1596 //              notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());    
1597                 
1598                 // Find the name of the notebook
1599                 String notebookName = null;
1600                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1601                         if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1602                                 notebookName = listManager.getNotebookIndex().get(i).getName();
1603                                 break;
1604                         }
1605                 }
1606                 
1607                 // If we found the name, update the browser window
1608                 if (notebookName != null) {
1609                         updateListNoteNotebook(guid, notebookName);
1610                         if (guid.equals(currentNoteGuid)) {
1611                                 int pos =  browserWindow.notebookBox.findText(notebookName);
1612                                 if (pos >=0)
1613                                         browserWindow.notebookBox.setCurrentIndex(pos);
1614                         }
1615                 }
1616                 
1617                 // If we're dealing with the current note, then we need to be sure and update the notebook there
1618                 if (guid.equals(currentNoteGuid)) {
1619                         if (currentNote != null) {
1620                                 currentNote.setNotebookGuid(notebookGuid);
1621                         }
1622                 }
1623         }
1624         // Open/close notebooks
1625         @SuppressWarnings("unused")
1626         private void closeNotebooks() {
1627                 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1628                 na.exec();
1629                 if (!na.okClicked())
1630                         return;
1631                 
1632                 waitCursor(true);
1633                 listManager.getArchiveNotebookIndex().clear();
1634                 
1635                 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1636                         String text = na.getClosedBookList().takeItem(i).text();
1637                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1638                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1639                                         Notebook n = listManager.getNotebookIndex().get(j);
1640                                         conn.getNotebookTable().setArchived(n.getGuid(),true);
1641                                         listManager.getArchiveNotebookIndex().add(n);
1642                                         j=listManager.getNotebookIndex().size();
1643                                 }
1644                         }
1645                 }
1646                 
1647                 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1648                         String text = na.getOpenBookList().takeItem(i).text();
1649                         for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1650                                 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1651                                         Notebook n = listManager.getNotebookIndex().get(j);
1652                                         conn.getNotebookTable().setArchived(n.getGuid(),false);
1653                                         j=listManager.getNotebookIndex().size();
1654                                 }
1655                         }
1656                 }
1657                 notebookTreeSelection();
1658                 listManager.loadNotesIndex();
1659                 notebookIndexUpdated();
1660                 noteIndexUpdated(false);
1661                 reloadTagTree(true);
1662 //              noteIndexUpdated(false);
1663                 
1664                 // Build a list of non-closed notebooks
1665                 List<Notebook> nbooks = new ArrayList<Notebook>();
1666                 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1667                         boolean found=false;
1668                         for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1669                                 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1670                                         found = true;
1671                         }
1672                         if (!found)
1673                                 nbooks.add(listManager.getNotebookIndex().get(i));
1674                 }
1675                 waitCursor(false);
1676                 browserWindow.setNotebookList(nbooks);
1677         }
1678         // Change the notebook's icon
1679         @SuppressWarnings("unused")
1680         private void setNotebookIcon() {
1681                 boolean stackSelected = false;
1682                 boolean allNotebookSelected = false;
1683                 
1684                 QTreeWidgetItem currentSelection;
1685                 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1686                 if (selections.size() == 0)
1687                         return;
1688                 
1689                 currentSelection = selections.get(0);   
1690                 String guid = currentSelection.text(2);
1691                 if (guid.equalsIgnoreCase(""))
1692                         allNotebookSelected = true;
1693                 if (guid.equalsIgnoreCase("STACK"))
1694                         stackSelected = true;
1695
1696                 QIcon currentIcon = currentSelection.icon(0);
1697                 QIcon icon;
1698                 SetIcon dialog;
1699                 
1700                 if (!stackSelected && !allNotebookSelected) {
1701                         icon = conn.getNotebookTable().getIcon(guid);
1702                         if (icon == null) {
1703                                 dialog = new SetIcon(currentIcon);
1704                                 dialog.setUseDefaultIcon(true);
1705                         } else {
1706                                 dialog = new SetIcon(icon);
1707                                 dialog.setUseDefaultIcon(false);
1708                         }
1709                 } else {
1710                         if (stackSelected) {
1711                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1712                         } else {
1713                                 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");                              
1714                         }
1715                         if (icon == null) {
1716                                 dialog = new SetIcon(currentIcon);
1717                                 dialog.setUseDefaultIcon(true);
1718                         } else {
1719                                 dialog = new SetIcon(icon);
1720                                 dialog.setUseDefaultIcon(false);
1721                         }
1722                 }
1723                 dialog.exec();
1724                 if (dialog.okPressed()) {
1725                         QIcon newIcon = dialog.getIcon();
1726                         if (stackSelected) {
1727                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1728                                 if (newIcon == null) {
1729                                         newIcon = new QIcon(iconPath+"books2.png");
1730                                 }
1731                                 currentSelection.setIcon(0,newIcon);
1732                                 return;
1733                         }
1734                         if (allNotebookSelected) {
1735                                 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1736                                 if (newIcon == null) {
1737                                         newIcon = new QIcon(iconPath+"notebook-green.png");
1738                                 }
1739                                 currentSelection.setIcon(0,newIcon);
1740                                 return;
1741                         }
1742                         conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1743                         if (newIcon == null) {
1744                                 boolean isPublished = false;;
1745                                 boolean found = false;
1746                                 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1747                                         if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1748                                                 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1749                                                 found = true;
1750                                         }
1751                                 }
1752                                 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1753                         }
1754                         currentSelection.setIcon(0, newIcon);
1755                 }
1756         
1757         }
1758         
1759         
1760     //***************************************************************
1761     //***************************************************************
1762     //** These functions deal with Tag menu items
1763     //***************************************************************
1764     //***************************************************************
1765         // Add a new notebook
1766         @SuppressWarnings("unused")
1767         private void addTag() {
1768                 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1769                 TagEdit edit = new TagEdit();
1770                 edit.setTagList(listManager.getTagIndex());
1771                 edit.exec();
1772         
1773                 if (!edit.okPressed())
1774                         return;
1775         
1776                 Calendar currentTime = new GregorianCalendar();
1777                 Long l = new Long(currentTime.getTimeInMillis());
1778                 String randint = new String(Long.toString(l));
1779         
1780                 Tag newTag = new Tag();
1781                 newTag.setUpdateSequenceNum(0);
1782                 newTag.setGuid(randint);
1783                 newTag.setName(edit.getTag());
1784                 conn.getTagTable().addTag(newTag, true);
1785                 listManager.getTagIndex().add(newTag);
1786                 reloadTagTree(true);
1787                 
1788                 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1789         }
1790         @SuppressWarnings("unused")
1791         private void reloadTagTree() {
1792                 reloadTagTree(false);
1793         }
1794         private void reloadTagTree(boolean reload) {
1795                 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1796                 tagIndexUpdated(reload);
1797                 boolean filter = false;
1798                 listManager.countTagResults(listManager.getNoteIndex());
1799                 if (notebookTree.selectedItems().size() > 0 
1800                                                   && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1801                                                   filter = true;
1802                 if (tagTree.selectedItems().size() > 0)
1803                         filter = true;
1804                 tagTree.showAllTags(!filter);
1805                 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1806         }
1807         // Edit an existing tag
1808         @SuppressWarnings("unused")
1809         private void editTag() {
1810                 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1811                 TagEdit edit = new TagEdit();
1812                 edit.setTitle("Edit Tag");
1813                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1814                 QTreeWidgetItem currentSelection;
1815                 currentSelection = selections.get(0);
1816                 edit.setTag(currentSelection.text(0));
1817                 edit.setTagList(listManager.getTagIndex());
1818                 edit.exec();
1819         
1820                 if (!edit.okPressed())
1821                         return;
1822         
1823                 String guid = currentSelection.text(2);
1824                 currentSelection.setText(0,edit.getTag());
1825                 
1826                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1827                         if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1828                                 listManager.getTagIndex().get(i).setName(edit.getTag());
1829                                 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1830                                 updateListTagName(guid);
1831                                 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1832                                         browserWindow.setTag(getTagNamesForNote(currentNote));
1833                                 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1834                                 return;
1835                         }
1836                 }
1837                 browserWindow.setTag(getTagNamesForNote(currentNote));
1838                 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1839         }
1840         // Delete an existing tag
1841         @SuppressWarnings("unused")
1842         private void deleteTag() {
1843                 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1844                 
1845                 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1846                         QMessageBox.StandardButton.Yes, 
1847                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1848                                                         return;
1849                 }
1850                 
1851                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1852         for (int i=selections.size()-1; i>=0; i--) {
1853                 QTreeWidgetItem currentSelection;
1854                 currentSelection = selections.get(i);                   
1855                 removeTagItem(currentSelection.text(2));
1856         }
1857         tagIndexUpdated(true);
1858         tagTreeSelection();
1859         listManager.countTagResults(listManager.getNoteIndex());
1860 //              tagTree.updateCounts(listManager.getTagCounter());
1861         logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1862         }
1863         // Remove a tag tree item.  Go recursively down & remove the children too
1864         private void removeTagItem(String guid) {
1865         for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {             
1866                 String parent = listManager.getTagIndex().get(j).getParentGuid();
1867                 if (parent != null && parent.equals(guid)) {            
1868                         //Remove this tag's children
1869                         removeTagItem(listManager.getTagIndex().get(j).getGuid());
1870                 }
1871         }
1872         //Now, remove this tag
1873         removeListTagName(guid);
1874         conn.getTagTable().expungeTag(guid, true);                      
1875         for (int a=0; a<listManager.getTagIndex().size(); a++) {
1876                 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1877                         listManager.getTagIndex().remove(a);
1878                         return;
1879                 }
1880         }
1881         }
1882         // Setup the tree containing the user's tags
1883     private void initializeTagTree() {
1884         logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1885 //      tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1886 //      tagTree.itemClicked.connect(this, "tagTreeSelection()");
1887         tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1888         listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1889         logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1890     }
1891     // Listener when a tag is selected
1892         private void tagTreeSelection() {
1893         logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1894                 
1895         clearTrashFilter();
1896         clearAttributeFilter();
1897         clearSavedSearchFilter();
1898         
1899                 menuBar.noteRestoreAction.setVisible(false);
1900                 
1901         List<QTreeWidgetItem> selections = tagTree.selectedItems();
1902         QTreeWidgetItem currentSelection;
1903         selectedTagGUIDs.clear();
1904         for (int i=0; i<selections.size(); i++) {
1905                 currentSelection = selections.get(i);
1906                 selectedTagGUIDs.add(currentSelection.text(2));
1907         }
1908         if (selections.size() > 0) {
1909                 menuBar.tagEditAction.setEnabled(true);
1910                 menuBar.tagDeleteAction.setEnabled(true);
1911                 menuBar.tagIconAction.setEnabled(true);
1912         }
1913         else {
1914                 menuBar.tagEditAction.setEnabled(false);
1915                 menuBar.tagDeleteAction.setEnabled(false);
1916                 menuBar.tagIconAction.setEnabled(true);
1917         }
1918         listManager.setSelectedTags(selectedTagGUIDs);
1919         listManager.loadNotesIndex();
1920         noteIndexUpdated(false);
1921         logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1922     }
1923     // trigger the tag index to be refreshed
1924     @SuppressWarnings("unused")
1925         private void tagIndexUpdated() {
1926         tagIndexUpdated(true);
1927     }
1928     private void tagIndexUpdated(boolean reload) {
1929         logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1930                 if (selectedTagGUIDs == null)
1931                         selectedTagGUIDs = new ArrayList<String>();
1932                 if (reload)
1933                         listManager.reloadTagIndex();
1934
1935                 tagTree.blockSignals(true);
1936                 if (reload) {
1937                         tagTree.setIcons(conn.getTagTable().getAllIcons());
1938                         tagTree.load(listManager.getTagIndex());
1939                 }
1940         for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1941                 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1942                 if (!found)
1943                         selectedTagGUIDs.remove(i);
1944         }
1945         tagTree.blockSignals(false);
1946         
1947                 browserWindow.setTag(getTagNamesForNote(currentNote));
1948         logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1949     }   
1950     // Show/Hide note information
1951         private void toggleTagWindow() {
1952                 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1953         if (tagTree.isVisible())
1954                 tagTree.hide();
1955         else
1956                 tagTree.show();
1957         menuBar.hideTags.setChecked(tagTree.isVisible());
1958         Global.saveWindowVisible("tagTree", tagTree.isVisible());
1959         logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1960     }   
1961         // A note's tags have been updated
1962         @SuppressWarnings("unused")
1963         private void updateNoteTags(String guid, List<String> tags) {
1964                 // Save any new tags.  We'll need them later.
1965                 List<String> newTags = new ArrayList<String>();
1966                 for (int i=0; i<tags.size(); i++) {
1967                         if (conn.getTagTable().findTagByName(tags.get(i))==null) 
1968                                 newTags.add(tags.get(i));
1969                 }
1970                 
1971                 listManager.saveNoteTags(guid, tags);
1972                 listManager.countTagResults(listManager.getNoteIndex());
1973                 StringBuffer names = new StringBuffer("");
1974                 for (int i=0; i<tags.size(); i++) {
1975                         names = names.append(tags.get(i));
1976                         if (i<tags.size()-1) {
1977                                 names.append(Global.tagDelimeter + " ");
1978                         }
1979                 }
1980                 browserWindow.setTag(names.toString());
1981                 noteDirty = true;
1982                 
1983                 // Now, we need to add any new tags to the tag tree
1984                 for (int i=0; i<newTags.size(); i++) 
1985                         tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
1986         }
1987         // Get a string containing all tag names for a note
1988         private String getTagNamesForNote(Note n) {
1989                 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
1990                 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
1991                         return "";
1992                 StringBuffer buffer = new StringBuffer(100);
1993                 Vector<String> v = new Vector<String>();
1994                 List<String> guids = n.getTagGuids();
1995                 
1996                 if (guids == null) 
1997                         return "";
1998                 
1999                 for (int i=0; i<guids.size(); i++) {
2000                         v.add(listManager.getTagNameByGuid(guids.get(i)));
2001                 }
2002                 Comparator<String> comparator = Collections.reverseOrder();
2003                 Collections.sort(v,comparator);
2004                 Collections.reverse(v);
2005                 
2006                 for (int i = 0; i<v.size(); i++) {
2007                         if (i>0) 
2008                                 buffer.append(", ");
2009                         buffer.append(v.get(i));
2010                 }
2011                 
2012                 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2013                 return buffer.toString();
2014         }       
2015         // Tags were added via dropping notes from the note list
2016         @SuppressWarnings("unused")
2017         private void tagsAdded(String noteGuid, String tagGuid) {
2018                 String tagName = null;
2019                 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2020                         if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2021                                 tagName = listManager.getTagIndex().get(i).getName();
2022                                 i=listManager.getTagIndex().size();
2023                         }
2024                 }
2025                 if (tagName == null)
2026                         return;
2027                 
2028                 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2029                         if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2030                                 List<String> tagNames = new ArrayList<String>();
2031                                 tagNames.add(new String(tagName));
2032                                 Note n = listManager.getMasterNoteIndex().get(i);
2033                                 for (int j=0; j<n.getTagNames().size(); j++) {
2034                                         tagNames.add(new String(n.getTagNames().get(j)));
2035                                 }
2036                                 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2037                                 if (n.getGuid().equals(currentNoteGuid)) {
2038                                         Collections.sort(tagNames);
2039                                         String display = "";
2040                                         for (int j=0; j<tagNames.size(); j++) {
2041                                                 display = display+tagNames.get(j);
2042                                                 if (j+2<tagNames.size()) 
2043                                                         display = display+Global.tagDelimeter+" ";
2044                                         }
2045                                         browserWindow.setTag(display);
2046                                 }
2047                                 i=listManager.getMasterNoteIndex().size();
2048                         }
2049                 }
2050                 
2051                 
2052                 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2053         }
2054         private void clearTagFilter() {
2055                 tagTree.blockSignals(true);
2056                 tagTree.clearSelection();
2057                 menuBar.noteRestoreAction.setVisible(false);
2058                 menuBar.tagEditAction.setEnabled(false);
2059                 menuBar.tagDeleteAction.setEnabled(false);
2060                 menuBar.tagIconAction.setEnabled(false);
2061                 selectedTagGUIDs.clear();
2062         listManager.setSelectedTags(selectedTagGUIDs);
2063         tagTree.blockSignals(false);
2064         }
2065         // Change the icon for a tag
2066         @SuppressWarnings("unused")
2067         private void setTagIcon() {
2068                 QTreeWidgetItem currentSelection;
2069                 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2070                 if (selections.size() == 0)
2071                         return;
2072                 
2073                 currentSelection = selections.get(0);   
2074                 String guid = currentSelection.text(2);
2075
2076                 QIcon currentIcon = currentSelection.icon(0);
2077                 QIcon icon = conn.getTagTable().getIcon(guid);
2078                 SetIcon dialog;
2079                 if (icon == null) {
2080                         dialog = new SetIcon(currentIcon);
2081                         dialog.setUseDefaultIcon(true);
2082                 } else {
2083                         dialog = new SetIcon(icon);
2084                         dialog.setUseDefaultIcon(false);
2085                 }
2086                 dialog.exec();
2087                 if (dialog.okPressed()) {
2088                         QIcon newIcon = dialog.getIcon();
2089                         conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2090                         if (newIcon == null) 
2091                                 newIcon = new QIcon(iconPath+"tag.png");
2092                         currentSelection.setIcon(0, newIcon);
2093                 }
2094         
2095         }
2096
2097         
2098     //***************************************************************
2099     //***************************************************************
2100     //** These functions deal with Saved Search menu items
2101     //***************************************************************
2102     //***************************************************************
2103         // Add a new notebook
2104         @SuppressWarnings("unused")
2105         private void addSavedSearch() {
2106                 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2107                 SavedSearchEdit edit = new SavedSearchEdit();
2108                 edit.setSearchList(listManager.getSavedSearchIndex());
2109                 edit.exec();
2110         
2111                 if (!edit.okPressed())
2112                         return;
2113         
2114                 Calendar currentTime = new GregorianCalendar();         
2115                 Long l = new Long(currentTime.getTimeInMillis());
2116                 String randint = new String(Long.toString(l));
2117         
2118                 SavedSearch search = new SavedSearch();
2119                 search.setUpdateSequenceNum(0);
2120                 search.setGuid(randint);
2121                 search.setName(edit.getName());
2122                 search.setQuery(edit.getQuery());
2123                 search.setFormat(QueryFormat.USER);
2124                 listManager.getSavedSearchIndex().add(search);
2125                 conn.getSavedSearchTable().addSavedSearch(search, true);
2126                 savedSearchIndexUpdated();
2127                 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2128         }
2129         // Edit an existing tag
2130         @SuppressWarnings("unused")
2131         private void editSavedSearch() {
2132                 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2133                 SavedSearchEdit edit = new SavedSearchEdit();
2134                 edit.setTitle(tr("Edit Search"));
2135                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2136                 QTreeWidgetItem currentSelection;
2137                 currentSelection = selections.get(0);
2138                 String guid = currentSelection.text(1);
2139                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2140                 edit.setName(currentSelection.text(0));
2141                 edit.setQuery(s.getQuery());
2142                 edit.setSearchList(listManager.getSavedSearchIndex());
2143                 edit.exec();
2144         
2145                 if (!edit.okPressed())
2146                         return;
2147         
2148                 List<SavedSearch> list = listManager.getSavedSearchIndex();
2149                 SavedSearch search = null;
2150                 boolean found = false;
2151                 for (int i=0; i<list.size(); i++) {
2152                         search = list.get(i);
2153                         if (search.getGuid().equals(guid)) {
2154                                 i=list.size();
2155                                 found = true;
2156                         }
2157                 }
2158                 if (!found)
2159                         return;
2160                 search.setName(edit.getName());
2161                 search.setQuery(edit.getQuery());
2162                 conn.getSavedSearchTable().updateSavedSearch(search, true);
2163                 savedSearchIndexUpdated();
2164                 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2165         }
2166         // Delete an existing tag
2167         @SuppressWarnings("unused")
2168         private void deleteSavedSearch() {
2169                 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2170                 
2171                 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2172                         QMessageBox.StandardButton.Yes, 
2173                         QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2174                                                         return;
2175                 }
2176                 
2177                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2178         for (int i=selections.size()-1; i>=0; i--) {
2179                 QTreeWidgetItem currentSelection;
2180                 currentSelection = selections.get(i);
2181                 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2182                         if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2183                                 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2184                                 listManager.getSavedSearchIndex().remove(j);
2185                                 j=listManager.getSavedSearchIndex().size()+1;
2186                         }
2187                 }
2188                 selections.remove(i);
2189         }
2190         savedSearchIndexUpdated();
2191         logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2192         }
2193     // Setup the tree containing the user's tags
2194     private void initializeSavedSearchTree() {
2195         logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2196         savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2197         logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2198     }
2199     // Listener when a tag is selected
2200     @SuppressWarnings("unused")
2201         private void savedSearchTreeSelection() {
2202         logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2203
2204         clearNotebookFilter();
2205         clearTagFilter();
2206         clearTrashFilter();
2207         clearAttributeFilter();
2208         
2209         String currentGuid = selectedSavedSearchGUID;
2210         menuBar.savedSearchEditAction.setEnabled(true);
2211         menuBar.savedSearchDeleteAction.setEnabled(true);
2212         menuBar.savedSearchIconAction.setEnabled(true);
2213         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2214         QTreeWidgetItem currentSelection;
2215         selectedSavedSearchGUID = "";
2216         for (int i=0; i<selections.size(); i++) {
2217                 currentSelection = selections.get(i);
2218                 if (currentSelection.text(1).equals(currentGuid)) {
2219                         currentSelection.setSelected(false);
2220                 } else {
2221                         selectedSavedSearchGUID = currentSelection.text(1);
2222                 }
2223 //              i = selections.size() +1;
2224         }
2225         
2226         // There is the potential for no notebooks to be selected if this 
2227         // happens then we make it look like all notebooks were selecetd.
2228         // If that happens, just select the "all notebooks"
2229         if (selections.size()==0) {
2230                 clearSavedSearchFilter();
2231         }
2232         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2233         
2234         logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2235     }
2236     private void clearSavedSearchFilter() {
2237         menuBar.savedSearchEditAction.setEnabled(false);
2238         menuBar.savedSearchDeleteAction.setEnabled(false);
2239         menuBar.savedSearchIconAction.setEnabled(false);
2240         savedSearchTree.blockSignals(true);
2241         savedSearchTree.clearSelection();
2242         savedSearchTree.blockSignals(false);
2243         selectedSavedSearchGUID = "";
2244         searchField.setEditText("");
2245         searchPerformed = false;
2246         listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2247     }
2248     // trigger the tag index to be refreshed
2249         private void savedSearchIndexUpdated() { 
2250                 if (selectedSavedSearchGUID == null)
2251                         selectedSavedSearchGUID = new String();
2252                 savedSearchTree.blockSignals(true);
2253                 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2254         savedSearchTree.load(listManager.getSavedSearchIndex());
2255         savedSearchTree.selectGuid(selectedSavedSearchGUID);
2256         savedSearchTree.blockSignals(false);
2257     }
2258     // trigger when the saved search selection changes
2259     @SuppressWarnings("unused")
2260         private void updateSavedSearchSelection() {
2261                 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2262                 
2263         menuBar.savedSearchEditAction.setEnabled(true);
2264         menuBar.savedSearchDeleteAction.setEnabled(true);
2265         menuBar.savedSearchIconAction.setEnabled(true);
2266         List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2267
2268         if (selections.size() > 0) {
2269                 menuBar.savedSearchEditAction.setEnabled(true);
2270                 menuBar.savedSearchDeleteAction.setEnabled(true);
2271                 menuBar.savedSearchIconAction.setEnabled(true);
2272                 selectedSavedSearchGUID = selections.get(0).text(1);
2273                 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2274                 searchField.setEditText(s.getQuery());
2275         } else { 
2276                 menuBar.savedSearchEditAction.setEnabled(false);
2277                 menuBar.savedSearchDeleteAction.setEnabled(false);
2278                 menuBar.savedSearchIconAction.setEnabled(false);
2279                 selectedSavedSearchGUID = "";
2280                 searchField.setEditText("");
2281         }
2282         searchFieldChanged();
2283         
2284                 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2285
2286         
2287     }
2288     // Show/Hide note information
2289         private void toggleSavedSearchWindow() {
2290                 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2291         if (savedSearchTree.isVisible())
2292                 savedSearchTree.hide();
2293         else
2294                 savedSearchTree.show();
2295         menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2296                                 
2297                 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2298         logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2299     }
2300         // Change the icon for a saved search
2301         @SuppressWarnings("unused")
2302         private void setSavedSearchIcon() {
2303                 QTreeWidgetItem currentSelection;
2304                 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2305                 if (selections.size() == 0)
2306                         return;
2307                 
2308                 currentSelection = selections.get(0);   
2309                 String guid = currentSelection.text(1);
2310
2311                 QIcon currentIcon = currentSelection.icon(0);
2312                 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2313                 SetIcon dialog;
2314                 if (icon == null) {
2315                         dialog = new SetIcon(currentIcon);
2316                         dialog.setUseDefaultIcon(true);
2317                 } else {
2318                         dialog = new SetIcon(icon);
2319                         dialog.setUseDefaultIcon(false);
2320                 }
2321                 dialog.exec();
2322                 if (dialog.okPressed()) {
2323                         QIcon newIcon = dialog.getIcon();
2324                         conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2325                         if (newIcon == null) 
2326                                 newIcon = new QIcon(iconPath+"search.png");
2327                         currentSelection.setIcon(0, newIcon);
2328                 }
2329         
2330         }
2331         
2332         
2333         
2334         
2335     //***************************************************************
2336     //***************************************************************
2337     //** These functions deal with Help menu & tool menu items
2338     //***************************************************************
2339     //***************************************************************
2340         // Show database status
2341         @SuppressWarnings("unused")
2342         private void databaseStatus() {
2343                 waitCursor(true);
2344                 int dirty = conn.getNoteTable().getDirtyCount();
2345                 int unindexed = conn.getNoteTable().getUnindexedCount();
2346                 DatabaseStatus status = new DatabaseStatus();
2347                 status.setUnsynchronized(dirty);
2348                 status.setUnindexed(unindexed);
2349                 status.setNoteCount(conn.getNoteTable().getNoteCount());
2350                 status.setNotebookCount(listManager.getNotebookIndex().size());
2351                 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2352                 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2353                 status.setTagCount(listManager.getTagIndex().size());
2354                 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2355                 status.setWordCount(conn.getWordsTable().getWordCount());
2356                 waitCursor(false);
2357                 status.exec();
2358         }
2359         // Compact the database
2360         @SuppressWarnings("unused")
2361         private void compactDatabase() {
2362         logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2363                 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2364                                 "but please be aware that depending upon the size of your database this can be time consuming " +
2365                                 "and NeverNote will be unresponsive until it is complete.  Do you wish to continue?"),
2366                                 QMessageBox.StandardButton.Yes, 
2367                                 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2368                                                         return;
2369                 }
2370                 setMessage("Compacting database.");
2371                 waitCursor(true);
2372                 listManager.compactDatabase();
2373                 waitCursor(false);
2374                 setMessage("Database compact is complete.");            
2375         logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2376     }
2377         @SuppressWarnings("unused")
2378         private void accountInformation() {
2379                 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2380                 AccountDialog dialog = new AccountDialog();
2381                 dialog.show();
2382                 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2383         }
2384         @SuppressWarnings("unused")
2385         private void releaseNotes() {
2386                 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2387                 QDialog dialog = new QDialog(this);
2388                 QHBoxLayout layout = new QHBoxLayout();
2389                 QTextEdit textBox = new QTextEdit();
2390                 layout.addWidget(textBox);
2391                 textBox.setReadOnly(true);
2392                 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2393                 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2394                 QIODevice.OpenModeFlag.Text)))
2395                         return;
2396                 textBox.setText(file.readAll().toString());
2397                 file.close();
2398                 dialog.setWindowTitle(tr("Release Notes"));
2399                 dialog.setLayout(layout);
2400                 dialog.show();
2401                 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2402         }
2403         // Called when user picks Log from the help menu
2404         @SuppressWarnings("unused")
2405         private void logger() {
2406                 logger.log(logger.HIGH, "Entering NeverNote.logger");
2407                 QDialog dialog = new QDialog(this);
2408                 QHBoxLayout layout = new QHBoxLayout();
2409                 QListWidget textBox = new QListWidget();
2410                 layout.addWidget(textBox);
2411                 textBox.addItems(emitLog);
2412                 
2413                 dialog.setLayout(layout);
2414                 dialog.setWindowTitle(tr("Mesasge Log"));
2415                 dialog.show();
2416                 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2417         }
2418         // Menu option "help/about" was selected
2419         @SuppressWarnings("unused")
2420         private void about() {
2421                 logger.log(logger.HIGH, "Entering NeverNote.about");
2422                 QMessageBox.about(this, 
2423                                                 tr("About NeverNote"),
2424                                                 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2425                                                 +Global.version
2426                                                 +tr("<hr></center>Evernote"
2427                                                                 +"An Open Source Evernote Client.<br><br>" 
2428                                                                 +"Licensed under GPL v2.  <br><hr><br>"
2429                                                                 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2430                                                                 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2431                                                                 +"PDFRenderer is licened under the LGPL<br>"
2432                                                                 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2433                                                                 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2434                                                                 +"Jazzy is licened under the LGPL<br>"
2435                                                                 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));     
2436                 logger.log(logger.HIGH, "Leaving NeverNote.about");
2437         }
2438         // Hide the entire left hand side
2439         @SuppressWarnings("unused")
2440         private void toggleLeftSide() {
2441                 boolean hidden;
2442                 
2443                 hidden = !menuBar.hideLeftSide.isChecked();
2444                 menuBar.hideLeftSide.setChecked(!hidden);
2445                 
2446                 if (notebookTree.isVisible() != hidden)
2447                         toggleNotebookWindow();
2448                 if (savedSearchTree.isVisible() != hidden)
2449                         toggleSavedSearchWindow();
2450                 if (tagTree.isVisible() != hidden)
2451                         toggleTagWindow();
2452                 if (attributeTree.isVisible() != hidden)
2453                         toggleAttributesWindow();
2454                 if (trashTree.isVisible() != hidden)
2455                         toggleTrashWindow();
2456                 
2457                 Global.saveWindowVisible("leftPanel", hidden);
2458                 
2459         }
2460                         
2461         
2462     //***************************************************************
2463     //***************************************************************
2464     //** These functions deal with the Toolbar
2465     //***************************************************************
2466     //***************************************************************  
2467         // Text in the search bar has been cleared
2468         private void searchFieldCleared() {
2469                 saveNote();
2470                 
2471                 // This is done because we want to force a reload of
2472                 // images.  Some images we may want to highlight the text.
2473                 readOnlyCache.clear();
2474                 inkNoteCache.clear();
2475                 noteCache.clear();
2476                 QWebSettings.setMaximumPagesInCache(0);
2477                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2478         
2479                 searchField.setEditText("");
2480                 saveNoteColumnPositions();
2481                 saveNoteIndexWidth();
2482                 noteIndexUpdated(true);
2483                 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2484                         currentNote = listManager.getNoteIndex().get(0);
2485                         currentNoteGuid = currentNote.getGuid();
2486                 }
2487                 if (currentNote != null)
2488                         loadNoteBrowserInformation(browserWindow);
2489         }
2490         // text in the search bar changed.  We only use this to tell if it was cleared, 
2491         // otherwise we trigger off searchFieldChanged.
2492         @SuppressWarnings("unused")
2493         private void searchFieldTextChanged(String text) {
2494                 if (text.trim().equals("")) {
2495                         searchFieldCleared();
2496                         if (searchPerformed) {
2497
2498                                 // This is done because we want to force a reload of
2499                                 // images.  Some images we may want to highlight the text.
2500                                 noteCache.clear();
2501                                 readOnlyCache.clear();
2502                                 inkNoteCache.clear();
2503                                 QWebSettings.setMaximumPagesInCache(0);
2504                                 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2505                                 
2506                                 listManager.setEnSearch("");
2507                                 listManager.loadNotesIndex();
2508                                 refreshEvernoteNote(true);
2509                                 noteIndexUpdated(false);
2510                         }
2511                         searchPerformed = false;
2512                 }
2513         }
2514     // Text in the toolbar has changed
2515     private void searchFieldChanged() {
2516         logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2517         noteCache.clear();
2518         readOnlyCache.clear();
2519         inkNoteCache.clear();
2520         saveNoteColumnPositions();
2521         saveNoteIndexWidth();
2522         String text = searchField.currentText();
2523         listManager.setEnSearch(text.trim());
2524         listManager.loadNotesIndex();
2525 //--->>>        noteIndexUpdated(true);
2526         noteIndexUpdated(false);
2527         refreshEvernoteNote(true);
2528         searchPerformed = true;
2529         logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2530     }
2531
2532     // Build the window tool bar
2533     private void setupToolBar() {
2534         logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2535         toolBar = addToolBar(tr("Tool Bar"));   
2536         menuBar.setupToolBarVisible();
2537         if (!Global.isWindowVisible("toolBar"))
2538                 toolBar.setVisible(false);
2539         else
2540                 toolBar.setVisible(true);
2541
2542         prevButton = toolBar.addAction("Previous");
2543         QIcon prevIcon = new QIcon(iconPath+"back.png");
2544         prevButton.setIcon(prevIcon);
2545         prevButton.triggered.connect(this, "previousViewedAction()");   
2546         togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2547         
2548         nextButton = toolBar.addAction("Next");
2549         QIcon nextIcon = new QIcon(iconPath+"forward.png");
2550         nextButton.setIcon(nextIcon);
2551         nextButton.triggered.connect(this, "nextViewedAction()");       
2552         toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2553         
2554         upButton = toolBar.addAction("Up");
2555         QIcon upIcon = new QIcon(iconPath+"up.png");
2556         upButton.setIcon(upIcon);
2557         upButton.triggered.connect(this, "upAction()");         
2558         toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2559
2560         
2561         downButton = toolBar.addAction("Down");
2562         QIcon downIcon = new QIcon(iconPath+"down.png");
2563         downButton.setIcon(downIcon);
2564         downButton.triggered.connect(this, "downAction()");
2565         toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2566         
2567         synchronizeButton = toolBar.addAction("Synchronize");
2568         synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2569         synchronizeIconAngle = 0;
2570         synchronizeButton.triggered.connect(this, "evernoteSync()");
2571         toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2572         
2573         printButton = toolBar.addAction("Print");
2574         QIcon printIcon = new QIcon(iconPath+"print.png");
2575         printButton.setIcon(printIcon);
2576         printButton.triggered.connect(this, "printNote()");
2577         togglePrintButton(Global.isToolbarButtonVisible("print"));
2578
2579         tagButton = toolBar.addAction("Tag"); 
2580         QIcon tagIcon = new QIcon(iconPath+"tag.png");
2581         tagButton.setIcon(tagIcon);
2582         tagButton.triggered.connect(browserWindow, "modifyTags()");
2583         toggleTagButton(Global.isToolbarButtonVisible("tag"));
2584
2585         attributeButton = toolBar.addAction("Attributes"); 
2586         QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2587         attributeButton.setIcon(attributeIcon);
2588         attributeButton.triggered.connect(this, "toggleNoteInformation()");
2589         toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2590                 
2591         emailButton = toolBar.addAction("Email");
2592         QIcon emailIcon = new QIcon(iconPath+"email.png");
2593         emailButton.setIcon(emailIcon);
2594         emailButton.triggered.connect(this, "emailNote()");
2595         toggleEmailButton(Global.isToolbarButtonVisible("email"));
2596
2597         deleteButton = toolBar.addAction("Delete");     
2598         QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2599         deleteButton.setIcon(deleteIcon);
2600         deleteButton.triggered.connect(this, "deleteNote()");
2601         toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2602
2603         newButton = toolBar.addAction("New");
2604         QIcon newIcon = new QIcon(iconPath+"new.png");
2605         newButton.triggered.connect(this, "addNote()");
2606         newButton.setIcon(newIcon);
2607         toggleNewButton(Global.isToolbarButtonVisible("new"));
2608         
2609         allNotesButton = toolBar.addAction("All Notes");
2610         QIcon allIcon = new QIcon(iconPath+"books.png");
2611         allNotesButton.triggered.connect(this, "allNotes()");
2612         allNotesButton.setIcon(allIcon);
2613         toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2614         
2615         toolBar.addSeparator();
2616         toolBar.addWidget(new QLabel(tr("Quota:")));
2617         toolBar.addWidget(quotaBar);
2618         //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2619         updateQuotaBar();
2620         toolBar.addSeparator();
2621         
2622         // Setup the zoom
2623         zoomSpinner = new QSpinBox();
2624         zoomSpinner.setMinimum(10);
2625         zoomSpinner.setMaximum(1000);
2626         zoomSpinner.setAccelerated(true);
2627         zoomSpinner.setSingleStep(10);
2628         zoomSpinner.setValue(100);
2629         zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2630         toolBar.addWidget(new QLabel(tr("Zoom")));
2631         toolBar.addWidget(zoomSpinner);
2632         
2633         //toolBar.addWidget(new QLabel("                    "));
2634         toolBar.addSeparator();
2635         toolBar.addWidget(new QLabel(tr("  Search:")));
2636         toolBar.addWidget(searchField);
2637         QSizePolicy sizePolicy = new QSizePolicy();
2638         sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2639         searchField.setSizePolicy(sizePolicy);
2640         searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2641
2642         searchClearButton = toolBar.addAction("Search Clear");
2643         QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2644         searchClearButton.setIcon(searchClearIcon);
2645         searchClearButton.triggered.connect(this, "searchFieldCleared()");
2646         toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2647
2648         logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2649     }
2650     // Update the sychronize button picture
2651     @Override
2652         public QMenu createPopupMenu() {
2653         QMenu contextMenu = super.createPopupMenu();
2654         
2655         contextMenu.addSeparator();
2656         QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2657         contextMenu.addAction(prevAction);
2658         prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2659
2660         QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2661         contextMenu.addAction(nextAction);
2662         nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2663
2664         QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2665         contextMenu.addAction(upAction);
2666         upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2667
2668         QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2669         contextMenu.addAction(downAction);
2670         downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2671
2672         QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2673         contextMenu.addAction(synchronizeAction);
2674         synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2675
2676         QAction printAction = addContextAction("print", tr("Print"));
2677         contextMenu.addAction(printAction);
2678         printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2679
2680         QAction tagAction = addContextAction("tag", tr("Tag"));
2681         contextMenu.addAction(tagAction);
2682         tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2683         
2684         QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2685         contextMenu.addAction(attributeAction);
2686         attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2687         
2688         QAction emailAction = addContextAction("email", tr("Email"));
2689         contextMenu.addAction(emailAction);
2690         emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2691
2692         QAction deleteAction = addContextAction("delete", tr("Delete"));
2693         contextMenu.addAction(deleteAction);
2694         deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2695
2696         QAction newAction = addContextAction("new", tr("Add"));
2697         contextMenu.addAction(newAction);
2698         newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2699
2700         QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2701         contextMenu.addAction(allNotesAction);
2702         allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2703         
2704         QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2705         contextMenu.addAction(searchClearAction);
2706         searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2707         
2708         return contextMenu;
2709         
2710     }
2711     private QAction addContextAction(String config, String name) {
2712         QAction newAction = new QAction(this);
2713                 newAction.setText(name);
2714                 newAction.setCheckable(true);
2715                 newAction.setChecked(Global.isToolbarButtonVisible(config));
2716                 return newAction;
2717     }
2718     private void togglePrevArrowButton(Boolean toggle) {
2719                 prevButton.setVisible(toggle);
2720                 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2721     }
2722     private void toggleNextArrowButton(Boolean toggle) {
2723                 nextButton.setVisible(toggle);
2724                 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2725     }
2726     private void toggleUpArrowButton(Boolean toggle) {
2727                 upButton.setVisible(toggle);
2728                 Global.saveToolbarButtonsVisible("upArrow", toggle);
2729     }
2730     private void toggleDownArrowButton(Boolean toggle) {
2731                 downButton.setVisible(toggle);
2732                 Global.saveToolbarButtonsVisible("downArrow", toggle);
2733     }
2734     private void toggleSynchronizeButton(Boolean toggle) {
2735                 synchronizeButton.setVisible(toggle);
2736                 Global.saveToolbarButtonsVisible("synchronize", toggle);
2737     }
2738     private void togglePrintButton(Boolean toggle) {
2739                 printButton.setVisible(toggle);
2740                 Global.saveToolbarButtonsVisible("print", toggle);
2741     }
2742     private void toggleTagButton(Boolean toggle) {
2743                 tagButton.setVisible(toggle);
2744                 Global.saveToolbarButtonsVisible("tag", toggle);
2745     }
2746     private void toggleAttributeButton(Boolean toggle) {
2747                 attributeButton.setVisible(toggle);
2748                 Global.saveToolbarButtonsVisible("attribute", toggle);
2749     }
2750     private void toggleEmailButton(Boolean toggle) {
2751                 emailButton.setVisible(toggle);
2752                 Global.saveToolbarButtonsVisible("email", toggle);
2753     }
2754     private void toggleDeleteButton(Boolean toggle) {
2755                 deleteButton.setVisible(toggle);
2756                 Global.saveToolbarButtonsVisible("delete", toggle);
2757     }
2758     private void toggleNewButton(Boolean toggle) {
2759                 newButton.setVisible(toggle);
2760                 Global.saveToolbarButtonsVisible("new", toggle);
2761     }
2762     private void toggleAllNotesButton(Boolean toggle) {
2763                 allNotesButton.setVisible(toggle);
2764                 Global.saveToolbarButtonsVisible("allNotes", toggle);
2765     }
2766     private void toggleSearchClearButton(Boolean toggle) {
2767                 searchClearButton.setVisible(toggle);
2768                 Global.saveToolbarButtonsVisible("searchClear", toggle);
2769     }
2770
2771
2772
2773
2774
2775     @SuppressWarnings("unused")
2776         private void updateSyncButton() {
2777                 
2778         if (syncIcons == null) {
2779                 syncIcons = new ArrayList<QPixmap>();
2780                 double angle = 0.0;
2781                 synchronizeIconAngle = 0;
2782                 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2783                 syncIcons.add(pix);
2784                 for (int i=0; i<=360; i++) {
2785                         QPixmap rotatedPix = new QPixmap(pix.size());
2786                         QPainter p = new QPainter(rotatedPix);
2787                 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2788                 QSize size = pix.size();
2789                 p.translate(size.width()/2, size.height()/2);
2790                 angle = angle+1.0;
2791                 p.rotate(angle);
2792                 p.setBackgroundMode(BGMode.OpaqueMode);
2793                 p.translate(-size.width()/2, -size.height()/2);
2794                 p.drawPixmap(0,0, pix);
2795                 p.end();
2796                 syncIcons.add(rotatedPix);
2797                 }
2798         }
2799
2800         synchronizeIconAngle++;
2801         if (synchronizeIconAngle > 359)
2802                 synchronizeIconAngle=0;
2803         synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2804         
2805     }
2806     // Synchronize with Evernote
2807         @SuppressWarnings("unused")
2808         private void evernoteSync() {
2809         logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2810         if (!Global.isConnected)
2811                 remoteConnect();
2812         if (Global.isConnected)
2813                 synchronizeAnimationTimer.start(5);
2814 //                      synchronizeAnimationTimer.start(200);
2815         syncTimer();
2816         logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2817     }
2818     private void updateQuotaBar() {
2819         long limit = Global.getUploadLimit();
2820         long amount = Global.getUploadAmount();
2821         if (amount>0 && limit>0) {
2822                 int percent =(int)(amount*100/limit);
2823                 quotaBar.setValue(percent);
2824         } else 
2825                 quotaBar.setValue(0);
2826     }
2827         // Zoom changed
2828     @SuppressWarnings("unused")
2829         private void zoomChanged() {
2830         browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2831     }
2832
2833     //****************************************************************
2834     //****************************************************************
2835     //* System Tray functions
2836     //****************************************************************
2837     //****************************************************************
2838         private void trayToggleVisible() {
2839         if (isVisible()) {
2840                 hide();
2841         } else {
2842                 show();
2843                 if (windowMaximized)
2844                         showMaximized();
2845                 else
2846                         showNormal();
2847                 raise();
2848         }
2849     }
2850     @SuppressWarnings("unused")
2851         private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2852         if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2853                 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2854                 trayToggleVisible();
2855         }
2856     }
2857     
2858     
2859     //***************************************************************
2860     //***************************************************************
2861     //** These functions deal with the trash tree
2862     //***************************************************************
2863     //***************************************************************    
2864     // Setup the tree containing the trash.
2865     @SuppressWarnings("unused")
2866         private void trashTreeSelection() {     
2867         logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2868         
2869         clearNotebookFilter();
2870         clearTagFilter();
2871         clearAttributeFilter();
2872         clearSavedSearchFilter();
2873         
2874         String tempGuid = currentNoteGuid;
2875         
2876 //      currentNoteGuid = "";
2877         currentNote = new Note();
2878         selectedNoteGUIDs.clear();
2879         listManager.getSelectedNotebooks().clear();
2880         listManager.getSelectedTags().clear();
2881         listManager.setSelectedSavedSearch("");
2882         browserWindow.clear();
2883     
2884         // toggle the add buttons
2885         newButton.setEnabled(!newButton.isEnabled());
2886         menuBar.noteAdd.setEnabled(newButton.isEnabled());
2887         menuBar.noteAdd.setVisible(true);
2888         
2889         List<QTreeWidgetItem> selections = trashTree.selectedItems();
2890         if (selections.size() == 0) {
2891                 currentNoteGuid = trashNoteGuid;
2892                         trashNoteGuid = tempGuid;
2893                 Global.showDeleted = false;
2894                 menuBar.noteRestoreAction.setEnabled(false);
2895                 menuBar.noteRestoreAction.setVisible(false);
2896         }
2897         else {
2898                 currentNoteGuid = trashNoteGuid;
2899                         trashNoteGuid = tempGuid;
2900                 menuBar.noteRestoreAction.setEnabled(true);
2901                 menuBar.noteRestoreAction.setVisible(true);
2902                 Global.showDeleted = true;
2903         }
2904         listManager.loadNotesIndex();
2905         noteIndexUpdated(false);
2906 ////            browserWindow.setEnabled(newButton.isEnabled());
2907         browserWindow.setReadOnly(!newButton.isEnabled());
2908         logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2909     }
2910     // Empty the trash file
2911     @SuppressWarnings("unused")
2912         private void emptyTrash() {
2913 //      browserWindow.clear();
2914         listManager.emptyTrash();
2915         if (trashTree.selectedItems().size() > 0) {
2916                 listManager.getSelectedNotebooks().clear();
2917                 listManager.getSelectedTags().clear();
2918                 listManager.setSelectedSavedSearch("");
2919                 newButton.setEnabled(!newButton.isEnabled());
2920                 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2921                 menuBar.noteAdd.setVisible(true);
2922                 browserWindow.clear();
2923                 
2924                 clearTagFilter();
2925                 clearNotebookFilter();
2926                 clearSavedSearchFilter();
2927                 clearAttributeFilter();
2928                         
2929                 Global.showDeleted = false;
2930                 menuBar.noteRestoreAction.setEnabled(false);
2931                 menuBar.noteRestoreAction.setVisible(false);
2932                 
2933                 listManager.loadNotesIndex();
2934 //--->>>                noteIndexUpdated(true);
2935                 noteIndexUpdated(false);
2936         }       
2937    }
2938     // Show/Hide trash window
2939         private void toggleTrashWindow() {
2940                 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2941         if (trashTree.isVisible())
2942                 trashTree.hide();
2943         else
2944                 trashTree.show();
2945         menuBar.hideTrash.setChecked(trashTree.isVisible());
2946         
2947                 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2948         logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2949     }    
2950         private void clearTrashFilter() {
2951                 Global.showDeleted = false;
2952         newButton.setEnabled(true);
2953         menuBar.noteAdd.setEnabled(true);
2954         menuBar.noteAdd.setVisible(true);
2955                 trashTree.blockSignals(true);
2956                 trashTree.clearSelection();
2957                 trashTree.blockSignals(false);
2958                 
2959         }
2960     
2961    
2962     //***************************************************************
2963     //***************************************************************
2964     //** These functions deal with connection settings
2965     //***************************************************************
2966     //***************************************************************
2967         // SyncRunner had a problem and things are disconnected
2968         @SuppressWarnings("unused")
2969         private void remoteErrorDisconnect() {
2970                 menuBar.connectAction.setText(tr("Connect"));
2971                 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2972                 menuBar.synchronizeAction.setEnabled(false);
2973                 synchronizeAnimationTimer.stop();
2974                 return;
2975         }
2976         // Do a manual connect/disconnect
2977     private void remoteConnect() {
2978         logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2979
2980         if (Global.isConnected) {
2981                 Global.isConnected = false;
2982                 syncRunner.enDisconnect();
2983                 setupConnectMenuOptions();
2984                 setupOnlineMenu();
2985                 return;
2986         }
2987         
2988         AESEncrypter aes = new AESEncrypter();
2989         try {
2990                         aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
2991                 } catch (FileNotFoundException e) {
2992                         // File not found, so we'll just get empty strings anyway. 
2993                 }
2994                 String userid = aes.getUserid();
2995                 String password = aes.getPassword();
2996                 if (!userid.equals("") && !password.equals("")) {
2997                 Global.username = userid;
2998                 Global.password = password;
2999                 }               
3000
3001         // Show the login dialog box
3002                 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3003                         LoginDialog login = new LoginDialog();
3004                         login.exec();
3005                 
3006                         if (!login.okPressed()) {
3007                                 return;
3008                         }
3009         
3010                         Global.username = login.getUserid();
3011                         Global.password = login.getPassword();
3012                 }
3013                 syncRunner.username = Global.username;
3014                 syncRunner.password = Global.password;
3015                 syncRunner.userStoreUrl = Global.userStoreUrl;
3016                 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3017                 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3018                 
3019             if (Global.getProxyValue("url").equals("")) {
3020                 System.setProperty("http.proxyHost","") ;
3021                 System.setProperty("http.proxyPort", "") ;
3022                 System.setProperty("https.proxyHost","") ;
3023                 System.setProperty("https.proxyPort", "") ;         
3024             } else {
3025                         // PROXY
3026                 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3027                 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3028                 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3029                 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3030          
3031                 if (Global.getProxyValue("userid").equals("")) {
3032                         Authenticator.setDefault(new Authenticator() {
3033                                 @Override
3034                                 protected PasswordAuthentication getPasswordAuthentication() {
3035                                         return new
3036                                         PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3037                                         }});
3038                         }
3039                 }
3040                 
3041                 
3042                 syncRunner.enConnect();
3043                 Global.isConnected = syncRunner.isConnected;
3044                 setupOnlineMenu();
3045                 setupConnectMenuOptions();
3046                 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3047     }
3048     private void setupConnectMenuOptions() {
3049         logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3050                 if (!Global.isConnected) {
3051                         menuBar.connectAction.setText(tr("Connect"));
3052                         menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3053                         menuBar.synchronizeAction.setEnabled(false);
3054                 } else {
3055                         menuBar.connectAction.setText(tr("Disconnect"));
3056                         menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3057                         menuBar.synchronizeAction.setEnabled(true);
3058                 }
3059                 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3060     }
3061     
3062     
3063     
3064     //***************************************************************
3065     //***************************************************************
3066     //** These functions deal with the GUI Attribute tree
3067     //***************************************************************
3068     //***************************************************************    
3069     @SuppressWarnings("unused")
3070         private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3071         
3072 //      clearTagFilter();
3073 //      clearNotebookFilter();
3074         clearTrashFilter();
3075 //      clearSavedSearchFilter();
3076
3077         if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3078                 if (item.childCount() > 0) {
3079                         item.setSelected(false);
3080                 } else {
3081                 Global.createdBeforeFilter.reset();
3082                 Global.createdSinceFilter.reset();
3083                 Global.changedBeforeFilter.reset();
3084                 Global.changedSinceFilter.reset();
3085                 Global.containsFilter.reset();
3086                         attributeTreeSelected = item;
3087                         DateAttributeFilterTable f = null;
3088                         f = findDateAttributeFilterTable(item.parent());
3089                         if (f!=null)
3090                                 f.select(item.parent().indexOfChild(item));
3091                         else {
3092                                 Global.containsFilter.select(item.parent().indexOfChild(item));
3093                         }