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