OSDN Git Service

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