OSDN Git Service

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