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())
703 public void checkForUpdates() {
704 // Send off thread to check for a new version
705 versionChecker = new QNetworkAccessManager(this);
706 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
707 QNetworkRequest request = new QNetworkRequest();
708 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
709 versionChecker.get(request);
711 private void upgradeFileRead(QNetworkReply reply) {
712 if (!reply.isReadable())
715 String winVersion = Global.version;
716 String osxVersion = Global.version;
717 String linuxVersion = Global.version;
718 String linux64Version = Global.version;
719 String version = Global.version;
721 // Determine the versions available
722 QByteArray data = reply.readLine();
723 while (data != null && !reply.atEnd()) {
724 String line = data.toString();
726 if (line.contains(":"))
727 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
730 if (line.toLowerCase().contains("windows"))
731 winVersion = lineVersion;
732 else if (line.toLowerCase().contains("os-x"))
733 osxVersion = lineVersion;
734 else if (line.toLowerCase().contains("linux amd64"))
735 linux64Version = lineVersion;
736 else if (line.toLowerCase().contains("linux i386"))
737 linuxVersion = lineVersion;
738 else if (line.toLowerCase().contains("default"))
739 version = lineVersion;
741 // Read the next line
742 data = reply.readLine();
745 // Now we need to determine what system we are on.
746 if (System.getProperty("os.name").toLowerCase().contains("windows"))
747 version = winVersion;
748 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
749 version = osxVersion;
750 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
751 if (System.getProperty("os.arch").contains("amd64") ||
752 System.getProperty("os.arch").contains("x86_64") ||
753 System.getProperty("os.arch").contains("i686"))
754 version = linux64Version;
756 version = linuxVersion;
760 if (Global.version.equals(version))
763 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
765 if (dialog.remindMe())
766 Global.setCheckVersionUpgrade(true);
768 Global.setCheckVersionUpgrade(false);
773 public static void main(String[] args) {
774 log.setLevel(Level.FATAL);
775 QApplication.initialize(args);
776 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
777 QSplashScreen splash = new QSplashScreen(pixmap);
780 DatabaseConnection dbConn;
783 initializeGlobalSettings(args);
785 showSplash = Global.isWindowVisible("SplashScreen");
789 dbConn = setupDatabaseConnection();
791 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
792 Global.getFileManager().purgeResDirectory(true);
794 } catch (InitializationException e) {
797 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
801 NeverNote application = new NeverNote(dbConn);
803 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
804 if (Global.startMinimized())
805 application.showMinimized();
807 if (Global.wasWindowMaximized())
808 application.showMaximized();
814 splash.finish(application);
816 System.out.println("Goodbye.");
821 * Open the internal database, or create if not present
823 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
825 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
826 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
828 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
829 boolean dbExists = f.exists();
831 Global.setDatabaseUrl("");
833 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
834 boolean goodCheck = false;
836 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
838 if (!dialog.okPressed())
840 Global.cipherPassword = dialog.getPassword();
841 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
842 Global.getDatabaseUserPassword(), Global.cipherPassword);
845 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
849 // Encrypt the database upon shutdown
850 private void encryptOnShutdown() {
851 String dbPath= Global.getFileManager().getDbDirPath("");
852 String dbName = "NeverNote";
854 Statement st = conn.getConnection().createStatement();
855 st.execute("shutdown");
856 if (QMessageBox.question(this, "Are you sure",
857 "Are you sure you wish to encrypt the database?",
858 QMessageBox.StandardButton.Yes,
859 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
860 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
861 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
862 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
864 } catch (SQLException e) {
869 // Decrypt the database upon shutdown
870 private void decryptOnShutdown() {
871 String dbPath= Global.getFileManager().getDbDirPath("");
872 String dbName = "NeverNote";
874 Statement st = conn.getConnection().createStatement();
875 st.execute("shutdown");
876 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
877 encryptCipher = "AES";
879 encryptCipher = "XTEA";
880 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
881 "Are you sure you wish to decrypt the database?"),
882 QMessageBox.StandardButton.Yes,
883 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
885 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
886 Global.setDatabaseUrl("");
887 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
889 } catch (SQLException e) {
894 * Encrypt/Decrypt the local database
896 public void doDatabaseEncrypt() {
897 // The database is not currently encrypted
898 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
899 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
900 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
901 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
902 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
903 "Do you wish to proceed?"),
904 QMessageBox.StandardButton.Yes,
905 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
908 DBEncryptDialog dialog = new DBEncryptDialog();
910 if (dialog.okPressed()) {
911 Global.cipherPassword = dialog.getPassword();
912 encryptOnShutdown = true;
913 encryptCipher = dialog.getEncryptionMethod();
916 DBEncryptDialog dialog = new DBEncryptDialog();
917 dialog.setWindowTitle("Database Decryption");
918 dialog.hideEncryption();
920 if (dialog.okPressed()) {
921 if (!dialog.getPassword().equals(Global.cipherPassword)) {
922 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
925 decryptOnShutdown = true;
932 private static void initializeGlobalSettings(String[] args) throws InitializationException {
933 StartupConfig startupConfig = new StartupConfig();
935 for (String arg : args) {
936 String lower = arg.toLowerCase();
937 if (lower.startsWith("--name="))
938 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
939 if (lower.startsWith("--home="))
940 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
941 if (lower.startsWith("--disable-viewing"))
942 startupConfig.setDisableViewing(true);
944 Global.setup(startupConfig);
949 public void closeEvent(QCloseEvent event) {
950 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
955 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
958 if (currentNote!= null & browserWindow!=null) {
959 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
960 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
963 setMessage(tr("Beginning shutdown."));
965 // Close down external windows
966 Collection<ExternalBrowse> windows = externalWindows.values();
967 Iterator<ExternalBrowse> iterator = windows.iterator();
968 while (iterator.hasNext()) {
969 ExternalBrowse browser = iterator.next();
970 browser.windowClosing.disconnect();
975 externalFileEditedSaver();
976 if (Global.isConnected && Global.synchronizeOnClose()) {
977 setMessage(tr("Performing synchronization before closing."));
978 syncRunner.addWork("SYNC");
980 setMessage("Closing Program.");
981 threadMonitorTimer.stop();
983 syncRunner.addWork("STOP");
984 syncRunner.keepRunning = false;
985 thumbnailRunner.addWork("STOP");
986 syncRunner.keepRunning = false;
987 indexRunner.addWork("STOP");
988 syncRunner.keepRunning = false;
993 if (tempFiles != null)
996 browserWindow.noteSignal.tagsChanged.disconnect();
997 browserWindow.noteSignal.titleChanged.disconnect();
998 browserWindow.noteSignal.noteChanged.disconnect();
999 browserWindow.noteSignal.notebookChanged.disconnect();
1000 browserWindow.noteSignal.createdDateChanged.disconnect();
1001 browserWindow.noteSignal.alteredDateChanged.disconnect();
1002 syncRunner.searchSignal.listChanged.disconnect();
1003 syncRunner.tagSignal.listChanged.disconnect();
1004 syncRunner.notebookSignal.listChanged.disconnect();
1005 syncRunner.noteIndexSignal.listChanged.disconnect();
1008 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1009 saveNoteColumnPositions();
1010 saveNoteIndexWidth();
1012 int width = notebookTree.columnWidth(0);
1013 Global.setColumnWidth("notebookTreeName", width);
1014 width = tagTree.columnWidth(0);
1015 Global.setColumnWidth("tagTreeName", width);
1017 Global.saveWindowMaximized(isMaximized());
1018 Global.saveCurrentNoteGuid(currentNoteGuid);
1020 int sortCol = noteTableView.proxyModel.sortColumn();
1021 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1022 Global.setSortColumn(sortCol);
1023 Global.setSortOrder(sortOrder);
1027 Global.keepRunning = false;
1029 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1030 if (indexRunner.thread().isAlive())
1031 indexRunner.thread().join(50);
1032 if (!indexRunner.thread().isAlive())
1033 logger.log(logger.MEDIUM, "Index thread has stopped");
1035 logger.log(logger.MEDIUM, "Index thread still running - bypassing");
1036 } catch (InterruptedException e1) {
1037 e1.printStackTrace();
1039 if (!syncRunner.isIdle()) {
1041 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1043 logger.log(logger.MEDIUM, "Sync thread has stopped");
1044 } catch (InterruptedException e1) {
1045 e1.printStackTrace();
1049 if (encryptOnShutdown) {
1050 encryptOnShutdown();
1052 if (decryptOnShutdown) {
1053 decryptOnShutdown();
1055 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1058 @SuppressWarnings("unused")
1059 private void closeNeverNote() {
1063 public void setMessage(String s) {
1064 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1065 logger.log(logger.HIGH, "Message: " +s);
1066 statusBar.showMessage(s);
1068 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1071 private void waitCursor(boolean wait) {
1073 if (QApplication.overrideCursor() == null)
1074 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1077 while (QApplication.overrideCursor() != null)
1078 QApplication.restoreOverrideCursor();
1082 private void setupIndexListeners() {
1083 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1084 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1085 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1086 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1088 private void setupSyncSignalListeners() {
1089 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1090 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1091 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1092 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1093 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1095 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1096 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1097 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1099 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1100 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1101 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1102 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1104 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1107 private void setupBrowserSignalListeners() {
1108 setupBrowserWindowListeners(browserWindow, true);
1111 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1112 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1113 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1114 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1115 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1116 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1117 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1118 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1119 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1120 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1121 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1122 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1123 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1124 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1125 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1126 if (master) browser.focusLost.connect(this, "saveNote()");
1127 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1130 //***************************************************************
1131 //***************************************************************
1132 //* Settings and look & feel
1133 //***************************************************************
1134 //***************************************************************
1135 @SuppressWarnings("unused")
1136 private void settings() {
1137 logger.log(logger.HIGH, "Entering NeverNote.settings");
1138 saveNoteColumnPositions();
1139 saveNoteIndexWidth();
1141 ConfigDialog settings = new ConfigDialog(this);
1142 String dateFormat = Global.getDateFormat();
1143 String timeFormat = Global.getTimeFormat();
1145 indexTime = 1000*Global.getIndexThreadSleepInterval();
1146 indexTimer.start(indexTime); // reset indexing timer
1149 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1150 if (Global.showTrayIcon())
1155 if (menuBar.showEditorBar.isChecked())
1156 showEditorButtons(browserWindow);
1158 // Reset the save timer
1159 if (Global.getAutoSaveInterval() > 0)
1160 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1164 // This is a hack to force a reload of the index in case the date or time changed.
1165 // if (!dateFormat.equals(Global.getDateFormat()) ||
1166 // !timeFormat.equals(Global.getTimeFormat())) {
1168 readOnlyCache.clear();
1169 inkNoteCache.clear();
1170 noteIndexUpdated(true);
1173 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1175 // Restore things to the way they were
1176 private void restoreWindowState(boolean mainWindow) {
1177 // We need to name things or this doesn't work.
1178 setObjectName("NeverNote");
1179 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1180 browserIndexSplitter.setObjectName("browserIndexSplitter");
1181 leftSplitter1.setObjectName("leftSplitter1");
1183 // Restore the actual positions.
1185 restoreGeometry(Global.restoreGeometry(objectName()));
1186 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1187 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1188 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1191 // Save window positions for the next start
1192 private void saveWindowState() {
1193 Global.saveGeometry(objectName(), saveGeometry());
1194 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1195 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1196 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1198 // Load the style sheet
1199 private void loadStyleSheet() {
1200 String fileName = Global.getFileManager().getQssDirPath("default.qss");
1201 QFile file = new QFile(fileName);
1202 file.open(OpenModeFlag.ReadOnly);
1203 String styleSheet = file.readAll().toString();
1205 setStyleSheet(styleSheet);
1207 // Save column positions for the next time
1208 private void saveNoteColumnPositions() {
1209 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1210 Global.setColumnPosition("noteTableCreationPosition", position);
1211 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1212 Global.setColumnPosition("noteTableTagPosition", position);
1213 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1214 Global.setColumnPosition("noteTableNotebookPosition", position);
1215 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1216 Global.setColumnPosition("noteTableChangedPosition", position);
1217 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1218 Global.setColumnPosition("noteTableAuthorPosition", position);
1219 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1220 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1221 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1222 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1223 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1224 Global.setColumnPosition("noteTableTitlePosition", position);
1225 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1226 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1227 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1228 Global.setColumnPosition("noteTableGuidPosition", position);
1229 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1230 Global.setColumnPosition("noteTableThumbnailPosition", position);
1233 // Save column widths for the next time
1234 private void saveNoteIndexWidth() {
1236 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1237 Global.setColumnWidth("noteTableCreationPosition", width);
1238 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1239 Global.setColumnWidth("noteTableChangedPosition", width);
1240 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1241 Global.setColumnWidth("noteTableGuidPosition", width);
1242 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1243 Global.setColumnWidth("noteTableNotebookPosition", width);
1244 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1245 Global.setColumnWidth("noteTableTagPosition", width);
1246 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1247 Global.setColumnWidth("noteTableTitlePosition", width);
1248 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1249 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1250 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1251 Global.setColumnWidth("noteTableAuthorPosition", width);
1252 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1253 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1254 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1255 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1256 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1257 Global.setColumnWidth("noteTableThumbnailPosition", width);
1258 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1259 Global.setColumnWidth("noteTableGuidPosition", width);
1263 //***************************************************************
1264 //***************************************************************
1265 //** These functions deal with Notebook menu items
1266 //***************************************************************
1267 //***************************************************************
1268 // Setup the tree containing the user's notebooks.
1269 private void initializeNotebookTree() {
1270 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1271 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1272 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1273 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1274 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1276 // Listener when a notebook is selected
1277 private void notebookTreeSelection() {
1278 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1281 clearAttributeFilter();
1282 clearSavedSearchFilter();
1283 if (Global.mimicEvernoteInterface) {
1285 searchField.clear();
1287 menuBar.noteRestoreAction.setVisible(false);
1288 menuBar.notebookEditAction.setEnabled(true);
1289 menuBar.notebookDeleteAction.setEnabled(true);
1290 menuBar.notebookPublishAction.setEnabled(true);
1291 menuBar.notebookShareAction.setEnabled(true);
1292 menuBar.notebookIconAction.setEnabled(true);
1293 menuBar.notebookStackAction.setEnabled(true);
1294 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1295 selectedNotebookGUIDs.clear();
1297 String stackName = "";
1298 if (selections.size() > 0) {
1299 guid = (selections.get(0).text(2));
1300 stackName = selections.get(0).text(0);
1302 if (!Global.mimicEvernoteInterface) {
1303 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1304 if (selections.size()==0) {
1305 selectedNotebookGUIDs.clear();
1306 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1307 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1309 menuBar.notebookEditAction.setEnabled(false);
1310 menuBar.notebookDeleteAction.setEnabled(false);
1311 menuBar.notebookStackAction.setEnabled(false);
1312 menuBar.notebookIconAction.setEnabled(false);
1315 if (!guid.equals("") && !guid.equals("STACK")) {
1316 selectedNotebookGUIDs.add(guid);
1317 menuBar.notebookIconAction.setEnabled(true);
1319 menuBar.notebookIconAction.setEnabled(true);
1320 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1321 Notebook book = listManager.getNotebookIndex().get(j);
1322 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1323 selectedNotebookGUIDs.add(book.getGuid());
1326 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1327 listManager.loadNotesIndex();
1328 noteIndexUpdated(false);
1329 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1332 private void clearNotebookFilter() {
1333 notebookTree.blockSignals(true);
1334 notebookTree.clearSelection();
1335 menuBar.noteRestoreAction.setVisible(false);
1336 menuBar.notebookEditAction.setEnabled(false);
1337 menuBar.notebookDeleteAction.setEnabled(false);
1338 selectedNotebookGUIDs.clear();
1339 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1340 notebookTree.blockSignals(false);
1342 // Triggered when the notebook DB has been updated
1343 private void notebookIndexUpdated() {
1344 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1346 // Get the possible icons
1347 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1348 notebookTree.setIcons(icons);
1350 if (selectedNotebookGUIDs == null)
1351 selectedNotebookGUIDs = new ArrayList<String>();
1352 List<Notebook> books = conn.getNotebookTable().getAll();
1353 for (int i=books.size()-1; i>=0; i--) {
1354 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1355 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1357 j=listManager.getArchiveNotebookIndex().size();
1363 listManager.countNotebookResults(listManager.getNoteIndex());
1364 notebookTree.blockSignals(true);
1365 notebookTree.load(books, listManager.getLocalNotebooks());
1366 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1367 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1369 selectedNotebookGUIDs.remove(i);
1371 notebookTree.blockSignals(false);
1373 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1375 // Show/Hide note information
1376 private void toggleNotebookWindow() {
1377 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1378 if (notebookTree.isVisible())
1379 notebookTree.hide();
1381 notebookTree.show();
1382 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1383 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1384 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1386 // Add a new notebook
1387 @SuppressWarnings("unused")
1388 private void addNotebook() {
1389 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1390 NotebookEdit edit = new NotebookEdit();
1391 edit.setNotebooks(listManager.getNotebookIndex());
1394 if (!edit.okPressed())
1397 Calendar currentTime = new GregorianCalendar();
1398 Long l = new Long(currentTime.getTimeInMillis());
1399 String randint = new String(Long.toString(l));
1401 Notebook newBook = new Notebook();
1402 newBook.setUpdateSequenceNum(0);
1403 newBook.setGuid(randint);
1404 newBook.setName(edit.getNotebook());
1405 newBook.setServiceCreated(new Date().getTime());
1406 newBook.setServiceUpdated(new Date().getTime());
1407 newBook.setDefaultNotebook(false);
1408 newBook.setPublished(false);
1410 listManager.getNotebookIndex().add(newBook);
1412 listManager.getLocalNotebooks().add(newBook.getGuid());
1413 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1414 notebookIndexUpdated();
1415 listManager.countNotebookResults(listManager.getNoteIndex());
1416 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1417 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1419 // Edit an existing notebook
1420 @SuppressWarnings("unused")
1421 private void stackNotebook() {
1422 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1423 StackNotebook edit = new StackNotebook();
1425 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1426 QTreeWidgetItem currentSelection;
1427 for (int i=0; i<selections.size(); i++) {
1428 currentSelection = selections.get(0);
1429 String guid = currentSelection.text(2);
1430 if (guid.equalsIgnoreCase("")) {
1431 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1434 if (guid.equalsIgnoreCase("STACK")) {
1435 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1440 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1445 if (!edit.okPressed())
1448 String stack = edit.getStackName();
1450 for (int i=0; i<selections.size(); i++) {
1451 currentSelection = selections.get(i);
1452 String guid = currentSelection.text(2);
1453 listManager.updateNotebookStack(guid, stack);
1455 notebookIndexUpdated();
1456 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1458 // Edit an existing notebook
1459 @SuppressWarnings("unused")
1460 private void editNotebook() {
1461 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1462 NotebookEdit edit = new NotebookEdit();
1464 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1465 QTreeWidgetItem currentSelection;
1466 currentSelection = selections.get(0);
1467 edit.setNotebook(currentSelection.text(0));
1469 String guid = currentSelection.text(2);
1470 if (!guid.equalsIgnoreCase("STACK")) {
1471 edit.setTitle(tr("Edit Notebook"));
1472 edit.setNotebooks(listManager.getNotebookIndex());
1473 edit.setLocalCheckboxEnabled(false);
1474 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1475 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1476 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1477 i=listManager.getNotebookIndex().size();
1481 edit.setTitle(tr("Edit Stack"));
1482 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1483 edit.hideLocalCheckbox();
1484 edit.hideDefaultCheckbox();
1489 if (!edit.okPressed())
1493 if (guid.equalsIgnoreCase("STACK")) {
1494 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1495 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1496 if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1497 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1499 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1500 currentSelection.setText(0, edit.getNotebook());
1504 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1505 currentSelection.setText(0, edit.getNotebook());
1507 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1508 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1509 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1510 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1511 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1512 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1513 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1514 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1516 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1517 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1518 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1519 linkedNotebook.setShareName(edit.getNotebook());
1520 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1522 i=listManager.getNotebookIndex().size();
1526 // Build a list of non-closed notebooks
1527 List<Notebook> nbooks = new ArrayList<Notebook>();
1528 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1529 boolean found=false;
1530 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1531 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1535 nbooks.add(listManager.getNotebookIndex().get(i));
1539 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1540 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1541 browserWindow.setNotebookList(filteredBooks);
1542 Iterator<String> set = externalWindows.keySet().iterator();
1543 while(set.hasNext())
1544 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1545 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1547 // Publish a notebook
1548 @SuppressWarnings("unused")
1549 private void publishNotebook() {
1550 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1551 QTreeWidgetItem currentSelection;
1552 currentSelection = selections.get(0);
1553 String guid = currentSelection.text(2);
1555 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1560 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1561 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1562 n = listManager.getNotebookIndex().get(i);
1564 i = listManager.getNotebookIndex().size();
1570 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1573 if (!publish.okClicked())
1576 Publishing p = publish.getPublishing();
1577 boolean isPublished = !publish.isStopPressed();
1578 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1579 n.setPublished(isPublished);
1581 listManager.getNotebookIndex().set(position, n);
1582 notebookIndexUpdated();
1584 // Publish a notebook
1585 @SuppressWarnings("unused")
1586 private void shareNotebook() {
1587 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1588 QTreeWidgetItem currentSelection;
1589 currentSelection = selections.get(0);
1590 String guid = currentSelection.text(2);
1592 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1596 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1597 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1598 n = listManager.getNotebookIndex().get(i);
1599 i = listManager.getNotebookIndex().size();
1603 String authToken = null;
1604 if (syncRunner.isConnected)
1605 authToken = syncRunner.authToken;
1606 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1611 // Delete an existing notebook
1612 @SuppressWarnings("unused")
1613 private void deleteNotebook() {
1614 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1615 boolean stacksFound = false;
1616 boolean notebooksFound = false;
1617 boolean assigned = false;
1618 // Check if any notes have this notebook
1619 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1620 for (int i=0; i<selections.size(); i++) {
1621 QTreeWidgetItem currentSelection;
1622 currentSelection = selections.get(i);
1623 String guid = currentSelection.text(2);
1624 if (!guid.equalsIgnoreCase("STACK")) {
1625 notebooksFound = true;
1626 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1627 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1628 if (noteGuid.equals(guid)) {
1630 j=listManager.getNoteIndex().size();
1631 i=selections.size();
1639 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1640 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1644 if (conn.getNotebookTable().getAll().size() == 1) {
1645 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1649 // If all notebooks are clear, verify the delete
1650 String msg1 = new String(tr("Delete selected notebooks?"));
1651 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1652 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1653 " not deleted unless selected?"));
1655 if (stacksFound && notebooksFound)
1657 if (!stacksFound && notebooksFound)
1659 if (stacksFound && !notebooksFound)
1661 if (QMessageBox.question(this, tr("Confirmation"), msg,
1662 QMessageBox.StandardButton.Yes,
1663 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1667 // If confirmed, delete the notebook
1668 for (int i=selections.size()-1; i>=0; i--) {
1669 QTreeWidgetItem currentSelection;
1670 currentSelection = selections.get(i);
1671 String guid = currentSelection.text(2);
1672 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1673 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1674 listManager.renameStack(currentSelection.text(0), "");
1676 conn.getNotebookTable().expungeNotebook(guid, true);
1677 listManager.deleteNotebook(guid);
1681 notebookIndexUpdated();
1682 // notebookTreeSelection();
1683 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1684 // listManager.countNotebookResults(listManager.getNoteIndex());
1685 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1687 // A note's notebook has been updated
1688 @SuppressWarnings("unused")
1689 private void updateNoteNotebook(String guid, String notebookGuid) {
1691 // Update the list manager
1692 listManager.updateNoteNotebook(guid, notebookGuid);
1693 listManager.countNotebookResults(listManager.getNoteIndex());
1694 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1696 // Find the name of the notebook
1697 String notebookName = null;
1698 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1699 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1700 notebookName = listManager.getNotebookIndex().get(i).getName();
1705 // If we found the name, update the browser window
1706 if (notebookName != null) {
1707 updateListNoteNotebook(guid, notebookName);
1708 if (guid.equals(currentNoteGuid)) {
1709 int pos = browserWindow.notebookBox.findText(notebookName);
1711 browserWindow.notebookBox.setCurrentIndex(pos);
1715 // If we're dealing with the current note, then we need to be sure and update the notebook there
1716 if (guid.equals(currentNoteGuid)) {
1717 if (currentNote != null) {
1718 currentNote.setNotebookGuid(notebookGuid);
1722 // Open/close notebooks
1723 @SuppressWarnings("unused")
1724 private void closeNotebooks() {
1725 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1727 if (!na.okClicked())
1731 listManager.getArchiveNotebookIndex().clear();
1733 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1734 String text = na.getClosedBookList().takeItem(i).text();
1735 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1736 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1737 Notebook n = listManager.getNotebookIndex().get(j);
1738 conn.getNotebookTable().setArchived(n.getGuid(),true);
1739 listManager.getArchiveNotebookIndex().add(n);
1740 j=listManager.getNotebookIndex().size();
1745 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1746 String text = na.getOpenBookList().takeItem(i).text();
1747 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1748 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1749 Notebook n = listManager.getNotebookIndex().get(j);
1750 conn.getNotebookTable().setArchived(n.getGuid(),false);
1751 j=listManager.getNotebookIndex().size();
1755 notebookTreeSelection();
1756 listManager.loadNotesIndex();
1757 notebookIndexUpdated();
1758 noteIndexUpdated(false);
1759 reloadTagTree(true);
1760 // noteIndexUpdated(false);
1762 // Build a list of non-closed notebooks
1763 List<Notebook> nbooks = new ArrayList<Notebook>();
1764 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1765 boolean found=false;
1766 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1767 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1771 nbooks.add(listManager.getNotebookIndex().get(i));
1774 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1775 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1776 browserWindow.setNotebookList(filteredBooks);
1778 // Update any external windows
1779 Iterator<String> set = externalWindows.keySet().iterator();
1780 while(set.hasNext())
1781 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1785 // Change the notebook's icon
1786 @SuppressWarnings("unused")
1787 private void setNotebookIcon() {
1788 boolean stackSelected = false;
1789 boolean allNotebookSelected = false;
1791 QTreeWidgetItem currentSelection;
1792 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1793 if (selections.size() == 0)
1796 currentSelection = selections.get(0);
1797 String guid = currentSelection.text(2);
1798 if (guid.equalsIgnoreCase(""))
1799 allNotebookSelected = true;
1800 if (guid.equalsIgnoreCase("STACK"))
1801 stackSelected = true;
1803 QIcon currentIcon = currentSelection.icon(0);
1807 if (!stackSelected && !allNotebookSelected) {
1808 icon = conn.getNotebookTable().getIcon(guid);
1810 dialog = new SetIcon(currentIcon);
1811 dialog.setUseDefaultIcon(true);
1813 dialog = new SetIcon(icon);
1814 dialog.setUseDefaultIcon(false);
1817 if (stackSelected) {
1818 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1820 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1823 dialog = new SetIcon(currentIcon);
1824 dialog.setUseDefaultIcon(true);
1826 dialog = new SetIcon(icon);
1827 dialog.setUseDefaultIcon(false);
1831 if (dialog.okPressed()) {
1832 QIcon newIcon = dialog.getIcon();
1833 if (stackSelected) {
1834 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1835 if (newIcon == null) {
1836 newIcon = new QIcon(iconPath+"books2.png");
1838 currentSelection.setIcon(0,newIcon);
1841 if (allNotebookSelected) {
1842 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1843 if (newIcon == null) {
1844 newIcon = new QIcon(iconPath+"notebook-green.png");
1846 currentSelection.setIcon(0,newIcon);
1849 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1850 if (newIcon == null) {
1851 boolean isPublished = false;;
1852 boolean found = false;
1853 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1854 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1855 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1859 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1861 currentSelection.setIcon(0, newIcon);
1867 //***************************************************************
1868 //***************************************************************
1869 //** These functions deal with Tag menu items
1870 //***************************************************************
1871 //***************************************************************
1872 // Add a new notebook
1873 @SuppressWarnings("unused")
1874 private void addTag() {
1875 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1876 TagEdit edit = new TagEdit();
1877 edit.setTagList(listManager.getTagIndex());
1880 if (!edit.okPressed())
1883 Calendar currentTime = new GregorianCalendar();
1884 Long l = new Long(currentTime.getTimeInMillis());
1885 String randint = new String(Long.toString(l));
1887 Tag newTag = new Tag();
1888 newTag.setUpdateSequenceNum(0);
1889 newTag.setGuid(randint);
1890 newTag.setName(edit.getTag());
1891 conn.getTagTable().addTag(newTag, true);
1892 listManager.getTagIndex().add(newTag);
1893 reloadTagTree(true);
1895 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1897 @SuppressWarnings("unused")
1898 private void reloadTagTree() {
1899 reloadTagTree(false);
1901 private void reloadTagTree(boolean reload) {
1902 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1903 tagIndexUpdated(reload);
1904 boolean filter = false;
1905 listManager.countTagResults(listManager.getNoteIndex());
1906 if (notebookTree.selectedItems().size() > 0
1907 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1909 if (tagTree.selectedItems().size() > 0)
1911 tagTree.showAllTags(!filter);
1912 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1914 // Edit an existing tag
1915 @SuppressWarnings("unused")
1916 private void editTag() {
1917 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1918 TagEdit edit = new TagEdit();
1919 edit.setTitle("Edit Tag");
1920 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1921 QTreeWidgetItem currentSelection;
1922 currentSelection = selections.get(0);
1923 edit.setTag(currentSelection.text(0));
1924 edit.setTagList(listManager.getTagIndex());
1927 if (!edit.okPressed())
1930 String guid = currentSelection.text(2);
1931 currentSelection.setText(0,edit.getTag());
1933 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1934 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1935 listManager.getTagIndex().get(i).setName(edit.getTag());
1936 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1937 updateListTagName(guid);
1938 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1939 browserWindow.setTag(getTagNamesForNote(currentNote));
1940 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1944 browserWindow.setTag(getTagNamesForNote(currentNote));
1945 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1947 // Delete an existing tag
1948 @SuppressWarnings("unused")
1949 private void deleteTag() {
1950 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1952 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1953 QMessageBox.StandardButton.Yes,
1954 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1958 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1959 for (int i=selections.size()-1; i>=0; i--) {
1960 QTreeWidgetItem currentSelection;
1961 currentSelection = selections.get(i);
1962 removeTagItem(currentSelection.text(2));
1964 tagIndexUpdated(true);
1966 listManager.countTagResults(listManager.getNoteIndex());
1967 // tagTree.updateCounts(listManager.getTagCounter());
1968 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1970 // Remove a tag tree item. Go recursively down & remove the children too
1971 private void removeTagItem(String guid) {
1972 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1973 String parent = listManager.getTagIndex().get(j).getParentGuid();
1974 if (parent != null && parent.equals(guid)) {
1975 //Remove this tag's children
1976 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1979 //Now, remove this tag
1980 removeListTagName(guid);
1981 conn.getTagTable().expungeTag(guid, true);
1982 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1983 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1984 listManager.getTagIndex().remove(a);
1989 // Setup the tree containing the user's tags
1990 private void initializeTagTree() {
1991 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1992 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1993 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
1994 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1995 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1996 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1998 // Listener when a tag is selected
1999 private void tagTreeSelection() {
2000 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2003 clearAttributeFilter();
2004 clearSavedSearchFilter();
2006 menuBar.noteRestoreAction.setVisible(false);
2008 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2009 QTreeWidgetItem currentSelection;
2010 selectedTagGUIDs.clear();
2011 for (int i=0; i<selections.size(); i++) {
2012 currentSelection = selections.get(i);
2013 selectedTagGUIDs.add(currentSelection.text(2));
2015 if (selections.size() > 0) {
2016 menuBar.tagEditAction.setEnabled(true);
2017 menuBar.tagDeleteAction.setEnabled(true);
2018 menuBar.tagIconAction.setEnabled(true);
2021 menuBar.tagEditAction.setEnabled(false);
2022 menuBar.tagDeleteAction.setEnabled(false);
2023 menuBar.tagIconAction.setEnabled(true);
2025 listManager.setSelectedTags(selectedTagGUIDs);
2026 listManager.loadNotesIndex();
2027 noteIndexUpdated(false);
2028 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2030 // trigger the tag index to be refreshed
2031 @SuppressWarnings("unused")
2032 private void tagIndexUpdated() {
2033 tagIndexUpdated(true);
2035 private void tagIndexUpdated(boolean reload) {
2036 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2037 if (selectedTagGUIDs == null)
2038 selectedTagGUIDs = new ArrayList<String>();
2040 listManager.reloadTagIndex();
2042 tagTree.blockSignals(true);
2044 tagTree.setIcons(conn.getTagTable().getAllIcons());
2045 tagTree.load(listManager.getTagIndex());
2047 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2048 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2050 selectedTagGUIDs.remove(i);
2052 tagTree.blockSignals(false);
2054 browserWindow.setTag(getTagNamesForNote(currentNote));
2055 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2057 // Show/Hide note information
2058 private void toggleTagWindow() {
2059 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2060 if (tagTree.isVisible())
2064 menuBar.hideTags.setChecked(tagTree.isVisible());
2065 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2066 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2068 // A note's tags have been updated
2069 @SuppressWarnings("unused")
2070 private void updateNoteTags(String guid, List<String> tags) {
2071 // Save any new tags. We'll need them later.
2072 List<String> newTags = new ArrayList<String>();
2073 for (int i=0; i<tags.size(); i++) {
2074 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2075 newTags.add(tags.get(i));
2078 listManager.saveNoteTags(guid, tags);
2079 listManager.countTagResults(listManager.getNoteIndex());
2080 StringBuffer names = new StringBuffer("");
2081 for (int i=0; i<tags.size(); i++) {
2082 names = names.append(tags.get(i));
2083 if (i<tags.size()-1) {
2084 names.append(Global.tagDelimeter + " ");
2087 browserWindow.setTag(names.toString());
2090 // Now, we need to add any new tags to the tag tree
2091 for (int i=0; i<newTags.size(); i++)
2092 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2094 // Get a string containing all tag names for a note
2095 private String getTagNamesForNote(Note n) {
2096 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2097 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2099 StringBuffer buffer = new StringBuffer(100);
2100 Vector<String> v = new Vector<String>();
2101 List<String> guids = n.getTagGuids();
2106 for (int i=0; i<guids.size(); i++) {
2107 v.add(listManager.getTagNameByGuid(guids.get(i)));
2109 Comparator<String> comparator = Collections.reverseOrder();
2110 Collections.sort(v,comparator);
2111 Collections.reverse(v);
2113 for (int i = 0; i<v.size(); i++) {
2115 buffer.append(", ");
2116 buffer.append(v.get(i));
2119 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2120 return buffer.toString();
2122 // Tags were added via dropping notes from the note list
2123 @SuppressWarnings("unused")
2124 private void tagsAdded(String noteGuid, String tagGuid) {
2125 String tagName = null;
2126 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2127 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2128 tagName = listManager.getTagIndex().get(i).getName();
2129 i=listManager.getTagIndex().size();
2132 if (tagName == null)
2135 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2136 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2137 List<String> tagNames = new ArrayList<String>();
2138 tagNames.add(new String(tagName));
2139 Note n = listManager.getMasterNoteIndex().get(i);
2140 for (int j=0; j<n.getTagNames().size(); j++) {
2141 tagNames.add(new String(n.getTagNames().get(j)));
2143 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2144 if (n.getGuid().equals(currentNoteGuid)) {
2145 Collections.sort(tagNames);
2146 String display = "";
2147 for (int j=0; j<tagNames.size(); j++) {
2148 display = display+tagNames.get(j);
2149 if (j+2<tagNames.size())
2150 display = display+Global.tagDelimeter+" ";
2152 browserWindow.setTag(display);
2154 i=listManager.getMasterNoteIndex().size();
2159 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2161 private void clearTagFilter() {
2162 tagTree.blockSignals(true);
2163 tagTree.clearSelection();
2164 menuBar.noteRestoreAction.setVisible(false);
2165 menuBar.tagEditAction.setEnabled(false);
2166 menuBar.tagDeleteAction.setEnabled(false);
2167 menuBar.tagIconAction.setEnabled(false);
2168 selectedTagGUIDs.clear();
2169 listManager.setSelectedTags(selectedTagGUIDs);
2170 tagTree.blockSignals(false);
2172 // Change the icon for a tag
2173 @SuppressWarnings("unused")
2174 private void setTagIcon() {
2175 QTreeWidgetItem currentSelection;
2176 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2177 if (selections.size() == 0)
2180 currentSelection = selections.get(0);
2181 String guid = currentSelection.text(2);
2183 QIcon currentIcon = currentSelection.icon(0);
2184 QIcon icon = conn.getTagTable().getIcon(guid);
2187 dialog = new SetIcon(currentIcon);
2188 dialog.setUseDefaultIcon(true);
2190 dialog = new SetIcon(icon);
2191 dialog.setUseDefaultIcon(false);
2194 if (dialog.okPressed()) {
2195 QIcon newIcon = dialog.getIcon();
2196 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2197 if (newIcon == null)
2198 newIcon = new QIcon(iconPath+"tag.png");
2199 currentSelection.setIcon(0, newIcon);
2205 //***************************************************************
2206 //***************************************************************
2207 //** These functions deal with Saved Search menu items
2208 //***************************************************************
2209 //***************************************************************
2210 // Add a new notebook
2211 @SuppressWarnings("unused")
2212 private void addSavedSearch() {
2213 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2214 SavedSearchEdit edit = new SavedSearchEdit();
2215 edit.setSearchList(listManager.getSavedSearchIndex());
2218 if (!edit.okPressed())
2221 Calendar currentTime = new GregorianCalendar();
2222 Long l = new Long(currentTime.getTimeInMillis());
2223 String randint = new String(Long.toString(l));
2225 SavedSearch search = new SavedSearch();
2226 search.setUpdateSequenceNum(0);
2227 search.setGuid(randint);
2228 search.setName(edit.getName());
2229 search.setQuery(edit.getQuery());
2230 search.setFormat(QueryFormat.USER);
2231 listManager.getSavedSearchIndex().add(search);
2232 conn.getSavedSearchTable().addSavedSearch(search, true);
2233 savedSearchIndexUpdated();
2234 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2236 // Edit an existing tag
2237 @SuppressWarnings("unused")
2238 private void editSavedSearch() {
2239 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2240 SavedSearchEdit edit = new SavedSearchEdit();
2241 edit.setTitle(tr("Edit Search"));
2242 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2243 QTreeWidgetItem currentSelection;
2244 currentSelection = selections.get(0);
2245 String guid = currentSelection.text(1);
2246 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2247 edit.setName(currentSelection.text(0));
2248 edit.setQuery(s.getQuery());
2249 edit.setSearchList(listManager.getSavedSearchIndex());
2252 if (!edit.okPressed())
2255 List<SavedSearch> list = listManager.getSavedSearchIndex();
2256 SavedSearch search = null;
2257 boolean found = false;
2258 for (int i=0; i<list.size(); i++) {
2259 search = list.get(i);
2260 if (search.getGuid().equals(guid)) {
2267 search.setName(edit.getName());
2268 search.setQuery(edit.getQuery());
2269 conn.getSavedSearchTable().updateSavedSearch(search, true);
2270 savedSearchIndexUpdated();
2271 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2273 // Delete an existing tag
2274 @SuppressWarnings("unused")
2275 private void deleteSavedSearch() {
2276 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2278 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2279 QMessageBox.StandardButton.Yes,
2280 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2284 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2285 for (int i=selections.size()-1; i>=0; i--) {
2286 QTreeWidgetItem currentSelection;
2287 currentSelection = selections.get(i);
2288 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2289 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2290 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2291 listManager.getSavedSearchIndex().remove(j);
2292 j=listManager.getSavedSearchIndex().size()+1;
2295 selections.remove(i);
2297 savedSearchIndexUpdated();
2298 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2300 // Setup the tree containing the user's tags
2301 private void initializeSavedSearchTree() {
2302 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2303 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2304 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2306 // Listener when a tag is selected
2307 @SuppressWarnings("unused")
2308 private void savedSearchTreeSelection() {
2309 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2311 clearNotebookFilter();
2314 clearAttributeFilter();
2316 String currentGuid = selectedSavedSearchGUID;
2317 menuBar.savedSearchEditAction.setEnabled(true);
2318 menuBar.savedSearchDeleteAction.setEnabled(true);
2319 menuBar.savedSearchIconAction.setEnabled(true);
2320 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2321 QTreeWidgetItem currentSelection;
2322 selectedSavedSearchGUID = "";
2323 for (int i=0; i<selections.size(); i++) {
2324 currentSelection = selections.get(i);
2325 if (currentSelection.text(1).equals(currentGuid)) {
2326 currentSelection.setSelected(false);
2328 selectedSavedSearchGUID = currentSelection.text(1);
2330 // i = selections.size() +1;
2333 // There is the potential for no notebooks to be selected if this
2334 // happens then we make it look like all notebooks were selecetd.
2335 // If that happens, just select the "all notebooks"
2336 if (selections.size()==0) {
2337 clearSavedSearchFilter();
2339 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2341 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2343 private void clearSavedSearchFilter() {
2344 menuBar.savedSearchEditAction.setEnabled(false);
2345 menuBar.savedSearchDeleteAction.setEnabled(false);
2346 menuBar.savedSearchIconAction.setEnabled(false);
2347 savedSearchTree.blockSignals(true);
2348 savedSearchTree.clearSelection();
2349 savedSearchTree.blockSignals(false);
2350 selectedSavedSearchGUID = "";
2351 searchField.setEditText("");
2352 searchPerformed = false;
2353 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2355 // trigger the tag index to be refreshed
2356 private void savedSearchIndexUpdated() {
2357 if (selectedSavedSearchGUID == null)
2358 selectedSavedSearchGUID = new String();
2359 savedSearchTree.blockSignals(true);
2360 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2361 savedSearchTree.load(listManager.getSavedSearchIndex());
2362 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2363 savedSearchTree.blockSignals(false);
2365 // trigger when the saved search selection changes
2366 @SuppressWarnings("unused")
2367 private void updateSavedSearchSelection() {
2368 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2370 menuBar.savedSearchEditAction.setEnabled(true);
2371 menuBar.savedSearchDeleteAction.setEnabled(true);
2372 menuBar.savedSearchIconAction.setEnabled(true);
2373 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2375 if (selections.size() > 0) {
2376 menuBar.savedSearchEditAction.setEnabled(true);
2377 menuBar.savedSearchDeleteAction.setEnabled(true);
2378 menuBar.savedSearchIconAction.setEnabled(true);
2379 selectedSavedSearchGUID = selections.get(0).text(1);
2380 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2381 searchField.setEditText(s.getQuery());
2383 menuBar.savedSearchEditAction.setEnabled(false);
2384 menuBar.savedSearchDeleteAction.setEnabled(false);
2385 menuBar.savedSearchIconAction.setEnabled(false);
2386 selectedSavedSearchGUID = "";
2387 searchField.setEditText("");
2389 searchFieldChanged();
2391 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2395 // Show/Hide note information
2396 private void toggleSavedSearchWindow() {
2397 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2398 if (savedSearchTree.isVisible())
2399 savedSearchTree.hide();
2401 savedSearchTree.show();
2402 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2404 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2405 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2407 // Change the icon for a saved search
2408 @SuppressWarnings("unused")
2409 private void setSavedSearchIcon() {
2410 QTreeWidgetItem currentSelection;
2411 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2412 if (selections.size() == 0)
2415 currentSelection = selections.get(0);
2416 String guid = currentSelection.text(1);
2418 QIcon currentIcon = currentSelection.icon(0);
2419 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2422 dialog = new SetIcon(currentIcon);
2423 dialog.setUseDefaultIcon(true);
2425 dialog = new SetIcon(icon);
2426 dialog.setUseDefaultIcon(false);
2429 if (dialog.okPressed()) {
2430 QIcon newIcon = dialog.getIcon();
2431 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2432 if (newIcon == null)
2433 newIcon = new QIcon(iconPath+"search.png");
2434 currentSelection.setIcon(0, newIcon);
2442 //***************************************************************
2443 //***************************************************************
2444 //** These functions deal with Help menu & tool menu items
2445 //***************************************************************
2446 //***************************************************************
2447 // Show database status
2448 @SuppressWarnings("unused")
2449 private void databaseStatus() {
2451 int dirty = conn.getNoteTable().getDirtyCount();
2452 int unindexed = conn.getNoteTable().getUnindexedCount();
2453 DatabaseStatus status = new DatabaseStatus();
2454 status.setUnsynchronized(dirty);
2455 status.setUnindexed(unindexed);
2456 status.setNoteCount(conn.getNoteTable().getNoteCount());
2457 status.setNotebookCount(listManager.getNotebookIndex().size());
2458 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2459 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2460 status.setTagCount(listManager.getTagIndex().size());
2461 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2462 status.setWordCount(conn.getWordsTable().getWordCount());
2466 // Compact the database
2467 @SuppressWarnings("unused")
2468 private void compactDatabase() {
2469 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2470 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2471 "but please be aware that depending upon the size of your database this can be time consuming " +
2472 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2473 QMessageBox.StandardButton.Yes,
2474 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2477 setMessage("Compacting database.");
2479 listManager.compactDatabase();
2481 setMessage("Database compact is complete.");
2482 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2484 @SuppressWarnings("unused")
2485 private void accountInformation() {
2486 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2487 AccountDialog dialog = new AccountDialog();
2489 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2491 @SuppressWarnings("unused")
2492 private void releaseNotes() {
2493 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2494 QDialog dialog = new QDialog(this);
2495 QHBoxLayout layout = new QHBoxLayout();
2496 QTextEdit textBox = new QTextEdit();
2497 layout.addWidget(textBox);
2498 textBox.setReadOnly(true);
2499 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2500 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2501 QIODevice.OpenModeFlag.Text)))
2503 textBox.setText(file.readAll().toString());
2505 dialog.setWindowTitle(tr("Release Notes"));
2506 dialog.setLayout(layout);
2508 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2510 // Called when user picks Log from the help menu
2511 @SuppressWarnings("unused")
2512 private void logger() {
2513 logger.log(logger.HIGH, "Entering NeverNote.logger");
2514 QDialog dialog = new QDialog(this);
2515 QHBoxLayout layout = new QHBoxLayout();
2516 QListWidget textBox = new QListWidget();
2517 layout.addWidget(textBox);
2518 textBox.addItems(emitLog);
2520 dialog.setLayout(layout);
2521 dialog.setWindowTitle(tr("Mesasge Log"));
2523 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2525 // Menu option "help/about" was selected
2526 @SuppressWarnings("unused")
2527 private void about() {
2528 logger.log(logger.HIGH, "Entering NeverNote.about");
2529 QMessageBox.about(this,
2530 tr("About NeverNote"),
2531 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2533 +tr("<hr></center>Evernote"
2534 +"An Open Source Evernote Client.<br><br>"
2535 +"Licensed under GPL v2. <br><hr><br>"
2536 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2537 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2538 +"PDFRenderer is licened under the LGPL<br>"
2539 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2540 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2541 +"Jazzy is licened under the LGPL<br>"
2542 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2543 logger.log(logger.HIGH, "Leaving NeverNote.about");
2545 // Hide the entire left hand side
2546 @SuppressWarnings("unused")
2547 private void toggleLeftSide() {
2550 hidden = !menuBar.hideLeftSide.isChecked();
2551 menuBar.hideLeftSide.setChecked(!hidden);
2553 if (notebookTree.isVisible() != hidden)
2554 toggleNotebookWindow();
2555 if (savedSearchTree.isVisible() != hidden)
2556 toggleSavedSearchWindow();
2557 if (tagTree.isVisible() != hidden)
2559 if (attributeTree.isVisible() != hidden)
2560 toggleAttributesWindow();
2561 if (trashTree.isVisible() != hidden)
2562 toggleTrashWindow();
2564 Global.saveWindowVisible("leftPanel", hidden);
2569 //***************************************************************
2570 //***************************************************************
2571 //** These functions deal with the Toolbar
2572 //***************************************************************
2573 //***************************************************************
2574 // Text in the search bar has been cleared
2575 private void searchFieldCleared() {
2578 // This is done because we want to force a reload of
2579 // images. Some images we may want to highlight the text.
2580 readOnlyCache.clear();
2581 inkNoteCache.clear();
2583 QWebSettings.setMaximumPagesInCache(0);
2584 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2586 searchField.setEditText("");
2587 saveNoteColumnPositions();
2588 saveNoteIndexWidth();
2589 noteIndexUpdated(true);
2590 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2591 currentNote = listManager.getNoteIndex().get(0);
2592 currentNoteGuid = currentNote.getGuid();
2594 if (currentNote != null)
2595 loadNoteBrowserInformation(browserWindow);
2597 // text in the search bar changed. We only use this to tell if it was cleared,
2598 // otherwise we trigger off searchFieldChanged.
2599 @SuppressWarnings("unused")
2600 private void searchFieldTextChanged(String text) {
2601 QWebSettings.setMaximumPagesInCache(0);
2602 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2604 if (text.trim().equals("")) {
2605 searchFieldCleared();
2606 if (searchPerformed) {
2608 // This is done because we want to force a reload of
2609 // images. Some images we may want to highlight the text.
2611 readOnlyCache.clear();
2612 inkNoteCache.clear();
2614 listManager.setEnSearch("");
2615 listManager.loadNotesIndex();
2616 refreshEvernoteNote(true);
2617 noteIndexUpdated(false);
2619 searchPerformed = false;
2622 // Text in the toolbar has changed
2623 private void searchFieldChanged() {
2624 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2626 readOnlyCache.clear();
2627 inkNoteCache.clear();
2628 saveNoteColumnPositions();
2629 saveNoteIndexWidth();
2630 String text = searchField.currentText();
2631 listManager.setEnSearch(text.trim());
2632 listManager.loadNotesIndex();
2633 //--->>> noteIndexUpdated(true);
2634 noteIndexUpdated(false);
2635 refreshEvernoteNote(true);
2636 searchPerformed = true;
2637 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2640 // Build the window tool bar
2641 private void setupToolBar() {
2642 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2643 toolBar = addToolBar(tr("Tool Bar"));
2644 menuBar.setupToolBarVisible();
2645 if (!Global.isWindowVisible("toolBar"))
2646 toolBar.setVisible(false);
2648 toolBar.setVisible(true);
2650 prevButton = toolBar.addAction("Previous");
2651 QIcon prevIcon = new QIcon(iconPath+"back.png");
2652 prevButton.setIcon(prevIcon);
2653 prevButton.triggered.connect(this, "previousViewedAction()");
2654 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2656 nextButton = toolBar.addAction("Next");
2657 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2658 nextButton.setIcon(nextIcon);
2659 nextButton.triggered.connect(this, "nextViewedAction()");
2660 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2662 upButton = toolBar.addAction("Up");
2663 QIcon upIcon = new QIcon(iconPath+"up.png");
2664 upButton.setIcon(upIcon);
2665 upButton.triggered.connect(this, "upAction()");
2666 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2669 downButton = toolBar.addAction("Down");
2670 QIcon downIcon = new QIcon(iconPath+"down.png");
2671 downButton.setIcon(downIcon);
2672 downButton.triggered.connect(this, "downAction()");
2673 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2675 synchronizeButton = toolBar.addAction("Synchronize");
2676 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2677 synchronizeIconAngle = 0;
2678 synchronizeButton.triggered.connect(this, "evernoteSync()");
2679 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2681 printButton = toolBar.addAction("Print");
2682 QIcon printIcon = new QIcon(iconPath+"print.png");
2683 printButton.setIcon(printIcon);
2684 printButton.triggered.connect(this, "printNote()");
2685 togglePrintButton(Global.isToolbarButtonVisible("print"));
2687 tagButton = toolBar.addAction("Tag");
2688 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2689 tagButton.setIcon(tagIcon);
2690 tagButton.triggered.connect(browserWindow, "modifyTags()");
2691 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2693 attributeButton = toolBar.addAction("Attributes");
2694 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2695 attributeButton.setIcon(a