OSDN Git Service

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