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.webkit.QWebPage.WebAction;
132 import com.trolltech.qt.webkit.QWebSettings;
134 import cx.fbn.nevernote.config.InitializationException;
135 import cx.fbn.nevernote.config.StartupConfig;
136 import cx.fbn.nevernote.dialog.AccountDialog;
137 import cx.fbn.nevernote.dialog.ConfigDialog;
138 import cx.fbn.nevernote.dialog.DBEncryptDialog;
139 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
140 import cx.fbn.nevernote.dialog.DatabaseStatus;
141 import cx.fbn.nevernote.dialog.FindDialog;
142 import cx.fbn.nevernote.dialog.IgnoreSync;
143 import cx.fbn.nevernote.dialog.LoginDialog;
144 import cx.fbn.nevernote.dialog.NotebookArchive;
145 import cx.fbn.nevernote.dialog.NotebookEdit;
146 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
147 import cx.fbn.nevernote.dialog.PublishNotebook;
148 import cx.fbn.nevernote.dialog.SavedSearchEdit;
149 import cx.fbn.nevernote.dialog.SetIcon;
150 import cx.fbn.nevernote.dialog.ShareNotebook;
151 import cx.fbn.nevernote.dialog.StackNotebook;
152 import cx.fbn.nevernote.dialog.TagEdit;
153 import cx.fbn.nevernote.dialog.ThumbnailViewer;
154 import cx.fbn.nevernote.dialog.WatchFolder;
155 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
156 import cx.fbn.nevernote.filters.FilterEditorTags;
157 import cx.fbn.nevernote.gui.AttributeTreeWidget;
158 import cx.fbn.nevernote.gui.BrowserWindow;
159 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
160 import cx.fbn.nevernote.gui.ExternalBrowse;
161 import cx.fbn.nevernote.gui.MainMenuBar;
162 import cx.fbn.nevernote.gui.NotebookTreeWidget;
163 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
164 import cx.fbn.nevernote.gui.TableView;
165 import cx.fbn.nevernote.gui.TagTreeWidget;
166 import cx.fbn.nevernote.gui.Thumbnailer;
167 import cx.fbn.nevernote.gui.TrashTreeWidget;
168 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
169 import cx.fbn.nevernote.sql.DatabaseConnection;
170 import cx.fbn.nevernote.sql.WatchFolderRecord;
171 import cx.fbn.nevernote.threads.IndexRunner;
172 import cx.fbn.nevernote.threads.SyncRunner;
173 import cx.fbn.nevernote.threads.ThumbnailRunner;
174 import cx.fbn.nevernote.utilities.AESEncrypter;
175 import cx.fbn.nevernote.utilities.ApplicationLogger;
176 import cx.fbn.nevernote.utilities.FileImporter;
177 import cx.fbn.nevernote.utilities.FileUtils;
178 import cx.fbn.nevernote.utilities.ListManager;
179 import cx.fbn.nevernote.utilities.SyncTimes;
180 import cx.fbn.nevernote.xml.ExportData;
181 import cx.fbn.nevernote.xml.ImportData;
182 import cx.fbn.nevernote.xml.NoteFormatter;
185 public class NeverNote extends QMainWindow{
187 QStatusBar statusBar; // Application status bar
189 DatabaseConnection conn;
191 MainMenuBar menuBar; // Main menu bar
192 FindDialog find; // Text search in note dialog
193 List<String> emitLog; // Messages displayed in the status bar;
194 QSystemTrayIcon trayIcon; // little tray icon
195 QMenu trayMenu; // System tray menu
196 QAction trayExitAction; // Exit the application
197 QAction trayShowAction; // toggle the show/hide action
198 QAction trayAddNoteAction; // Add a note from the system tray
200 NotebookTreeWidget notebookTree; // List of notebooks
201 AttributeTreeWidget attributeTree; // List of note attributes
202 TagTreeWidget tagTree; // list of user created tags
203 SavedSearchTreeWidget savedSearchTree; // list of saved searches
204 TrashTreeWidget trashTree; // Trashcan
205 TableView noteTableView; // List of notes (the widget).
207 public BrowserWindow browserWindow; // Window containing browser & labels
208 public QToolBar toolBar; // The tool bar under the menu
209 QComboBox searchField; // search filter bar on the toolbar;
210 boolean searchPerformed = false; // Search was done?
211 QuotaProgressBar quotaBar; // The current quota usage
213 ApplicationLogger logger;
214 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
215 List<String> selectedTagGUIDs; // List of selected tag GUIDs
216 List<String> selectedNoteGUIDs; // List of selected notes
217 String selectedSavedSearchGUID; // Currently selected saved searches
218 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
220 NoteFilter filter; // Note filter
221 String currentNoteGuid; // GUID of the current note
222 Note currentNote; // The currently viewed note
223 boolean noteDirty; // Has the note been changed?
224 boolean inkNote; // if this is an ink note, it is read only
225 boolean readOnly; // Is this note read-only?
228 ListManager listManager; // DB runnable task
230 List<QTemporaryFile> tempFiles; // Array of temporary files;
232 QTimer indexTimer; // timer to start the index thread
233 IndexRunner indexRunner; // thread to index notes
236 QTimer syncTimer; // Sync on an interval
237 QTimer syncDelayTimer; // Sync delay to free up database
238 SyncRunner syncRunner; // thread to do a sync.
239 QThread syncThread; // Thread which talks to evernote
240 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
241 QThread thumbnailThread; // Thread that generates pretty pictures
242 QTimer saveTimer; // Timer to save note contents
244 QTimer authTimer; // Refresh authentication
245 QTimer externalFileSaveTimer; // Save files altered externally
246 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
247 List<String> externalFiles; // External files to save later
248 List<String> importFilesKeep; // Auto-import files to save later
249 List<String> importFilesDelete; // Auto-import files to save later
251 int indexTime; // how often to try and index
252 boolean indexRunning; // Is indexing running?
253 boolean indexDisabled; // Is indexing disabled?
255 int syncThreadsReady; // number of sync threads that are free
256 int syncTime; // Sync interval
257 boolean syncRunning; // Is sync running?
258 boolean automaticSync; // do sync automatically?
259 QTreeWidgetItem attributeTreeSelected;
261 QAction prevButton; // Go to the previous item viewed
262 QAction nextButton; // Go to the next item in the history
263 QAction downButton; // Go to the next item in the list
264 QAction upButton; // Go to the prev. item in the list;
265 QAction synchronizeButton; // Synchronize with Evernote
266 QAction allNotesButton; // Reset & view all notes
267 QTimer synchronizeAnimationTimer; // Timer to change animation button
268 int synchronizeIconAngle; // Used to rotate sync icon
269 QAction printButton; // Print Button
270 QAction tagButton; // Tag edit button
271 QAction attributeButton; // Attribute information button
272 QAction emailButton; // Email button
273 QAction deleteButton; // Delete button
274 QAction newButton; // new Note Button;
275 QSpinBox zoomSpinner; // Zoom zoom
276 QAction searchClearButton; // Clear the search field
278 QSplitter mainLeftRightSplitter; // main splitter for left/right side
279 QSplitter leftSplitter1; // first left hand splitter
280 QSplitter browserIndexSplitter; // splitter between note index & note text
282 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
283 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
284 List<String> importedFiles; // History of imported files (so we don't import twice)
286 OnlineNoteHistory historyWindow; // online history window
287 List<NoteVersionId> versions; // history versions
289 QTimer threadMonitorTimer; // Timer to watch threads.
290 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
291 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
292 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
293 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
294 int tagDeadCount=0; // number of consecutive dead times for the tag thread
295 int trashDeadCount=0; // number of consecutive dead times for the trash thread
296 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
298 HashMap<String, String> noteCache; // Cash of note content
299 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
300 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
301 List<String> historyGuids; // GUIDs of previously viewed items
302 int historyPosition; // Position within the viewed items
303 boolean fromHistory; // Is this from the history queue?
304 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
305 List<Thumbnailer> thumbGenerators; // generate preview image
306 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
307 boolean encryptOnShutdown; // should I encrypt when I close?
308 boolean decryptOnShutdown; // should I decrypt on shutdown;
309 String encryptCipher; // What cipher should I use?
310 Signal0 minimizeToTray;
311 boolean windowMaximized = false; // Keep track of the window state for restores
312 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
313 List<QPixmap> syncIcons; // Array of icons used in sync animation
314 private boolean closeAction = false; // Used to say when to close or when to minimize
315 private static Logger log = Logger.getLogger(NeverNote.class);
318 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
321 //***************************************************************
322 //***************************************************************
323 //** Constructor & main entry point
324 //***************************************************************
325 //***************************************************************
326 // Application Constructor
327 @SuppressWarnings("static-access")
328 public NeverNote(DatabaseConnection dbConn) {
330 if (conn.getConnection() == null) {
331 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
332 "is accessing the database or NeverNote is already running.\n\n" +
333 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
335 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
339 thread().setPriority(Thread.MAX_PRIORITY);
341 logger = new ApplicationLogger("nevernote.log");
342 logger.log(logger.HIGH, "Starting Application");
344 decryptOnShutdown = false;
345 encryptOnShutdown = false;
346 conn.checkDatabaseVersion();
350 // Start building the invalid XML tables
351 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
352 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
354 for (int i=0; i<elements.size(); i++) {
355 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
358 logger.log(logger.EXTREME, "Starting GUI build");
360 QTranslator nevernoteTranslator = new QTranslator();
361 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
362 QApplication.instance().installTranslator(nevernoteTranslator);
364 Global.originalPalette = QApplication.palette();
365 QApplication.setStyle(Global.getStyle());
366 if (Global.useStandardPalette())
367 QApplication.setPalette(QApplication.style().standardPalette());
368 setWindowTitle("NeverNote");
370 mainLeftRightSplitter = new QSplitter();
371 setCentralWidget(mainLeftRightSplitter);
372 leftSplitter1 = new QSplitter();
373 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
375 browserIndexSplitter = new QSplitter();
376 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
378 //* Setup threads & thread timers
379 int indexRunnerCount = Global.getIndexThreads();
380 indexRunnerCount = 1;
381 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
383 logger.log(logger.EXTREME, "Building list manager");
384 listManager = new ListManager(conn, logger);
386 logger.log(logger.EXTREME, "Building index runners & timers");
387 indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
388 indexThread = new QThread(indexRunner, "Index Thread");
389 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
392 synchronizeAnimationTimer = new QTimer();
393 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
395 indexTimer = new QTimer();
396 indexTime = 1000*Global.getIndexThreadSleepInterval();
397 indexTimer.start(indexTime); // Start indexing timer
398 indexTimer.timeout.connect(this, "indexTimer()");
399 indexDisabled = false;
400 indexRunning = false;
402 logger.log(logger.EXTREME, "Setting sync thread & timers");
404 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
405 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
406 syncTimer = new QTimer();
407 syncTimer.timeout.connect(this, "syncTimer()");
408 syncRunner.status.message.connect(this, "setMessage(String)");
409 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
410 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
413 automaticSync = true;
414 syncTimer.start(syncTime*60*1000);
416 automaticSync = false;
419 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
420 syncThread = new QThread(syncRunner, "Synchronization Thread");
424 logger.log(logger.EXTREME, "Starting thumnail thread");
425 pdfReadyQueue = new ArrayList<String>();
426 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
427 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
428 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
429 thumbnailThread.start();
430 thumbGenerators = new ArrayList<Thumbnailer>();
431 thumbnailTimer = new QTimer();
432 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
434 thumbnailTimer.setInterval(60*1000); // Thumbnail every minute
435 thumbnailTimer.start();
437 logger.log(logger.EXTREME, "Starting authentication timer");
438 authTimer = new QTimer();
439 authTimer.timeout.connect(this, "authTimer()");
440 authTimer.start(1000*60*15);
441 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
443 logger.log(logger.EXTREME, "Setting save note timer");
444 saveTimer = new QTimer();
445 saveTimer.timeout.connect(this, "saveNote()");
446 if (Global.getAutoSaveInterval() > 0) {
447 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
450 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
452 logger.log(logger.EXTREME, "Starting external file monitor timer");
453 externalFileSaveTimer = new QTimer();
454 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
455 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
456 externalFiles = new ArrayList<String>();
457 importFilesDelete = new ArrayList<String>();
458 importFilesKeep = new ArrayList<String>();
459 externalFileSaveTimer.start();
461 notebookTree = new NotebookTreeWidget(conn);
462 attributeTree = new AttributeTreeWidget();
463 tagTree = new TagTreeWidget(conn);
464 savedSearchTree = new SavedSearchTreeWidget();
465 trashTree = new TrashTreeWidget();
466 noteTableView = new TableView(logger, listManager);
468 QGridLayout leftGrid = new QGridLayout();
469 leftSplitter1.setLayout(leftGrid);
470 leftGrid.addWidget(notebookTree, 1, 1);
471 leftGrid.addWidget(tagTree,2,1);
472 leftGrid.addWidget(attributeTree,3,1);
473 leftGrid.addWidget(savedSearchTree,4,1);
474 leftGrid.addWidget(trashTree, 5, 1);
476 // Setup the browser window
477 noteCache = new HashMap<String,String>();
478 readOnlyCache = new HashMap<String, Boolean>();
479 inkNoteCache = new HashMap<String, Boolean>();
480 browserWindow = new BrowserWindow(conn);
482 mainLeftRightSplitter.addWidget(leftSplitter1);
483 mainLeftRightSplitter.addWidget(browserIndexSplitter);
485 if (Global.getListView() == Global.View_List_Wide) {
486 browserIndexSplitter.addWidget(noteTableView);
487 browserIndexSplitter.addWidget(browserWindow);
489 mainLeftRightSplitter.addWidget(noteTableView);
490 mainLeftRightSplitter.addWidget(browserWindow);
493 searchField = new QComboBox();
494 searchField.setEditable(true);
495 searchField.activatedIndex.connect(this, "searchFieldChanged()");
496 searchField.setDuplicatesEnabled(false);
497 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
499 quotaBar = new QuotaProgressBar();
501 // Setup the thumbnail viewer
502 thumbnailViewer = new ThumbnailViewer();
503 thumbnailViewer.upArrow.connect(this, "upAction()");
504 thumbnailViewer.downArrow.connect(this, "downAction()");
505 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
506 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
508 //Setup external browser manager
509 externalWindows = new HashMap<String, ExternalBrowse>();
511 listManager.loadNotesIndex();
512 initializeNotebookTree();
514 initializeSavedSearchTree();
515 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
516 attributeTreeSelected = null;
517 initializeNoteTable();
519 selectedNoteGUIDs = new ArrayList<String>();
520 statusBar = new QStatusBar();
521 setStatusBar(statusBar);
522 menuBar = new MainMenuBar(this);
523 emitLog = new ArrayList<String>();
525 tagTree.setDeleteAction(menuBar.tagDeleteAction);
526 tagTree.setEditAction(menuBar.tagEditAction);
527 tagTree.setAddAction(menuBar.tagAddAction);
528 tagTree.setIconAction(menuBar.tagIconAction);
529 tagTree.setVisible(Global.isWindowVisible("tagTree"));
530 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
531 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
532 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
534 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
535 notebookTree.setEditAction(menuBar.notebookEditAction);
536 notebookTree.setAddAction(menuBar.notebookAddAction);
537 notebookTree.setIconAction(menuBar.notebookIconAction);
538 notebookTree.setStackAction(menuBar.notebookStackAction);
539 notebookTree.setPublishAction(menuBar.notebookPublishAction);
540 notebookTree.setShareAction(menuBar.notebookShareAction);
541 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
542 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
543 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
544 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
545 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
547 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
548 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
549 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
550 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
551 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
552 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
553 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
555 noteTableView.setAddAction(menuBar.noteAdd);
556 noteTableView.setDeleteAction(menuBar.noteDelete);
557 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
558 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
559 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
560 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
561 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
562 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
563 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
564 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
565 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
567 quotaBar.setMouseClickAction(menuBar.accountAction);
570 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
571 trashTree.setEmptyAction(menuBar.emptyTrashAction);
572 trashTree.setVisible(Global.isWindowVisible("trashTree"));
573 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
574 trashTree.updateCounts(listManager.getTrashCount());
575 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
576 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
578 noteTableView.setVisible(Global.isWindowVisible("noteList"));
579 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
581 if (!Global.isWindowVisible("editorButtonBar"))
582 toggleEditorButtonBar();
583 if (!Global.isWindowVisible("leftPanel"))
584 menuBar.hideLeftSide.setChecked(true);
585 if (Global.isWindowVisible("noteInformation"))
586 toggleNoteInformation();
590 find = new FindDialog();
591 find.getOkButton().clicked.connect(this, "doFindText()");
593 // Setup the tray icon menu bar
594 trayShowAction = new QAction("Show/Hide", this);
595 trayExitAction = new QAction("Exit", this);
596 trayAddNoteAction = new QAction("Add Note", this);
598 trayExitAction.triggered.connect(this, "closeNeverNote()");
599 trayAddNoteAction.triggered.connect(this, "addNote()");
600 trayShowAction.triggered.connect(this, "trayToggleVisible()");
602 trayMenu = new QMenu(this);
603 trayMenu.addAction(trayAddNoteAction);
604 trayMenu.addAction(trayShowAction);
605 trayMenu.addAction(trayExitAction);
608 trayIcon = new QSystemTrayIcon(this);
609 trayIcon.setToolTip("NeverNote");
610 trayIcon.setContextMenu(trayMenu);
611 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
614 currentNoteGuid = Global.getLastViewedNoteGuid();
615 historyGuids = new ArrayList<String>();
619 if (!currentNoteGuid.trim().equals("")) {
620 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
623 noteIndexUpdated(true);
625 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
626 if (menuBar.showEditorBar.isChecked())
627 showEditorButtons(browserWindow);
628 tagIndexUpdated(true);
629 savedSearchIndexUpdated();
630 notebookIndexUpdated();
632 setupSyncSignalListeners();
633 setupBrowserSignalListeners();
634 setupIndexListeners();
637 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
638 tagTree.showAllTags(true);
640 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
641 setWindowIcon(appIcon);
642 trayIcon.setIcon(appIcon);
643 if (Global.showTrayIcon())
648 scrollToGuid(currentNoteGuid);
649 if (Global.automaticLogin()) {
651 if (Global.isConnected)
654 setupFolderImports();
657 restoreWindowState(true);
659 if (Global.mimicEvernoteInterface) {
660 notebookTree.selectGuid("");
663 threadMonitorTimer = new QTimer();
664 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
665 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
667 historyGuids.add(currentNoteGuid);
670 menuBar.blockSignals(true);
671 menuBar.narrowListView.blockSignals(true);
672 menuBar.wideListView.blockSignals(true);
673 if (Global.getListView() == Global.View_List_Narrow) {
674 menuBar.narrowListView.setChecked(true);
677 menuBar.wideListView.setChecked(true);
679 menuBar.blockSignals(false);
680 menuBar.narrowListView.blockSignals(false);
681 menuBar.wideListView.blockSignals(false);
683 if (Global.getListView() == Global.View_List_Wide) {
684 browserIndexSplitter.addWidget(noteTableView);
685 browserIndexSplitter.addWidget(browserWindow);
687 mainLeftRightSplitter.addWidget(noteTableView);
688 mainLeftRightSplitter.addWidget(browserWindow);
691 int sortCol = Global.getSortColumn();
692 int sortOrder = Global.getSortOrder();
693 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
699 public static void main(String[] args) {
700 log.setLevel(Level.FATAL);
701 QApplication.initialize(args);
702 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
703 QSplashScreen splash = new QSplashScreen(pixmap);
706 DatabaseConnection dbConn;
709 initializeGlobalSettings(args);
711 showSplash = Global.isWindowVisible("SplashScreen");
715 dbConn = setupDatabaseConnection();
717 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
718 Global.getFileManager().purgeResDirectory(true);
720 } catch (InitializationException e) {
723 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
727 NeverNote application = new NeverNote(dbConn);
729 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
730 if (Global.startMinimized())
731 application.showMinimized();
733 if (Global.wasWindowMaximized())
734 application.showMaximized();
740 splash.finish(application);
742 System.out.println("Goodbye.");
747 * Open the internal database, or create if not present
749 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
751 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
752 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
754 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
755 boolean dbExists = f.exists();
757 Global.setDatabaseUrl("");
759 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
760 boolean goodCheck = false;
762 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
764 if (!dialog.okPressed())
766 Global.cipherPassword = dialog.getPassword();
767 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
768 Global.getDatabaseUserPassword(), Global.cipherPassword);
771 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
775 // Encrypt the database upon shutdown
776 private void encryptOnShutdown() {
777 String dbPath= Global.getFileManager().getDbDirPath("");
778 String dbName = "NeverNote";
780 Statement st = conn.getConnection().createStatement();
781 st.execute("shutdown");
782 if (QMessageBox.question(this, "Are you sure",
783 "Are you sure you wish to encrypt the database?",
784 QMessageBox.StandardButton.Yes,
785 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
786 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
787 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
788 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
790 } catch (SQLException e) {
795 // Decrypt the database upon shutdown
796 private void decryptOnShutdown() {
797 String dbPath= Global.getFileManager().getDbDirPath("");
798 String dbName = "NeverNote";
800 Statement st = conn.getConnection().createStatement();
801 st.execute("shutdown");
802 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
803 encryptCipher = "AES";
805 encryptCipher = "XTEA";
806 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
807 "Are you sure you wish to decrypt the database?"),
808 QMessageBox.StandardButton.Yes,
809 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
811 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
812 Global.setDatabaseUrl("");
813 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
815 } catch (SQLException e) {
820 * Encrypt/Decrypt the local database
822 public void doDatabaseEncrypt() {
823 // The database is not currently encrypted
824 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
825 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
826 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
827 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
828 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
829 "Do you wish to proceed?"),
830 QMessageBox.StandardButton.Yes,
831 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
834 DBEncryptDialog dialog = new DBEncryptDialog();
836 if (dialog.okPressed()) {
837 Global.cipherPassword = dialog.getPassword();
838 encryptOnShutdown = true;
839 encryptCipher = dialog.getEncryptionMethod();
842 DBEncryptDialog dialog = new DBEncryptDialog();
843 dialog.setWindowTitle("Database Decryption");
844 dialog.hideEncryption();
846 if (dialog.okPressed()) {
847 if (!dialog.getPassword().equals(Global.cipherPassword)) {
848 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
851 decryptOnShutdown = true;
858 private static void initializeGlobalSettings(String[] args) throws InitializationException {
859 StartupConfig startupConfig = new StartupConfig();
861 for (String arg : args) {
862 String lower = arg.toLowerCase();
863 if (lower.startsWith("--name="))
864 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
865 if (lower.startsWith("--home="))
866 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
867 if (lower.startsWith("--disable-viewing"))
868 startupConfig.setDisableViewing(true);
870 Global.setup(startupConfig);
875 public void closeEvent(QCloseEvent event) {
876 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
881 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
884 if (currentNote!= null & browserWindow!=null) {
885 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
886 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
889 setMessage(tr("Beginning shutdown."));
891 // Close down external windows
892 Collection<ExternalBrowse> windows = externalWindows.values();
893 Iterator<ExternalBrowse> iterator = windows.iterator();
894 while (iterator.hasNext()) {
895 ExternalBrowse browser = iterator.next();
896 browser.windowClosing.disconnect();
901 externalFileEditedSaver();
902 if (Global.isConnected && Global.synchronizeOnClose()) {
903 setMessage(tr("Performing synchronization before closing."));
904 syncRunner.addWork("SYNC");
906 setMessage("Closing Program.");
907 threadMonitorTimer.stop();
909 syncRunner.addWork("STOP");
910 syncRunner.keepRunning = false;
911 thumbnailRunner.addWork("STOP");
912 syncRunner.keepRunning = false;
913 indexRunner.addWork("STOP");
914 syncRunner.keepRunning = false;
919 if (tempFiles != null)
922 browserWindow.noteSignal.tagsChanged.disconnect();
923 browserWindow.noteSignal.titleChanged.disconnect();
924 browserWindow.noteSignal.noteChanged.disconnect();
925 browserWindow.noteSignal.notebookChanged.disconnect();
926 browserWindow.noteSignal.createdDateChanged.disconnect();
927 browserWindow.noteSignal.alteredDateChanged.disconnect();
928 syncRunner.searchSignal.listChanged.disconnect();
929 syncRunner.tagSignal.listChanged.disconnect();
930 syncRunner.notebookSignal.listChanged.disconnect();
931 syncRunner.noteIndexSignal.listChanged.disconnect();
934 Global.saveWindowVisible("toolBar", toolBar.isVisible());
935 saveNoteColumnPositions();
936 saveNoteIndexWidth();
938 int width = notebookTree.columnWidth(0);
939 Global.setColumnWidth("notebookTreeName", width);
940 width = tagTree.columnWidth(0);
941 Global.setColumnWidth("tagTreeName", width);
943 Global.saveWindowMaximized(isMaximized());
944 Global.saveCurrentNoteGuid(currentNoteGuid);
946 int sortCol = noteTableView.proxyModel.sortColumn();
947 int sortOrder = noteTableView.proxyModel.sortOrder().value();
948 Global.setSortColumn(sortCol);
949 Global.setSortOrder(sortOrder);
953 Global.keepRunning = false;
955 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
956 if (indexRunner.thread().isAlive())
957 indexRunner.thread().join(50);
958 if (!indexRunner.thread().isAlive())
959 logger.log(logger.MEDIUM, "Index thread has stopped");
961 logger.log(logger.MEDIUM, "Index thread still running - bypassing");
962 } catch (InterruptedException e1) {
963 e1.printStackTrace();
965 if (!syncRunner.isIdle()) {
967 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
969 logger.log(logger.MEDIUM, "Sync thread has stopped");
970 } catch (InterruptedException e1) {
971 e1.printStackTrace();
975 if (encryptOnShutdown) {
978 if (decryptOnShutdown) {
981 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
984 @SuppressWarnings("unused")
985 private void closeNeverNote() {
989 public void setMessage(String s) {
990 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
991 logger.log(logger.HIGH, "Message: " +s);
992 statusBar.showMessage(s);
994 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
997 private void waitCursor(boolean wait) {
999 if (QApplication.overrideCursor() == null)
1000 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1003 while (QApplication.overrideCursor() != null)
1004 QApplication.restoreOverrideCursor();
1008 private void setupIndexListeners() {
1009 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1010 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1011 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1012 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1014 private void setupSyncSignalListeners() {
1015 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1016 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1017 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1018 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1019 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1021 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1022 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1023 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1025 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1026 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1027 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1028 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1030 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1033 private void setupBrowserSignalListeners() {
1034 setupBrowserWindowListeners(browserWindow, true);
1037 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1038 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1039 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1040 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1041 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1042 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1043 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1044 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1045 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1046 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1047 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1048 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1049 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1050 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1051 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1052 if (master) browser.focusLost.connect(this, "saveNote()");
1053 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1056 //***************************************************************
1057 //***************************************************************
1058 //* Settings and look & feel
1059 //***************************************************************
1060 //***************************************************************
1061 @SuppressWarnings("unused")
1062 private void settings() {
1063 logger.log(logger.HIGH, "Entering NeverNote.settings");
1064 saveNoteColumnPositions();
1065 saveNoteIndexWidth();
1067 ConfigDialog settings = new ConfigDialog(this);
1068 String dateFormat = Global.getDateFormat();
1069 String timeFormat = Global.getTimeFormat();
1071 indexTime = 1000*Global.getIndexThreadSleepInterval();
1072 indexTimer.start(indexTime); // reset indexing timer
1075 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1076 if (Global.showTrayIcon())
1081 if (menuBar.showEditorBar.isChecked())
1082 showEditorButtons(browserWindow);
1084 // Reset the save timer
1085 if (Global.getAutoSaveInterval() > 0)
1086 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1090 // This is a hack to force a reload of the index in case the date or time changed.
1091 // if (!dateFormat.equals(Global.getDateFormat()) ||
1092 // !timeFormat.equals(Global.getTimeFormat())) {
1094 readOnlyCache.clear();
1095 inkNoteCache.clear();
1096 noteIndexUpdated(true);
1099 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1101 // Restore things to the way they were
1102 private void restoreWindowState(boolean mainWindow) {
1103 // We need to name things or this doesn't work.
1104 setObjectName("NeverNote");
1105 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1106 browserIndexSplitter.setObjectName("browserIndexSplitter");
1107 leftSplitter1.setObjectName("leftSplitter1");
1109 // Restore the actual positions.
1111 restoreGeometry(Global.restoreGeometry(objectName()));
1112 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1113 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1114 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1117 // Save window positions for the next start
1118 private void saveWindowState() {
1119 Global.saveGeometry(objectName(), saveGeometry());
1120 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1121 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1122 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1124 // Load the style sheet
1125 private void loadStyleSheet() {
1126 String fileName = Global.getFileManager().getQssDirPath("default.qss");
1127 QFile file = new QFile(fileName);
1128 file.open(OpenModeFlag.ReadOnly);
1129 String styleSheet = file.readAll().toString();
1131 setStyleSheet(styleSheet);
1133 // Save column positions for the next time
1134 private void saveNoteColumnPositions() {
1135 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1136 Global.setColumnPosition("noteTableCreationPosition", position);
1137 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1138 Global.setColumnPosition("noteTableTagPosition", position);
1139 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1140 Global.setColumnPosition("noteTableNotebookPosition", position);
1141 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1142 Global.setColumnPosition("noteTableChangedPosition", position);
1143 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1144 Global.setColumnPosition("noteTableAuthorPosition", position);
1145 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1146 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1147 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1148 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1149 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1150 Global.setColumnPosition("noteTableTitlePosition", position);
1151 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1152 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1153 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1154 Global.setColumnPosition("noteTableGuidPosition", position);
1155 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1156 Global.setColumnPosition("noteTableThumbnailPosition", position);
1159 // Save column widths for the next time
1160 private void saveNoteIndexWidth() {
1162 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1163 Global.setColumnWidth("noteTableCreationPosition", width);
1164 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1165 Global.setColumnWidth("noteTableChangedPosition", width);
1166 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1167 Global.setColumnWidth("noteTableGuidPosition", width);
1168 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1169 Global.setColumnWidth("noteTableNotebookPosition", width);
1170 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1171 Global.setColumnWidth("noteTableTagPosition", width);
1172 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1173 Global.setColumnWidth("noteTableTitlePosition", width);
1174 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1175 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1176 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1177 Global.setColumnWidth("noteTableAuthorPosition", width);
1178 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1179 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1180 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1181 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1182 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1183 Global.setColumnWidth("noteTableThumbnailPosition", width);
1184 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1185 Global.setColumnWidth("noteTableGuidPosition", width);
1189 //***************************************************************
1190 //***************************************************************
1191 //** These functions deal with Notebook menu items
1192 //***************************************************************
1193 //***************************************************************
1194 // Setup the tree containing the user's notebooks.
1195 private void initializeNotebookTree() {
1196 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1197 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1198 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1199 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1200 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1202 // Listener when a notebook is selected
1203 private void notebookTreeSelection() {
1204 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1207 clearAttributeFilter();
1208 clearSavedSearchFilter();
1209 if (Global.mimicEvernoteInterface) {
1211 searchField.clear();
1213 menuBar.noteRestoreAction.setVisible(false);
1214 menuBar.notebookEditAction.setEnabled(true);
1215 menuBar.notebookDeleteAction.setEnabled(true);
1216 menuBar.notebookPublishAction.setEnabled(true);
1217 menuBar.notebookShareAction.setEnabled(true);
1218 menuBar.notebookIconAction.setEnabled(true);
1219 menuBar.notebookStackAction.setEnabled(true);
1220 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1221 selectedNotebookGUIDs.clear();
1223 String stackName = "";
1224 if (selections.size() > 0) {
1225 guid = (selections.get(0).text(2));
1226 stackName = selections.get(0).text(0);
1228 if (!Global.mimicEvernoteInterface) {
1229 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1230 if (selections.size()==0) {
1231 selectedNotebookGUIDs.clear();
1232 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1233 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1235 menuBar.notebookEditAction.setEnabled(false);
1236 menuBar.notebookDeleteAction.setEnabled(false);
1237 menuBar.notebookStackAction.setEnabled(false);
1238 menuBar.notebookIconAction.setEnabled(false);
1241 if (!guid.equals("") && !guid.equals("STACK")) {
1242 selectedNotebookGUIDs.add(guid);
1243 menuBar.notebookIconAction.setEnabled(true);
1245 menuBar.notebookIconAction.setEnabled(true);
1246 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1247 Notebook book = listManager.getNotebookIndex().get(j);
1248 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1249 selectedNotebookGUIDs.add(book.getGuid());
1252 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1253 listManager.loadNotesIndex();
1254 noteIndexUpdated(false);
1255 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1258 private void clearNotebookFilter() {
1259 notebookTree.blockSignals(true);
1260 notebookTree.clearSelection();
1261 menuBar.noteRestoreAction.setVisible(false);
1262 menuBar.notebookEditAction.setEnabled(false);
1263 menuBar.notebookDeleteAction.setEnabled(false);
1264 selectedNotebookGUIDs.clear();
1265 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1266 notebookTree.blockSignals(false);
1268 // Triggered when the notebook DB has been updated
1269 private void notebookIndexUpdated() {
1270 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1272 // Get the possible icons
1273 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1274 notebookTree.setIcons(icons);
1276 if (selectedNotebookGUIDs == null)
1277 selectedNotebookGUIDs = new ArrayList<String>();
1278 List<Notebook> books = conn.getNotebookTable().getAll();
1279 for (int i=books.size()-1; i>=0; i--) {
1280 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1281 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1283 j=listManager.getArchiveNotebookIndex().size();
1289 listManager.countNotebookResults(listManager.getNoteIndex());
1290 notebookTree.blockSignals(true);
1291 notebookTree.load(books, listManager.getLocalNotebooks());
1292 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1293 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1295 selectedNotebookGUIDs.remove(i);
1297 notebookTree.blockSignals(false);
1299 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1301 // Show/Hide note information
1302 private void toggleNotebookWindow() {
1303 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1304 if (notebookTree.isVisible())
1305 notebookTree.hide();
1307 notebookTree.show();
1308 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1309 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1310 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1312 // Add a new notebook
1313 @SuppressWarnings("unused")
1314 private void addNotebook() {
1315 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1316 NotebookEdit edit = new NotebookEdit();
1317 edit.setNotebooks(listManager.getNotebookIndex());
1320 if (!edit.okPressed())
1323 Calendar currentTime = new GregorianCalendar();
1324 Long l = new Long(currentTime.getTimeInMillis());
1325 String randint = new String(Long.toString(l));
1327 Notebook newBook = new Notebook();
1328 newBook.setUpdateSequenceNum(0);
1329 newBook.setGuid(randint);
1330 newBook.setName(edit.getNotebook());
1331 newBook.setServiceCreated(new Date().getTime());
1332 newBook.setServiceUpdated(new Date().getTime());
1333 newBook.setDefaultNotebook(false);
1334 newBook.setPublished(false);
1336 listManager.getNotebookIndex().add(newBook);
1338 listManager.getLocalNotebooks().add(newBook.getGuid());
1339 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1340 notebookIndexUpdated();
1341 listManager.countNotebookResults(listManager.getNoteIndex());
1342 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1343 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1345 // Edit an existing notebook
1346 @SuppressWarnings("unused")
1347 private void stackNotebook() {
1348 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1349 StackNotebook edit = new StackNotebook();
1351 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1352 QTreeWidgetItem currentSelection;
1353 for (int i=0; i<selections.size(); i++) {
1354 currentSelection = selections.get(0);
1355 String guid = currentSelection.text(2);
1356 if (guid.equalsIgnoreCase("")) {
1357 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1360 if (guid.equalsIgnoreCase("STACK")) {
1361 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1366 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1371 if (!edit.okPressed())
1374 String stack = edit.getStackName();
1376 for (int i=0; i<selections.size(); i++) {
1377 currentSelection = selections.get(i);
1378 String guid = currentSelection.text(2);
1379 listManager.updateNotebookStack(guid, stack);
1381 notebookIndexUpdated();
1382 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1384 // Edit an existing notebook
1385 @SuppressWarnings("unused")
1386 private void editNotebook() {
1387 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1388 NotebookEdit edit = new NotebookEdit();
1390 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1391 QTreeWidgetItem currentSelection;
1392 currentSelection = selections.get(0);
1393 edit.setNotebook(currentSelection.text(0));
1395 String guid = currentSelection.text(2);
1396 if (!guid.equalsIgnoreCase("STACK")) {
1397 edit.setTitle(tr("Edit Notebook"));
1398 edit.setNotebooks(listManager.getNotebookIndex());
1399 edit.setLocalCheckboxEnabled(false);
1400 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1401 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1402 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1403 i=listManager.getNotebookIndex().size();
1407 edit.setTitle(tr("Edit Stack"));
1408 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1409 edit.hideLocalCheckbox();
1410 edit.hideDefaultCheckbox();
1415 if (!edit.okPressed())
1419 if (guid.equalsIgnoreCase("STACK")) {
1420 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1421 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1422 if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1423 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1425 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1426 currentSelection.setText(0, edit.getNotebook());
1430 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1431 currentSelection.setText(0, edit.getNotebook());
1433 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1434 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1435 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1436 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1437 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1438 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1439 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1440 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1442 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1443 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1444 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1445 linkedNotebook.setShareName(edit.getNotebook());
1446 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1448 i=listManager.getNotebookIndex().size();
1452 // Build a list of non-closed notebooks
1453 List<Notebook> nbooks = new ArrayList<Notebook>();
1454 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1455 boolean found=false;
1456 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1457 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1461 nbooks.add(listManager.getNotebookIndex().get(i));
1465 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1466 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1467 browserWindow.setNotebookList(filteredBooks);
1468 Iterator<String> set = externalWindows.keySet().iterator();
1469 while(set.hasNext())
1470 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1471 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1473 // Publish a notebook
1474 @SuppressWarnings("unused")
1475 private void publishNotebook() {
1476 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1477 QTreeWidgetItem currentSelection;
1478 currentSelection = selections.get(0);
1479 String guid = currentSelection.text(2);
1481 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1486 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1487 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1488 n = listManager.getNotebookIndex().get(i);
1490 i = listManager.getNotebookIndex().size();
1496 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1499 if (!publish.okClicked())
1502 Publishing p = publish.getPublishing();
1503 boolean isPublished = !publish.isStopPressed();
1504 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1505 n.setPublished(isPublished);
1507 listManager.getNotebookIndex().set(position, n);
1508 notebookIndexUpdated();
1510 // Publish a notebook
1511 @SuppressWarnings("unused")
1512 private void shareNotebook() {
1513 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1514 QTreeWidgetItem currentSelection;
1515 currentSelection = selections.get(0);
1516 String guid = currentSelection.text(2);
1518 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1522 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1523 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1524 n = listManager.getNotebookIndex().get(i);
1525 i = listManager.getNotebookIndex().size();
1529 String authToken = null;
1530 if (syncRunner.isConnected)
1531 authToken = syncRunner.authToken;
1532 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1537 // Delete an existing notebook
1538 @SuppressWarnings("unused")
1539 private void deleteNotebook() {
1540 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1541 boolean stacksFound = false;
1542 boolean notebooksFound = false;
1543 boolean assigned = false;
1544 // Check if any notes have this notebook
1545 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1546 for (int i=0; i<selections.size(); i++) {
1547 QTreeWidgetItem currentSelection;
1548 currentSelection = selections.get(i);
1549 String guid = currentSelection.text(2);
1550 if (!guid.equalsIgnoreCase("STACK")) {
1551 notebooksFound = true;
1552 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1553 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1554 if (noteGuid.equals(guid)) {
1556 j=listManager.getNoteIndex().size();
1557 i=selections.size();
1565 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1566 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1570 if (conn.getNotebookTable().getAll().size() == 1) {
1571 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1575 // If all notebooks are clear, verify the delete
1576 String msg1 = new String(tr("Delete selected notebooks?"));
1577 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1578 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1579 " not deleted unless selected?"));
1581 if (stacksFound && notebooksFound)
1583 if (!stacksFound && notebooksFound)
1585 if (stacksFound && !notebooksFound)
1587 if (QMessageBox.question(this, tr("Confirmation"), msg,
1588 QMessageBox.StandardButton.Yes,
1589 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1593 // If confirmed, delete the notebook
1594 for (int i=selections.size()-1; i>=0; i--) {
1595 QTreeWidgetItem currentSelection;
1596 currentSelection = selections.get(i);
1597 String guid = currentSelection.text(2);
1598 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1599 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1600 listManager.renameStack(currentSelection.text(0), "");
1602 conn.getNotebookTable().expungeNotebook(guid, true);
1603 listManager.deleteNotebook(guid);
1607 notebookIndexUpdated();
1608 // notebookTreeSelection();
1609 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1610 // listManager.countNotebookResults(listManager.getNoteIndex());
1611 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1613 // A note's notebook has been updated
1614 @SuppressWarnings("unused")
1615 private void updateNoteNotebook(String guid, String notebookGuid) {
1617 // Update the list manager
1618 listManager.updateNoteNotebook(guid, notebookGuid);
1619 listManager.countNotebookResults(listManager.getNoteIndex());
1620 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1622 // Find the name of the notebook
1623 String notebookName = null;
1624 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1625 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1626 notebookName = listManager.getNotebookIndex().get(i).getName();
1631 // If we found the name, update the browser window
1632 if (notebookName != null) {
1633 updateListNoteNotebook(guid, notebookName);
1634 if (guid.equals(currentNoteGuid)) {
1635 int pos = browserWindow.notebookBox.findText(notebookName);
1637 browserWindow.notebookBox.setCurrentIndex(pos);
1641 // If we're dealing with the current note, then we need to be sure and update the notebook there
1642 if (guid.equals(currentNoteGuid)) {
1643 if (currentNote != null) {
1644 currentNote.setNotebookGuid(notebookGuid);
1648 // Open/close notebooks
1649 @SuppressWarnings("unused")
1650 private void closeNotebooks() {
1651 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1653 if (!na.okClicked())
1657 listManager.getArchiveNotebookIndex().clear();
1659 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1660 String text = na.getClosedBookList().takeItem(i).text();
1661 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1662 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1663 Notebook n = listManager.getNotebookIndex().get(j);
1664 conn.getNotebookTable().setArchived(n.getGuid(),true);
1665 listManager.getArchiveNotebookIndex().add(n);
1666 j=listManager.getNotebookIndex().size();
1671 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1672 String text = na.getOpenBookList().takeItem(i).text();
1673 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1674 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1675 Notebook n = listManager.getNotebookIndex().get(j);
1676 conn.getNotebookTable().setArchived(n.getGuid(),false);
1677 j=listManager.getNotebookIndex().size();
1681 notebookTreeSelection();
1682 listManager.loadNotesIndex();
1683 notebookIndexUpdated();
1684 noteIndexUpdated(false);
1685 reloadTagTree(true);
1686 // noteIndexUpdated(false);
1688 // Build a list of non-closed notebooks
1689 List<Notebook> nbooks = new ArrayList<Notebook>();
1690 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1691 boolean found=false;
1692 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1693 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1697 nbooks.add(listManager.getNotebookIndex().get(i));
1700 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1701 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1702 browserWindow.setNotebookList(filteredBooks);
1704 // Update any external windows
1705 Iterator<String> set = externalWindows.keySet().iterator();
1706 while(set.hasNext())
1707 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1711 // Change the notebook's icon
1712 @SuppressWarnings("unused")
1713 private void setNotebookIcon() {
1714 boolean stackSelected = false;
1715 boolean allNotebookSelected = false;
1717 QTreeWidgetItem currentSelection;
1718 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1719 if (selections.size() == 0)
1722 currentSelection = selections.get(0);
1723 String guid = currentSelection.text(2);
1724 if (guid.equalsIgnoreCase(""))
1725 allNotebookSelected = true;
1726 if (guid.equalsIgnoreCase("STACK"))
1727 stackSelected = true;
1729 QIcon currentIcon = currentSelection.icon(0);
1733 if (!stackSelected && !allNotebookSelected) {
1734 icon = conn.getNotebookTable().getIcon(guid);
1736 dialog = new SetIcon(currentIcon);
1737 dialog.setUseDefaultIcon(true);
1739 dialog = new SetIcon(icon);
1740 dialog.setUseDefaultIcon(false);
1743 if (stackSelected) {
1744 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1746 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1749 dialog = new SetIcon(currentIcon);
1750 dialog.setUseDefaultIcon(true);
1752 dialog = new SetIcon(icon);
1753 dialog.setUseDefaultIcon(false);
1757 if (dialog.okPressed()) {
1758 QIcon newIcon = dialog.getIcon();
1759 if (stackSelected) {
1760 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1761 if (newIcon == null) {
1762 newIcon = new QIcon(iconPath+"books2.png");
1764 currentSelection.setIcon(0,newIcon);
1767 if (allNotebookSelected) {
1768 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1769 if (newIcon == null) {
1770 newIcon = new QIcon(iconPath+"notebook-green.png");
1772 currentSelection.setIcon(0,newIcon);
1775 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1776 if (newIcon == null) {
1777 boolean isPublished = false;;
1778 boolean found = false;
1779 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1780 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1781 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1785 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1787 currentSelection.setIcon(0, newIcon);
1793 //***************************************************************
1794 //***************************************************************
1795 //** These functions deal with Tag menu items
1796 //***************************************************************
1797 //***************************************************************
1798 // Add a new notebook
1799 @SuppressWarnings("unused")
1800 private void addTag() {
1801 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1802 TagEdit edit = new TagEdit();
1803 edit.setTagList(listManager.getTagIndex());
1806 if (!edit.okPressed())
1809 Calendar currentTime = new GregorianCalendar();
1810 Long l = new Long(currentTime.getTimeInMillis());
1811 String randint = new String(Long.toString(l));
1813 Tag newTag = new Tag();
1814 newTag.setUpdateSequenceNum(0);
1815 newTag.setGuid(randint);
1816 newTag.setName(edit.getTag());
1817 conn.getTagTable().addTag(newTag, true);
1818 listManager.getTagIndex().add(newTag);
1819 reloadTagTree(true);
1821 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1823 @SuppressWarnings("unused")
1824 private void reloadTagTree() {
1825 reloadTagTree(false);
1827 private void reloadTagTree(boolean reload) {
1828 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1829 tagIndexUpdated(reload);
1830 boolean filter = false;
1831 listManager.countTagResults(listManager.getNoteIndex());
1832 if (notebookTree.selectedItems().size() > 0
1833 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1835 if (tagTree.selectedItems().size() > 0)
1837 tagTree.showAllTags(!filter);
1838 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1840 // Edit an existing tag
1841 @SuppressWarnings("unused")
1842 private void editTag() {
1843 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1844 TagEdit edit = new TagEdit();
1845 edit.setTitle("Edit Tag");
1846 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1847 QTreeWidgetItem currentSelection;
1848 currentSelection = selections.get(0);
1849 edit.setTag(currentSelection.text(0));
1850 edit.setTagList(listManager.getTagIndex());
1853 if (!edit.okPressed())
1856 String guid = currentSelection.text(2);
1857 currentSelection.setText(0,edit.getTag());
1859 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1860 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1861 listManager.getTagIndex().get(i).setName(edit.getTag());
1862 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1863 updateListTagName(guid);
1864 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1865 browserWindow.setTag(getTagNamesForNote(currentNote));
1866 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1870 browserWindow.setTag(getTagNamesForNote(currentNote));
1871 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1873 // Delete an existing tag
1874 @SuppressWarnings("unused")
1875 private void deleteTag() {
1876 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1878 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1879 QMessageBox.StandardButton.Yes,
1880 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1884 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1885 for (int i=selections.size()-1; i>=0; i--) {
1886 QTreeWidgetItem currentSelection;
1887 currentSelection = selections.get(i);
1888 removeTagItem(currentSelection.text(2));
1890 tagIndexUpdated(true);
1892 listManager.countTagResults(listManager.getNoteIndex());
1893 // tagTree.updateCounts(listManager.getTagCounter());
1894 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1896 // Remove a tag tree item. Go recursively down & remove the children too
1897 private void removeTagItem(String guid) {
1898 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1899 String parent = listManager.getTagIndex().get(j).getParentGuid();
1900 if (parent != null && parent.equals(guid)) {
1901 //Remove this tag's children
1902 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1905 //Now, remove this tag
1906 removeListTagName(guid);
1907 conn.getTagTable().expungeTag(guid, true);
1908 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1909 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1910 listManager.getTagIndex().remove(a);
1915 // Setup the tree containing the user's tags
1916 private void initializeTagTree() {
1917 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1918 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1919 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
1920 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1921 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1922 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1924 // Listener when a tag is selected
1925 private void tagTreeSelection() {
1926 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1929 clearAttributeFilter();
1930 clearSavedSearchFilter();
1932 menuBar.noteRestoreAction.setVisible(false);
1934 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1935 QTreeWidgetItem currentSelection;
1936 selectedTagGUIDs.clear();
1937 for (int i=0; i<selections.size(); i++) {
1938 currentSelection = selections.get(i);
1939 selectedTagGUIDs.add(currentSelection.text(2));
1941 if (selections.size() > 0) {
1942 menuBar.tagEditAction.setEnabled(true);
1943 menuBar.tagDeleteAction.setEnabled(true);
1944 menuBar.tagIconAction.setEnabled(true);
1947 menuBar.tagEditAction.setEnabled(false);
1948 menuBar.tagDeleteAction.setEnabled(false);
1949 menuBar.tagIconAction.setEnabled(true);
1951 listManager.setSelectedTags(selectedTagGUIDs);
1952 listManager.loadNotesIndex();
1953 noteIndexUpdated(false);
1954 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1956 // trigger the tag index to be refreshed
1957 @SuppressWarnings("unused")
1958 private void tagIndexUpdated() {
1959 tagIndexUpdated(true);
1961 private void tagIndexUpdated(boolean reload) {
1962 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1963 if (selectedTagGUIDs == null)
1964 selectedTagGUIDs = new ArrayList<String>();
1966 listManager.reloadTagIndex();
1968 tagTree.blockSignals(true);
1970 tagTree.setIcons(conn.getTagTable().getAllIcons());
1971 tagTree.load(listManager.getTagIndex());
1973 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1974 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1976 selectedTagGUIDs.remove(i);
1978 tagTree.blockSignals(false);
1980 browserWindow.setTag(getTagNamesForNote(currentNote));
1981 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1983 // Show/Hide note information
1984 private void toggleTagWindow() {
1985 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1986 if (tagTree.isVisible())
1990 menuBar.hideTags.setChecked(tagTree.isVisible());
1991 Global.saveWindowVisible("tagTree", tagTree.isVisible());
1992 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1994 // A note's tags have been updated
1995 @SuppressWarnings("unused")
1996 private void updateNoteTags(String guid, List<String> tags) {
1997 // Save any new tags. We'll need them later.
1998 List<String> newTags = new ArrayList<String>();
1999 for (int i=0; i<tags.size(); i++) {
2000 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2001 newTags.add(tags.get(i));
2004 listManager.saveNoteTags(guid, tags);
2005 listManager.countTagResults(listManager.getNoteIndex());
2006 StringBuffer names = new StringBuffer("");
2007 for (int i=0; i<tags.size(); i++) {
2008 names = names.append(tags.get(i));
2009 if (i<tags.size()-1) {
2010 names.append(Global.tagDelimeter + " ");
2013 browserWindow.setTag(names.toString());
2016 // Now, we need to add any new tags to the tag tree
2017 for (int i=0; i<newTags.size(); i++)
2018 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2020 // Get a string containing all tag names for a note
2021 private String getTagNamesForNote(Note n) {
2022 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2023 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2025 StringBuffer buffer = new StringBuffer(100);
2026 Vector<String> v = new Vector<String>();
2027 List<String> guids = n.getTagGuids();
2032 for (int i=0; i<guids.size(); i++) {
2033 v.add(listManager.getTagNameByGuid(guids.get(i)));
2035 Comparator<String> comparator = Collections.reverseOrder();
2036 Collections.sort(v,comparator);
2037 Collections.reverse(v);
2039 for (int i = 0; i<v.size(); i++) {
2041 buffer.append(", ");
2042 buffer.append(v.get(i));
2045 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2046 return buffer.toString();
2048 // Tags were added via dropping notes from the note list
2049 @SuppressWarnings("unused")
2050 private void tagsAdded(String noteGuid, String tagGuid) {
2051 String tagName = null;
2052 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2053 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2054 tagName = listManager.getTagIndex().get(i).getName();
2055 i=listManager.getTagIndex().size();
2058 if (tagName == null)
2061 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2062 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2063 List<String> tagNames = new ArrayList<String>();
2064 tagNames.add(new String(tagName));
2065 Note n = listManager.getMasterNoteIndex().get(i);
2066 for (int j=0; j<n.getTagNames().size(); j++) {
2067 tagNames.add(new String(n.getTagNames().get(j)));
2069 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2070 if (n.getGuid().equals(currentNoteGuid)) {
2071 Collections.sort(tagNames);
2072 String display = "";
2073 for (int j=0; j<tagNames.size(); j++) {
2074 display = display+tagNames.get(j);
2075 if (j+2<tagNames.size())
2076 display = display+Global.tagDelimeter+" ";
2078 browserWindow.setTag(display);
2080 i=listManager.getMasterNoteIndex().size();
2085 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2087 private void clearTagFilter() {
2088 tagTree.blockSignals(true);
2089 tagTree.clearSelection();
2090 menuBar.noteRestoreAction.setVisible(false);
2091 menuBar.tagEditAction.setEnabled(false);
2092 menuBar.tagDeleteAction.setEnabled(false);
2093 menuBar.tagIconAction.setEnabled(false);
2094 selectedTagGUIDs.clear();
2095 listManager.setSelectedTags(selectedTagGUIDs);
2096 tagTree.blockSignals(false);
2098 // Change the icon for a tag
2099 @SuppressWarnings("unused")
2100 private void setTagIcon() {
2101 QTreeWidgetItem currentSelection;
2102 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2103 if (selections.size() == 0)
2106 currentSelection = selections.get(0);
2107 String guid = currentSelection.text(2);
2109 QIcon currentIcon = currentSelection.icon(0);
2110 QIcon icon = conn.getTagTable().getIcon(guid);
2113 dialog = new SetIcon(currentIcon);
2114 dialog.setUseDefaultIcon(true);
2116 dialog = new SetIcon(icon);
2117 dialog.setUseDefaultIcon(false);
2120 if (dialog.okPressed()) {
2121 QIcon newIcon = dialog.getIcon();
2122 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2123 if (newIcon == null)
2124 newIcon = new QIcon(iconPath+"tag.png");
2125 currentSelection.setIcon(0, newIcon);
2131 //***************************************************************
2132 //***************************************************************
2133 //** These functions deal with Saved Search menu items
2134 //***************************************************************
2135 //***************************************************************
2136 // Add a new notebook
2137 @SuppressWarnings("unused")
2138 private void addSavedSearch() {
2139 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2140 SavedSearchEdit edit = new SavedSearchEdit();
2141 edit.setSearchList(listManager.getSavedSearchIndex());
2144 if (!edit.okPressed())
2147 Calendar currentTime = new GregorianCalendar();
2148 Long l = new Long(currentTime.getTimeInMillis());
2149 String randint = new String(Long.toString(l));
2151 SavedSearch search = new SavedSearch();
2152 search.setUpdateSequenceNum(0);
2153 search.setGuid(randint);
2154 search.setName(edit.getName());
2155 search.setQuery(edit.getQuery());
2156 search.setFormat(QueryFormat.USER);
2157 listManager.getSavedSearchIndex().add(search);
2158 conn.getSavedSearchTable().addSavedSearch(search, true);
2159 savedSearchIndexUpdated();
2160 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2162 // Edit an existing tag
2163 @SuppressWarnings("unused")
2164 private void editSavedSearch() {
2165 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2166 SavedSearchEdit edit = new SavedSearchEdit();
2167 edit.setTitle(tr("Edit Search"));
2168 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2169 QTreeWidgetItem currentSelection;
2170 currentSelection = selections.get(0);
2171 String guid = currentSelection.text(1);
2172 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2173 edit.setName(currentSelection.text(0));
2174 edit.setQuery(s.getQuery());
2175 edit.setSearchList(listManager.getSavedSearchIndex());
2178 if (!edit.okPressed())
2181 List<SavedSearch> list = listManager.getSavedSearchIndex();
2182 SavedSearch search = null;
2183 boolean found = false;
2184 for (int i=0; i<list.size(); i++) {
2185 search = list.get(i);
2186 if (search.getGuid().equals(guid)) {
2193 search.setName(edit.getName());
2194 search.setQuery(edit.getQuery());
2195 conn.getSavedSearchTable().updateSavedSearch(search, true);
2196 savedSearchIndexUpdated();
2197 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2199 // Delete an existing tag
2200 @SuppressWarnings("unused")
2201 private void deleteSavedSearch() {
2202 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2204 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2205 QMessageBox.StandardButton.Yes,
2206 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2210 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2211 for (int i=selections.size()-1; i>=0; i--) {
2212 QTreeWidgetItem currentSelection;
2213 currentSelection = selections.get(i);
2214 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2215 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2216 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2217 listManager.getSavedSearchIndex().remove(j);
2218 j=listManager.getSavedSearchIndex().size()+1;
2221 selections.remove(i);
2223 savedSearchIndexUpdated();
2224 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2226 // Setup the tree containing the user's tags
2227 private void initializeSavedSearchTree() {
2228 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2229 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2230 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2232 // Listener when a tag is selected
2233 @SuppressWarnings("unused")
2234 private void savedSearchTreeSelection() {
2235 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2237 clearNotebookFilter();
2240 clearAttributeFilter();
2242 String currentGuid = selectedSavedSearchGUID;
2243 menuBar.savedSearchEditAction.setEnabled(true);
2244 menuBar.savedSearchDeleteAction.setEnabled(true);
2245 menuBar.savedSearchIconAction.setEnabled(true);
2246 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2247 QTreeWidgetItem currentSelection;
2248 selectedSavedSearchGUID = "";
2249 for (int i=0; i<selections.size(); i++) {
2250 currentSelection = selections.get(i);
2251 if (currentSelection.text(1).equals(currentGuid)) {
2252 currentSelection.setSelected(false);
2254 selectedSavedSearchGUID = currentSelection.text(1);
2256 // i = selections.size() +1;
2259 // There is the potential for no notebooks to be selected if this
2260 // happens then we make it look like all notebooks were selecetd.
2261 // If that happens, just select the "all notebooks"
2262 if (selections.size()==0) {
2263 clearSavedSearchFilter();
2265 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2267 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2269 private void clearSavedSearchFilter() {
2270 menuBar.savedSearchEditAction.setEnabled(false);
2271 menuBar.savedSearchDeleteAction.setEnabled(false);
2272 menuBar.savedSearchIconAction.setEnabled(false);
2273 savedSearchTree.blockSignals(true);
2274 savedSearchTree.clearSelection();
2275 savedSearchTree.blockSignals(false);
2276 selectedSavedSearchGUID = "";
2277 searchField.setEditText("");
2278 searchPerformed = false;
2279 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2281 // trigger the tag index to be refreshed
2282 private void savedSearchIndexUpdated() {
2283 if (selectedSavedSearchGUID == null)
2284 selectedSavedSearchGUID = new String();
2285 savedSearchTree.blockSignals(true);
2286 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2287 savedSearchTree.load(listManager.getSavedSearchIndex());
2288 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2289 savedSearchTree.blockSignals(false);
2291 // trigger when the saved search selection changes
2292 @SuppressWarnings("unused")
2293 private void updateSavedSearchSelection() {
2294 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2296 menuBar.savedSearchEditAction.setEnabled(true);
2297 menuBar.savedSearchDeleteAction.setEnabled(true);
2298 menuBar.savedSearchIconAction.setEnabled(true);
2299 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2301 if (selections.size() > 0) {
2302 menuBar.savedSearchEditAction.setEnabled(true);
2303 menuBar.savedSearchDeleteAction.setEnabled(true);
2304 menuBar.savedSearchIconAction.setEnabled(true);
2305 selectedSavedSearchGUID = selections.get(0).text(1);
2306 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2307 searchField.setEditText(s.getQuery());
2309 menuBar.savedSearchEditAction.setEnabled(false);
2310 menuBar.savedSearchDeleteAction.setEnabled(false);
2311 menuBar.savedSearchIconAction.setEnabled(false);
2312 selectedSavedSearchGUID = "";
2313 searchField.setEditText("");
2315 searchFieldChanged();
2317 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2321 // Show/Hide note information
2322 private void toggleSavedSearchWindow() {
2323 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2324 if (savedSearchTree.isVisible())
2325 savedSearchTree.hide();
2327 savedSearchTree.show();
2328 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2330 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2331 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2333 // Change the icon for a saved search
2334 @SuppressWarnings("unused")
2335 private void setSavedSearchIcon() {
2336 QTreeWidgetItem currentSelection;
2337 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2338 if (selections.size() == 0)
2341 currentSelection = selections.get(0);
2342 String guid = currentSelection.text(1);
2344 QIcon currentIcon = currentSelection.icon(0);
2345 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2348 dialog = new SetIcon(currentIcon);
2349 dialog.setUseDefaultIcon(true);
2351 dialog = new SetIcon(icon);
2352 dialog.setUseDefaultIcon(false);
2355 if (dialog.okPressed()) {
2356 QIcon newIcon = dialog.getIcon();
2357 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2358 if (newIcon == null)
2359 newIcon = new QIcon(iconPath+"search.png");
2360 currentSelection.setIcon(0, newIcon);
2368 //***************************************************************
2369 //***************************************************************
2370 //** These functions deal with Help menu & tool menu items
2371 //***************************************************************
2372 //***************************************************************
2373 // Show database status
2374 @SuppressWarnings("unused")
2375 private void databaseStatus() {
2377 int dirty = conn.getNoteTable().getDirtyCount();
2378 int unindexed = conn.getNoteTable().getUnindexedCount();
2379 DatabaseStatus status = new DatabaseStatus();
2380 status.setUnsynchronized(dirty);
2381 status.setUnindexed(unindexed);
2382 status.setNoteCount(conn.getNoteTable().getNoteCount());
2383 status.setNotebookCount(listManager.getNotebookIndex().size());
2384 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2385 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2386 status.setTagCount(listManager.getTagIndex().size());
2387 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2388 status.setWordCount(conn.getWordsTable().getWordCount());
2392 // Compact the database
2393 @SuppressWarnings("unused")
2394 private void compactDatabase() {
2395 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2396 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2397 "but please be aware that depending upon the size of your database this can be time consuming " +
2398 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2399 QMessageBox.StandardButton.Yes,
2400 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2403 setMessage("Compacting database.");
2405 listManager.compactDatabase();
2407 setMessage("Database compact is complete.");
2408 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2410 @SuppressWarnings("unused")
2411 private void accountInformation() {
2412 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2413 AccountDialog dialog = new AccountDialog();
2415 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2417 @SuppressWarnings("unused")
2418 private void releaseNotes() {
2419 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2420 QDialog dialog = new QDialog(this);
2421 QHBoxLayout layout = new QHBoxLayout();
2422 QTextEdit textBox = new QTextEdit();
2423 layout.addWidget(textBox);
2424 textBox.setReadOnly(true);
2425 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2426 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2427 QIODevice.OpenModeFlag.Text)))
2429 textBox.setText(file.readAll().toString());
2431 dialog.setWindowTitle(tr("Release Notes"));
2432 dialog.setLayout(layout);
2434 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2436 // Called when user picks Log from the help menu
2437 @SuppressWarnings("unused")
2438 private void logger() {
2439 logger.log(logger.HIGH, "Entering NeverNote.logger");
2440 QDialog dialog = new QDialog(this);
2441 QHBoxLayout layout = new QHBoxLayout();
2442 QListWidget textBox = new QListWidget();
2443 layout.addWidget(textBox);
2444 textBox.addItems(emitLog);
2446 dialog.setLayout(layout);
2447 dialog.setWindowTitle(tr("Mesasge Log"));
2449 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2451 // Menu option "help/about" was selected
2452 @SuppressWarnings("unused")
2453 private void about() {
2454 logger.log(logger.HIGH, "Entering NeverNote.about");
2455 QMessageBox.about(this,
2456 tr("About NeverNote"),
2457 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2459 +tr("<hr></center>Evernote"
2460 +"An Open Source Evernote Client.<br><br>"
2461 +"Licensed under GPL v2. <br><hr><br>"
2462 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2463 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2464 +"PDFRenderer is licened under the LGPL<br>"
2465 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2466 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2467 +"Jazzy is licened under the LGPL<br>"
2468 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2469 logger.log(logger.HIGH, "Leaving NeverNote.about");
2471 // Hide the entire left hand side
2472 @SuppressWarnings("unused")
2473 private void toggleLeftSide() {
2476 hidden = !menuBar.hideLeftSide.isChecked();
2477 menuBar.hideLeftSide.setChecked(!hidden);
2479 if (notebookTree.isVisible() != hidden)
2480 toggleNotebookWindow();
2481 if (savedSearchTree.isVisible() != hidden)
2482 toggleSavedSearchWindow();
2483 if (tagTree.isVisible() != hidden)
2485 if (attributeTree.isVisible() != hidden)
2486 toggleAttributesWindow();
2487 if (trashTree.isVisible() != hidden)
2488 toggleTrashWindow();
2490 Global.saveWindowVisible("leftPanel", hidden);
2495 //***************************************************************
2496 //***************************************************************
2497 //** These functions deal with the Toolbar
2498 //***************************************************************
2499 //***************************************************************
2500 // Text in the search bar has been cleared
2501 private void searchFieldCleared() {
2504 // This is done because we want to force a reload of
2505 // images. Some images we may want to highlight the text.
2506 readOnlyCache.clear();
2507 inkNoteCache.clear();
2509 QWebSettings.setMaximumPagesInCache(0);
2510 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2512 searchField.setEditText("");
2513 saveNoteColumnPositions();
2514 saveNoteIndexWidth();
2515 noteIndexUpdated(true);
2516 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2517 currentNote = listManager.getNoteIndex().get(0);
2518 currentNoteGuid = currentNote.getGuid();
2520 if (currentNote != null)
2521 loadNoteBrowserInformation(browserWindow);
2523 // text in the search bar changed. We only use this to tell if it was cleared,
2524 // otherwise we trigger off searchFieldChanged.
2525 @SuppressWarnings("unused")
2526 private void searchFieldTextChanged(String text) {
2527 QWebSettings.setMaximumPagesInCache(0);
2528 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2530 if (text.trim().equals("")) {
2531 searchFieldCleared();
2532 if (searchPerformed) {
2534 // This is done because we want to force a reload of
2535 // images. Some images we may want to highlight the text.
2537 readOnlyCache.clear();
2538 inkNoteCache.clear();
2540 listManager.setEnSearch("");
2541 listManager.loadNotesIndex();
2542 refreshEvernoteNote(true);
2543 noteIndexUpdated(false);
2545 searchPerformed = false;
2548 // Text in the toolbar has changed
2549 private void searchFieldChanged() {
2550 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2552 readOnlyCache.clear();
2553 inkNoteCache.clear();
2554 saveNoteColumnPositions();
2555 saveNoteIndexWidth();
2556 String text = searchField.currentText();
2557 listManager.setEnSearch(text.trim());
2558 listManager.loadNotesIndex();
2559 //--->>> noteIndexUpdated(true);
2560 noteIndexUpdated(false);
2561 refreshEvernoteNote(true);
2562 searchPerformed = true;
2563 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2566 // Build the window tool bar
2567 private void setupToolBar() {
2568 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2569 toolBar = addToolBar(tr("Tool Bar"));
2570 menuBar.setupToolBarVisible();
2571 if (!Global.isWindowVisible("toolBar"))
2572 toolBar.setVisible(false);
2574 toolBar.setVisible(true);
2576 prevButton = toolBar.addAction("Previous");
2577 QIcon prevIcon = new QIcon(iconPath+"back.png");
2578 prevButton.setIcon(prevIcon);
2579 prevButton.triggered.connect(this, "previousViewedAction()");
2580 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2582 nextButton = toolBar.addAction("Next");
2583 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2584 nextButton.setIcon(nextIcon);
2585 nextButton.triggered.connect(this, "nextViewedAction()");
2586 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2588 upButton = toolBar.addAction("Up");
2589 QIcon upIcon = new QIcon(iconPath+"up.png");
2590 upButton.setIcon(upIcon);
2591 upButton.triggered.connect(this, "upAction()");
2592 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2595 downButton = toolBar.addAction("Down");
2596 QIcon downIcon = new QIcon(iconPath+"down.png");
2597 downButton.setIcon(downIcon);
2598 downButton.triggered.connect(this, "downAction()");
2599 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2601 synchronizeButton = toolBar.addAction("Synchronize");
2602 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2603 synchronizeIconAngle = 0;
2604 synchronizeButton.triggered.connect(this, "evernoteSync()");
2605 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2607 printButton = toolBar.addAction("Print");
2608 QIcon printIcon = new QIcon(iconPath+"print.png");
2609 printButton.setIcon(printIcon);
2610 printButton.triggered.connect(this, "printNote()");
2611 togglePrintButton(Global.isToolbarButtonVisible("print"));
2613 tagButton = toolBar.addAction("Tag");
2614 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2615 tagButton.setIcon(tagIcon);
2616 tagButton.triggered.connect(browserWindow, "modifyTags()");
2617 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2619 attributeButton = toolBar.addAction("Attributes");
2620 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2621 attributeButton.setIcon(attributeIcon);
2622 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2623 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2625 emailButton = toolBar.addAction("Email");
2626 QIcon emailIcon = new QIcon(iconPath+"email.png");
2627 emailButton.setIcon(emailIcon);
2628 emailButton.triggered.connect(this, "emailNote()");
2629 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2631 deleteButton = toolBar.addAction("Delete");
2632 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2633 deleteButton.setIcon(deleteIcon);
2634 deleteButton.triggered.connect(this, "deleteNote()");
2635 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2637 newButton = toolBar.addAction("New");
2638 QIcon newIcon = new QIcon(iconPath+"new.png");
2639 newButton.triggered.connect(this, "addNote()");
2640 newButton.setIcon(newIcon);
2641 toggleNewButton(Global.isToolbarButtonVisible("new"));
2643 allNotesButton = toolBar.addAction("All Notes");
2644 QIcon allIcon = new QIcon(iconPath+"books.png");
2645 allNotesButton.triggered.connect(this, "allNotes()");
2646 allNotesButton.setIcon(allIcon);
2647 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2649 toolBar.addSeparator();
2650 toolBar.addWidget(new QLabel(tr("Quota:")));
2651 toolBar.addWidget(quotaBar);
2652 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2654 toolBar.addSeparator();
2657 zoomSpinner = new QSpinBox();
2658 zoomSpinner.setMinimum(10);
2659 zoomSpinner.setMaximum(1000);
2660 zoomSpinner.setAccelerated(true);
2661 zoomSpinner.setSingleStep(10);
2662 zoomSpinner.setValue(100);
2663 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2664 toolBar.addWidget(new QLabel(tr("Zoom")));
2665 toolBar.addWidget(zoomSpinner);
2667 //toolBar.addWidget(new QLabel(" "));
2668 toolBar.addSeparator();
2669 toolBar.addWidget(new QLabel(tr(" Search:")));
2670 toolBar.addWidget(searchField);
2671 QSizePolicy sizePolicy = new QSizePolicy();
2672 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2673 searchField.setSizePolicy(sizePolicy);
2674 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2676 searchClearButton = toolBar.addAction("Search Clear");
2677 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2678 searchClearButton.setIcon(searchClearIcon);
2679 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2680 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2682 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2684 // Update the sychronize button picture
2686 public QMenu createPopupMenu() {
2687 QMenu contextMenu = super.createPopupMenu();
2689 contextMenu.addSeparator();
2690 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2691 contextMenu.addAction(prevAction);
2692 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2694 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2695 contextMenu.addAction(nextAction);
2696 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2698 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2699 contextMenu.addAction(upAction);
2700 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2702 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2703 contextMenu.addAction(downAction);
2704 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2706 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2707 contextMenu.addAction(synchronizeAction);
2708 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2710 QAction printAction = addContextAction("print", tr("Print"));
2711 contextMenu.addAction(printAction);
2712 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2714 QAction tagAction = addContextAction("tag", tr("Tag"));
2715 contextMenu.addAction(tagAction);
2716 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2718 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2719 contextMenu.addAction(attributeAction);
2720 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2722 QAction emailAction = addContextAction("email", tr("Email"));
2723 contextMenu.addAction(emailAction);
2724 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2726 QAction deleteAction = addContextAction("delete", tr("Delete"));
2727 contextMenu.addAction(deleteAction);
2728 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2730 QAction newAction = addContextAction("new", tr("Add"));
2731 contextMenu.addAction(newAction);
2732 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2734 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2735 contextMenu.addAction(allNotesAction);
2736 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2738 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2739 contextMenu.addAction(searchClearAction);
2740 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2745 private QAction addContextAction(String config, String name) {
2746 QAction newAction = new QAction(this);
2747 newAction.setText(name);
2748 newAction.setCheckable(true);
2749 newAction.setChecked(Global.isToolbarButtonVisible(config));
2752 private void togglePrevArrowButton(Boolean toggle) {
2753 prevButton.setVisible(toggle);
2754 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2756 private void toggleNextArrowButton(Boolean toggle) {
2757 nextButton.setVisible(toggle);
2758 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2760 private void toggleUpArrowButton(Boolean toggle) {
2761 upButton.setVisible(toggle);
2762 Global.saveToolbarButtonsVisible("upArrow", toggle);
2764 private void toggleDownArrowButton(Boolean toggle) {
2765 downButton.setVisible(toggle);
2766 Global.saveToolbarButtonsVisible("downArrow", toggle);
2768 private void toggleSynchronizeButton(Boolean toggle) {
2769 synchronizeButton.setVisible(toggle);
2770 Global.saveToolbarButtonsVisible("synchronize", toggle);
2772 private void togglePrintButton(Boolean toggle) {
2773 printButton.setVisible(toggle);
2774 Global.saveToolbarButtonsVisible("print", toggle);
2776 private void toggleTagButton(Boolean toggle) {
2777 tagButton.setVisible(toggle);
2778 Global.saveToolbarButtonsVisible("tag", toggle);
2780 private void toggleAttributeButton(Boolean toggle) {
2781 attributeButton.setVisible(toggle);
2782 Global.saveToolbarButtonsVisible("attribute", toggle);
2784 private void toggleEmailButton(Boolean toggle) {
2785 emailButton.setVisible(toggle);
2786 Global.saveToolbarButtonsVisible("email", toggle);
2788 private void toggleDeleteButton(Boolean toggle) {
2789 deleteButton.setVisible(toggle);
2790 Global.saveToolbarButtonsVisible("delete", toggle);
2792 private void toggleNewButton(Boolean toggle) {
2793 newButton.setVisible(toggle);
2794 Global.saveToolbarButtonsVisible("new", toggle);
2796 private void toggleAllNotesButton(Boolean toggle) {
2797 allNotesButton.setVisible(toggle);
2798 Global.saveToolbarButtonsVisible("allNotes", toggle);
2800 private void toggleSearchClearButton(Boolean toggle) {
2801 searchClearButton.setVisible(toggle);
2802 Global.saveToolbarButtonsVisible("searchClear", toggle);
2809 @SuppressWarnings("unused")
2810 private void updateSyncButton() {
2812 if (syncIcons == null) {
2813 syncIcons = new ArrayList<QPixmap>();
2815 synchronizeIconAngle = 0;
2816 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2818 for (int i=0; i<=360; i++) {
2819 QPixmap rotatedPix = new QPixmap(pix.size());
2820 QPainter p = new QPainter(rotatedPix);
2821 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2822 QSize size = pix.size();
2823 p.translate(size.width()/2, size.height()/2);
2826 p.setBackgroundMode(BGMode.OpaqueMode);
2827 p.translate(-size.width()/2, -size.height()/2);
2828 p.drawPixmap(0,0, pix);
2830 syncIcons.add(rotatedPix);
2834 synchronizeIconAngle++;
2835 if (synchronizeIconAngle > 359)
2836 synchronizeIconAngle=0;
2837 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2840 // Synchronize with Evernote
2841 @SuppressWarnings("unused")
2842 private void evernoteSync() {
2843 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2844 if (!Global.isConnected)
2846 if (Global.isConnected)
2847 synchronizeAnimationTimer.start(5);
2848 // synchronizeAnimationTimer.start(200);
2850 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2852 private void updateQuotaBar() {
2853 long limit = Global.getUploadLimit();
2854 long amount = Global.getUploadAmount();
2855 if (amount>0 && limit>0) {
2856 int percent =(int)(amount*100/limit);
2857 quotaBar.setValue(percent);
2859 quotaBar.setValue(0);
2862 @SuppressWarnings("unused")
2863 private void zoomChanged() {
2864 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2867 //****************************************************************
2868 //****************************************************************
2869 //* System Tray functions
2870 //****************************************************************
2871 //****************************************************************
2872 private void trayToggleVisible() {
2877 if (windowMaximized)
2884 @SuppressWarnings("unused")
2885 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2886 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2887 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2888 trayToggleVisible();
2893 //***************************************************************
2894 //***************************************************************
2895 //** These functions deal with the trash tree
2896 //***************************************************************
2897 //***************************************************************
2898 // Setup the tree containing the trash.
2899 @SuppressWarnings("unused")
2900 private void trashTreeSelection() {
2901 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2903 clearNotebookFilter();
2905 clearAttributeFilter();
2906 clearSavedSearchFilter();
2908 String tempGuid = currentNoteGuid;
2910 // currentNoteGuid = "";
2911 currentNote = new Note();
2912 selectedNoteGUIDs.clear();
2913 listManager.getSelectedNotebooks().clear();
2914 listManager.getSelectedTags().clear();
2915 listManager.setSelectedSavedSearch("");
2916 browserWindow.clear();
2918 // toggle the add buttons
2919 newButton.setEnabled(!newButton.isEnabled());
2920 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2921 menuBar.noteAdd.setVisible(true);
2923 List<QTreeWidgetItem> selections = trashTree.selectedItems();
2924 if (selections.size() == 0) {
2925 currentNoteGuid = trashNoteGuid;
2926 trashNoteGuid = tempGuid;
2927 Global.showDeleted = false;
2928 menuBar.noteRestoreAction.setEnabled(false);
2929 menuBar.noteRestoreAction.setVisible(false);
2932 currentNoteGuid = trashNoteGuid;
2933 trashNoteGuid = tempGuid;
2934 menuBar.noteRestoreAction.setEnabled(true);
2935 menuBar.noteRestoreAction.setVisible(true);
2936 Global.showDeleted = true;
2938 listManager.loadNotesIndex();
2939 noteIndexUpdated(false);
2940 //// browserWindow.setEnabled(newButton.isEnabled());
2941 browserWindow.setReadOnly(!newButton.isEnabled());
2942 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2944 // Empty the trash file
2945 @SuppressWarnings("unused")
2946 private void emptyTrash() {
2947 // browserWindow.clear();
2948 listManager.emptyTrash();
2949 if (trashTree.selectedItems().size() > 0) {
2950 listManager.getSelectedNotebooks().clear();
2951 listManager.getSelectedTags().clear();
2952 listManager.setSelectedSavedSearch("");
2953 newButton.setEnabled(!newButton.isEnabled());
2954 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2955 menuBar.noteAdd.setVisible(true);
2956 browserWindow.clear();
2959 clearNotebookFilter();
2960 clearSavedSearchFilter();
2961 clearAttributeFilter();
2963 Global.showDeleted = false;
2964 menuBar.noteRestoreAction.setEnabled(false);
2965 menuBar.noteRestoreAction.setVisible(false);
2967 listManager.loadNotesIndex();
2968 //--->>> noteIndexUpdated(true);
2969 noteIndexUpdated(false);
2972 // Show/Hide trash window
2973 private void toggleTrashWindow() {
2974 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2975 if (trashTree.isVisible())
2979 menuBar.hideTrash.setChecked(trashTree.isVisible());
2981 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2982 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2984 private void clearTrashFilter() {
2985 Global.showDeleted = false;
2986 newButton.setEnabled(true);
2987 menuBar.noteAdd.setEnabled(true);
2988 menuBar.noteAdd.setVisible(true);
2989 trashTree.blockSignals(true);
2990 trashTree.clearSelection();
2991 trashTree.blockSignals(false);
2996 //***************************************************************
2997 //***************************************************************
2998 //** These functions deal with connection settings
2999 //***************************************************************
3000 //***************************************************************
3001 // SyncRunner had a problem and things are disconnected
3002 @SuppressWarnings("unused")
3003 private void remoteErrorDisconnect() {
3004 menuBar.connectAction.setText(tr("Connect"));
3005 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3006 menuBar.synchronizeAction.setEnabled(false);
3007 Global.isConnected = false;
3008 synchronizeAnimationTimer.stop();
3011 // Do a manual connect/disconnect
3012 private void remoteConnect() {
3013 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3015 if (Global.isConnected) {
3016 Global.isConnected = false;
3017 syncRunner.enDisconnect();
3018 setupConnectMenuOptions();
3023 AESEncrypter aes = new AESEncrypter();
3025 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3026 } catch (FileNotFoundException e) {
3027 // File not found, so we'll just get empty strings anyway.
3029 String userid = aes.getUserid();
3030 String password = aes.getPassword();
3031 if (!userid.equals("") && !password.equals("")) {
3032 Global.username = userid;
3033 Global.password = password;
3036 // Show the login dialog box
3037 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3038 LoginDialog login = new LoginDialog();
3041 if (!login.okPressed()) {
3045 Global.username = login.getUserid();
3046 Global.password = login.getPassword();
3048 syncRunner.username = Global.username;
3049 syncRunner.password = Global.password;
3050 syncRunner.userStoreUrl = Global.userStoreUrl;
3051 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3052 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3054 if (Global.getProxyValue("url").equals("")) {
3055 System.setProperty("http.proxyHost","") ;
3056 System.setProperty("http.proxyPort", "") ;
3057 System.setProperty("https.proxyHost","") ;
3058 System.setProperty("https.proxyPort", "") ;
3061 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3062 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3063 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3064 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3066 if (Global.getProxyValue("userid").equals("")) {
3067 Authenticator.setDefault(new Authenticator() {
3069 protected PasswordAuthentication getPasswordAuthentication() {
3071 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3077 syncRunner.enConnect();
3078 Global.isConnected = syncRunner.isConnected;
3080 setupConnectMenuOptions();
3081 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3083 private void setupConnectMenuOptions() {
3084 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3085 if (!Global.isConnected) {
3086 menuBar.connectAction.setText(tr("Connect"));
3087 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3088 menuBar.synchronizeAction.setEnabled(false);
3090 menuBar.connectAction.setText(tr("Disconnect"));
3091 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3092 menuBar.synchronizeAction.setEnabled(true);
3094 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3099 //***************************************************************
3100 //***************************************************************
3101 //** These functions deal with the GUI Attribute tree
3102 //***************************************************************
3103 //***************************************************************
3104 @SuppressWarnings("unused")
3105 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3107 // clearTagFilter();
3108 // clearNotebookFilter();
3110 // clearSavedSearchFilter();
3112 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3113 if (item.childCount() > 0) {
3114 item.setSelected(false);
3116 Global.createdBeforeFilter.reset();
3117 Global.createdSinceFilter.reset();
3118 Global.changedBeforeFilter.reset();
3119 Global.changedSinceFilter.reset();
3120 Global.containsFilter.reset();
3121 attributeTreeSelected = item;
3122 DateAttributeFilterTable f = null;
3123 f = findDateAttributeFilterTable(item.parent());
3125 f.select(item.parent().indexOfChild(item));
3127 Global.containsFilter.select(item.parent().indexOfChild(item));
3130 listManager.loadNotesIndex();
3131 noteIndexUpdated(false);
3134 attributeTreeSelected = null;
3135 item.setSelected(false);
3136 Global.createdBeforeFilter.reset();
3137 Global.createdSinceFilter.reset();
3138 Global.changedBeforeFilter.reset();
3139 Global.changedSinceFilter.reset();
3140 Global.containsFilter.reset();
3141 listManager.loadNotesIndex();
3142 noteIndexUpdated(false);
3144 // This determines what attribute filter we need, depending upon the selection
3145 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3146 if (w.parent() != null && w.childCount() > 0) {
3147 QTreeWidgetItem parent = w.parent();
3148 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3149 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3150 return Global.createdSinceFilter;
3151 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3152 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3153 return Global.createdBeforeFilter;
3154 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3155 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3156 return Global.changedSinceFilter;
3157 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3158 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3159 return Global.changedBeforeFilter;
3164 // Show/Hide attribute search window
3165 private void toggleAttributesWindow() {
3166 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3167 if (attributeTree.isVisible())
3168 attributeTree.hide();
3170 attributeTree.show();
3171 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3173 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3174 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3176 private void clearAttributeFilter() {
3177 Global.createdBeforeFilter.reset();
3178 Global.createdSinceFilter.reset();
3179 Global.changedBeforeFilter.reset();
3180 Global.changedSinceFilter.reset();
3181 Global.containsFilter.reset();
3182 attributeTreeSelected = null;
3183 attributeTree.blockSignals(true);
3184 attributeTree.clearSelection();
3185 attributeTree.blockSignals(false);
3189 //***************************************************************
3190 //***************************************************************
3191 //** These functions deal with the GUI Note index table
3192 //***************************************************************
3193 //***************************************************************
3194 // Initialize the note list table
3195 private void initializeNoteTable() {
3196 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3197 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3198 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3199 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3201 // Show/Hide trash window
3202 @SuppressWarnings("unused")
3203 private void toggleNoteListWindow() {
3204 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3205 if (noteTableView.isVisible())
3206 noteTableView.hide();
3208 noteTableView.show();
3209 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3211 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3212 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3214 // Handle the event that a user selects a note from the table
3215 @SuppressWarnings("unused")
3216 private void noteTableSelection() {
3217 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3219 if (historyGuids.size() == 0) {
3220 historyGuids.add(currentNoteGuid);
3221 historyPosition = 1;
3223 noteTableView.showColumn(Global.noteTableGuidPosition);
3225 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3226 if (!Global.isColumnVisible("guid"))
3227 noteTableView.hideColumn(Global.noteTableGuidPosition);
3229 if (selections.size() > 0) {
3231 menuBar.noteDuplicateAction.setEnabled(true);
3232 menuBar.noteOnlineHistoryAction.setEnabled(true);
3233 menuBar.noteMergeAction.setEnabled(true);
3234 selectedNoteGUIDs.clear();
3235 if (selections.size() != 1 || Global.showDeleted) {
3236 menuBar.noteDuplicateAction.setEnabled(false);
3238 if (selections.size() != 1 || !Global.isConnected) {
3239 menuBar.noteOnlineHistoryAction.setEnabled(false);
3241 if (selections.size() == 1) {
3242 menuBar.noteMergeAction.setEnabled(false);
3244 for (int i=0; i<selections.size(); i++) {
3245 int row = selections.get(i).row();
3247 upButton.setEnabled(false);
3249 upButton.setEnabled(true);
3250 if (row < listManager.getNoteTableModel().rowCount()-1)
3251 downButton.setEnabled(true);
3253 downButton.setEnabled(false);
3254 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3255 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3256 currentNoteGuid = (String)ix.values().toArray()[0];
3257 selectedNoteGUIDs.add(currentNoteGuid);
3261 nextButton.setEnabled(true);
3262 prevButton.setEnabled(true);
3264 int endPosition = historyGuids.size()-1;
3265 for (int j=historyPosition; j<=endPosition; j++) {
3266 historyGuids.remove(historyGuids.size()-1);
3268 historyGuids.add(currentNoteGuid);
3269 historyPosition = historyGuids.size();
3271 if (historyPosition <= 1)
3272 prevButton.setEnabled(false);
3273 if (historyPosition == historyGuids.size())
3274 nextButton.setEnabled(false);
3276 fromHistory = false;
3277 scrollToGuid(currentNoteGuid);
3278 refreshEvernoteNote(true);
3279 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3281 // Trigger a refresh when the note db has been updated
3282 private void noteIndexUpdated(boolean reload) {
3283 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3285 refreshEvernoteNoteList();
3286 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3287 noteTableView.load(reload);
3288 scrollToGuid(currentNoteGuid);
3289 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3291 // Called when the list of notes is updated
3292 private void refreshEvernoteNoteList() {
3293 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3294 browserWindow.setDisabled(false);
3295 if (selectedNoteGUIDs == null)
3296 selectedNoteGUIDs = new ArrayList<String>();
3297 selectedNoteGUIDs.clear(); // clear out old entries
3299 String saveCurrentNoteGuid = new String();
3300 String tempNoteGuid = new String();
3302 historyGuids.clear();
3303 historyPosition = 0;
3304 prevButton.setEnabled(false);
3305 nextButton.setEnabled(false);
3307 if (currentNoteGuid == null)
3308 currentNoteGuid = new String();
3310 //determine current note guid
3311 for (Note note : listManager.getNoteIndex()) {
3312 tempNoteGuid = note.getGuid();
3313 if (currentNoteGuid.equals(tempNoteGuid)) {
3314 saveCurrentNoteGuid = tempNoteGuid;
3318 if (listManager.getNoteIndex().size() == 0) {
3319 currentNoteGuid = "";
3321 browserWindow.clear();
3322 browserWindow.setDisabled(true);
3325 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() > 0) {
3326 currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
3327 currentNoteGuid = currentNote.getGuid();
3328 refreshEvernoteNote(true);
3330 //we can reload if note not dirty
3331 // refreshEvernoteNote(!noteDirty);
3332 refreshEvernoteNote(false);
3334 reloadTagTree(false);
3336 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3338 // Called when the previous arrow button is clicked
3339 @SuppressWarnings("unused")
3340 private void previousViewedAction() {
3341 if (!prevButton.isEnabled())
3343 if (historyPosition == 0)
3346 if (historyPosition <= 0)
3348 String historyGuid = historyGuids.get(historyPosition-1);
3350 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3351 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3352 if (modelIndex != null) {
3353 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3354 String tableGuid = (String)ix.values().toArray()[0];
3355 if (tableGuid.equals(historyGuid)) {
3356 noteTableView.selectRow(i);
3362 @SuppressWarnings("unused")
3363 private void nextViewedAction() {
3364 if (!nextButton.isEnabled())
3366 String historyGuid = historyGuids.get(historyPosition);
3369 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3370 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3371 if (modelIndex != null) {
3372 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3373 String tableGuid = (String)ix.values().toArray()[0];
3374 if (tableGuid.equals(historyGuid)) {
3375 noteTableView.selectRow(i);
3381 // Called when the up arrow is clicked
3382 @SuppressWarnings("unused")
3383 private void upAction() {
3384 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3385 int row = selections.get(0).row();
3387 noteTableView.selectRow(row-1);
3390 // Called when the down arrow is clicked
3391 @SuppressWarnings("unused")
3392 private void downAction() {
3393 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3394 int row = selections.get(0).row();
3395 int max = listManager.getNoteTableModel().rowCount();
3397 noteTableView.selectRow(row+1);
3400 // Update a tag string for a specific note in the list
3401 @SuppressWarnings("unused")
3402 private void updateListTags(String guid, List<String> tags) {
3403 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3404 StringBuffer tagBuffer = new StringBuffer();
3405 for (int i=0; i<tags.size(); i++) {
3406 tagBuffer.append(tags.get(i));
3407 if (i<tags.size()-1)
3408 tagBuffer.append(", ");
3411 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3412 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3413 if (modelIndex != null) {
3414 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3415 String tableGuid = (String)ix.values().toArray()[0];
3416 if (tableGuid.equals(guid)) {
3417 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3418 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3419 noteTableView.proxyModel.invalidate();
3424 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3426 // Update a title for a specific note in the list
3427 @SuppressWarnings("unused")
3428 private void updateListAuthor(String guid, String author) {
3429 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3431 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3432 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3433 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3434 if (modelIndex != null) {
3435 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3436 String tableGuid = (String)ix.values().toArray()[0];
3437 if (tableGuid.equals(guid)) {
3438 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3439 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3440 noteTableView.proxyModel.invalidate();
3446 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3448 private void updateListNoteNotebook(String guid, String notebook) {
3449 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3450 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3451 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3453 // Update a title for a specific note in the list
3454 @SuppressWarnings("unused")
3455 private void updateListSourceUrl(String guid, String url) {
3456 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3458 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3459 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3460 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3461 if (modelIndex != null) {
3462 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3463 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3464 String tableGuid = (String)ix.values().toArray()[0];
3465 if (tableGuid.equals(guid)) {
3466 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3467 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3468 noteTableView.proxyModel.invalidate();
3473 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3475 @SuppressWarnings("unused")
3476 private void updateListGuid(String oldGuid, String newGuid) {
3477 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3479 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3480 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3481 if (modelIndex != null) {
3482 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3483 String tableGuid = (String)ix.values().toArray()[0];
3484 if (tableGuid.equals(oldGuid)) {
3485 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3486 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3491 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3493 private void updateListTagName(String guid) {
3494 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3496 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3497 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3498 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3500 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3501 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3502 if (modelIndex != null) {
3503 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3504 String noteGuid = (String)ix.values().toArray()[0];
3505 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3506 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3507 i=listManager.getNoteTableModel().rowCount();
3513 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3515 private void removeListTagName(String guid) {
3516 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3518 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3519 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3520 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3521 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3522 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3525 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3526 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3527 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3528 if (modelIndex != null) {
3529 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3530 String noteGuid = (String)ix.values().toArray()[0];
3531 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3532 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3533 i=listManager.getNoteTableModel().rowCount();
3539 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3541 private void updateListNotebookName(String oldName, String newName) {
3542 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3544 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3545 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3546 if (modelIndex != null) {
3547 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3548 String tableName = (String)ix.values().toArray()[0];
3549 if (tableName.equalsIgnoreCase(oldName)) {
3550 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3554 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3556 @SuppressWarnings("unused")
3557 private void updateListDateCreated(String guid, QDateTime date) {
3558 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3560 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3561 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3562 if (modelIndex != null) {
3563 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3564 String tableGuid = (String)ix.values().toArray()[0];
3565 if (tableGuid.equals(guid)) {
3566 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3567 noteTableView.proxyModel.invalidate();
3572 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3574 @SuppressWarnings("unused")
3575 private void updateListDateSubject(String guid, QDateTime date) {
3576 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3578 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3579 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3580 if (modelIndex != null) {
3581 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3582 String tableGuid = (String)ix.values().toArray()[0];
3583 if (tableGuid.equals(guid)) {
3584 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3585 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3586 noteTableView.proxyModel.invalidate();
3591 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3593 private void updateListDateChanged(String guid, QDateTime date) {
3594 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3596 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3597 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3598 if (modelIndex != null) {
3599 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3600 String tableGuid = (String)ix.values().toArray()[0];
3601 if (tableGuid.equals(guid)) {
3602 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3603 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3608 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3610 private void updateListDateChanged() {
3611 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3612 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3613 updateListDateChanged(currentNoteGuid, date);
3614 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3617 private void scrollToCurrentGuid() {
3618 //scrollToGuid(currentNoteGuid);
3619 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3620 if (selections.size() == 0)
3622 QModelIndex index = selections.get(0);
3623 int row = selections.get(0).row();
3624 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3627 // Scroll to a particular index item
3628 private void scrollToGuid(String guid) {
3629 if (currentNote == null || guid == null)
3631 if (currentNote.isActive() && Global.showDeleted) {
3632 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3633 if (!listManager.getNoteIndex().get(i).isActive()) {
3634 currentNote = listManager.getNoteIndex().get(i);
3635 currentNoteGuid = currentNote.getGuid();
3636 i = listManager.getNoteIndex().size();
3641 if (!currentNote.isActive() && !Global.showDeleted) {
3642 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3643 if (listManager.getNoteIndex().get(i).isActive()) {
3644 currentNote = listManager.getNoteIndex().get(i);
3645 currentNoteGuid = currentNote.getGuid();
3646 i = listManager.getNoteIndex().size();
3652 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3653 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3654 if (currentNoteGuid.equals(index.data())) {
3655 // noteTableView.setCurrentIndex(index);
3656 noteTableView.selectRow(i);
3657 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3658 i=listManager.getNoteTableModel().rowCount();
3661 noteTableView.repaint();
3663 // Show/Hide columns
3664 private void showColumns() {
3665 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3666 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3667 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3668 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3669 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3670 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3671 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3672 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3673 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3674 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3675 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3677 // Title color has changed
3678 @SuppressWarnings("unused")
3679 private void titleColorChanged(Integer color) {
3680 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3682 QColor backgroundColor = new QColor();
3683 QColor foregroundColor = new QColor(QColor.black);
3684 backgroundColor.setRgb(color);
3686 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3687 foregroundColor.setRgb(QColor.white.rgb());
3689 if (selectedNoteGUIDs.size() == 0)
3690 selectedNoteGUIDs.add(currentNoteGuid);
3692 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3693 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3694 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3695 if (modelIndex != null) {
3696 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3697 String tableGuid = (String)ix.values().toArray()[0];
3698 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3699 for (int k=0; k<Global.noteTableColumnCount; k++) {
3700 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3701 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3702 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3704 i=listManager.getNoteTableModel().rowCount();
3709 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3711 // Wide list was chosen
3712 public void narrowListView() {
3713 saveNoteColumnPositions();
3714 saveNoteIndexWidth();
3716 int sortCol = noteTableView.proxyModel.sortColumn();
3717 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3718 Global.setSortColumn(sortCol);
3719 Global.setSortOrder(sortOrder);
3721 Global.setListView(Global.View_List_Narrow);
3723 menuBar.wideListView.blockSignals(true);
3724 menuBar.narrowListView.blockSignals(true);
3726 menuBar.wideListView.setChecked(false);
3727 menuBar.narrowListView.setChecked(true);
3729 menuBar.wideListView.blockSignals(false);
3730 menuBar.narrowListView.blockSignals(false);
3732 mainLeftRightSplitter.addWidget(noteTableView);
3733 mainLeftRightSplitter.addWidget(browserWindow);
3734 restoreWindowState(false);
3735 noteTableView.repositionColumns();
3736 noteTableView.resizeColumnWidths();
3737 noteTableView.resizeRowHeights();
3739 sortCol = Global.getSortColumn();
3740 sortOrder = Global.getSortOrder();
3741 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3744 noteTableView.load(false);
3745 scrollToCurrentGuid();
3747 public void wideListView() {
3748 int sortCol = noteTableView.proxyModel.sortColumn();
3749 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3750 Global.setSortColumn(sortCol);
3751 Global.setSortOrder(sortOrder);
3754 saveNoteColumnPositions();
3755 saveNoteIndexWidth();
3756 Global.setListView(Global.View_List_Wide);
3758 menuBar.wideListView.blockSignals(true);
3759 menuBar.narrowListView.blockSignals(true);
3761 menuBar.wideListView.setChecked(true);
3762 menuBar.narrowListView.setChecked(false);
3764 menuBar.wideListView.blockSignals(false);
3765 menuBar.narrowListView.blockSignals(false);
3766 browserIndexSplitter.setVisible(true);
3767 browserIndexSplitter.addWidget(noteTableView);
3768 browserIndexSplitter.addWidget(browserWindow);
3769 restoreWindowState(false);
3770 noteTableView.repositionColumns();
3771 noteTableView.resizeColumnWidths();
3772 noteTableView.resizeRowHeights();
3774 sortCol = Global.getSortColumn();
3775 sortOrder = Global.getSortOrder();
3776 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3779 noteTableView.load(false);
3780 scrollToCurrentGuid();
3784 //***************************************************************
3785 //***************************************************************
3786 //** External editor window functions
3787 //***************************************************************
3788 //***************************************************************
3789 private void listDoubleClick() {
3791 if (externalWindows.containsKey(currentNoteGuid)) {
3792 externalWindows.get(currentNoteGuid).raise();
3795 // We have a new external editor to create
3796 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3797 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3798 newBrowser.setWindowIcon(appIcon);
3799 externalWindows.put(currentNoteGuid, newBrowser);
3800 showEditorButtons(newBrowser.getBrowserWindow());
3801 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3802 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3803 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3804 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3805 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3806 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3808 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3809 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3810 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3814 @SuppressWarnings("unused")
3815 private void externalWindowTitleEdited(String guid, String text) {
3816 if (guid.equals(currentNoteGuid)) {
3817 browserWindow.setTitle(text);
3820 @SuppressWarnings({ "rawtypes", "unused" })
3821 private void externalWindowTagsEdited(String guid, List values) {
3822 StringBuffer line = new StringBuffer(100);
3823 for (int i=0; i<values.size(); i++) {
3825 line.append(Global.tagDelimeter+" ");
3826 line.append(values.get(i));
3828 if (guid.equals(currentNoteGuid)) {
3829 browserWindow.setTag(line.toString());
3832 @SuppressWarnings("unused")
3833 private void externalWindowClosing(String guid) {
3834 externalWindows.remove(guid);
3839 //***************************************************************
3840 //***************************************************************
3841 //** These functions deal with Note specific things
3842 //***************************************************************
3843 //***************************************************************
3844 @SuppressWarnings("unused")
3845 private void setNoteDirty() {
3846 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
3847 // Find if the note is being edited externally. If it is, update it.
3848 if (externalWindows.containsKey(currentNoteGuid)) {
3849 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3850 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
3851 ExternalBrowse window = externalWindows.get(currentNoteGuid);
3852 window.getBrowserWindow().getBrowser().setContent(unicode);
3855 // If the note is dirty, then it is unsynchronized by default.
3859 // Set the note as dirty and check if its status is synchronized in the display table
3861 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
3862 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
3866 // If this wasn't already marked as unsynchronized, then we need to update the table
3867 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
3868 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
3869 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3870 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3871 if (modelIndex != null) {
3872 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3873 String tableGuid = (String)ix.values().toArray()[0];
3874 if (tableGuid.equals(currentNoteGuid)) {
3875 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3881 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
3883 @SuppressWarnings("unused")
3884 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
3885 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3886 QByteArray unicode = codec.fromUnicode(content);
3887 noteCache.remove(guid);
3888 noteCache.put(guid, unicode.toString());
3889 if (guid.equals(currentNoteGuid)) {
3891 browserWindow.getBrowser().setContent(unicode);
3894 thumbnailRunner.addWork("GENERATE "+ guid);
3895 saveNote(guid, browser);
3899 private void saveNote() {
3901 saveNote(currentNoteGuid, browserWindow);
3902 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
3906 private void saveNote(String guid, BrowserWindow window) {
3907 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
3908 logger.log(logger.EXTREME, "Note is dirty.");
3911 logger.log(logger.EXTREME, "Saving to cache");
3912 QTextCodec codec = QTextCodec.codecForLocale();
3913 // QTextDecoder decoder = codec.makeDecoder();
3914 codec = QTextCodec.codecForName("UTF-8");
3915 QByteArray unicode = codec.fromUnicode(window.getContent());
3916 noteCache.put(guid, unicode.toString());
3918 logger.log(logger.EXTREME, "updating list manager");
3919 listManager.updateNoteContent(guid, window.getContent());
3920 logger.log(logger.EXTREME, "Updating title");
3921 listManager.updateNoteTitle(guid, window.getTitle());
3922 updateListDateChanged();
3924 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
3925 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3926 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
3927 currentNote = listManager.getNoteIndex().get(i);
3928 i = listManager.getNoteIndex().size();
3933 // Get a note from Evernote (and put it in the browser)
3934 private void refreshEvernoteNote(boolean reload) {
3935 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
3937 if (Global.disableViewing) {
3938 browserWindow.setEnabled(false);
3943 if (Global.showDeleted)
3945 Global.cryptCounter =0;
3946 if (currentNoteGuid.equals("")) {
3947 browserWindow.setReadOnly(true);
3955 browserWindow.loadingData(true);
3957 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
3958 if (currentNote == null)
3961 loadNoteBrowserInformation(browserWindow);
3964 private void loadNoteBrowserInformation(BrowserWindow browser) {
3965 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
3966 formatter.setNote(currentNote, Global.pdfPreview());
3967 formatter.setHighlight(listManager.getEnSearch());
3969 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3970 js = new QByteArray();
3971 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
3972 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
3973 js.append("<style type=\"text/css\">.en-crypt-temp { border-collapse:collapse; border-style:solid; border-color:blue; padding:0.0mm 0.0mm 0.0mm 0.0mm; }</style>");
3974 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
3975 js.append("<style> img { max-width:100%; }</style>");
3976 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
3977 js.append("</head>");
3978 formatter.setNote(currentNote, Global.pdfPreview());
3979 js.append(formatter.rebuildNoteHTML());
3980 js.append("</HTML>");
3981 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
3982 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
3983 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
3984 browser.getBrowser().setContent(js);
3985 noteCache.put(currentNoteGuid, js.toString());
3987 if (formatter.resourceError)
3988 resourceErrorMessage();
3989 readOnly = formatter.readOnly;
3990 inkNote = formatter.inkNote;
3992 readOnlyCache.put(currentNoteGuid, true);
3994 inkNoteCache.put(currentNoteGuid, true);
3996 logger.log(logger.HIGH, "Note content is being pulled from the cache");
3997 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
3998 js = new QByteArray(cachedContent);
3999 browser.getBrowser().setContent(js);
4000 if (readOnlyCache.containsKey(currentNoteGuid))
4002 if (inkNoteCache.containsKey(currentNoteGuid))
4005 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4006 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4009 if (readOnly || inkNote)
4010 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4012 browser.getBrowser().page().setContentEditable(true);
4013 browser.setReadOnly(readOnly);
4014 deleteButton.setEnabled(!readOnly);
4015 tagButton.setEnabled(!readOnly);
4016 menuBar.noteDelete.setEnabled(!readOnly);
4017 menuBar.noteTags.setEnabled(!readOnly);
4018 browser.setNote(currentNote);
4020 if (conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4021 deleteButton.setEnabled(false);
4022 menuBar.notebookDeleteAction.setEnabled(false);
4024 deleteButton.setEnabled(true);
4025 menuBar.notebookDeleteAction.setEnabled(true);
4028 // Build a list of non-closed notebooks
4029 List<Notebook> nbooks = new ArrayList<Notebook>();
4030 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4031 boolean found=false;
4032 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4033 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4037 nbooks.add(listManager.getNotebookIndex().get(i));
4040 browser.setTitle(currentNote.getTitle());
4041 browser.setTag(getTagNamesForNote(currentNote));
4042 browser.setAuthor(currentNote.getAttributes().getAuthor());
4044 browser.setAltered(currentNote.getUpdated());
4045 browser.setCreation(currentNote.getCreated());
4046 if (currentNote.getAttributes().getSubjectDate() > 0)
4047 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4049 browser.setSubjectDate(currentNote.getCreated());
4050 browser.setUrl(currentNote.getAttributes().getSourceURL());
4052 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4053 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4054 browser.setAllTags(tagList);
4056 browser.setCurrentTags(currentNote.getTagNames());
4058 scrollToGuid(currentNoteGuid);
4060 browser.loadingData(false);
4061 if (thumbnailViewer.isActiveWindow())
4064 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4065 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4068 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4070 // Save a generated thumbnail
4071 private void toggleNoteInformation() {
4072 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4073 browserWindow.toggleInformation();
4074 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4075 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4076 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4078 // Listener triggered when a print button is pressed
4079 @SuppressWarnings("unused")
4080 private void printNote() {
4081 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4083 QPrintDialog dialog = new QPrintDialog();
4084 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4085 QPrinter printer = dialog.printer();
4086 browserWindow.getBrowser().print(printer);
4088 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4091 // Listener triggered when the email button is pressed
4092 @SuppressWarnings("unused")
4093 private void emailNote() {
4094 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4096 if (Desktop.isDesktopSupported()) {
4097 Desktop desktop = Desktop.getDesktop();
4099 String text2 = browserWindow.getContentsToEmail();
4100 QUrl url = new QUrl("mailto:");
4101 url.addQueryItem("subject", currentNote.getTitle());
4102 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4103 url.addQueryItem("body", text2);
4104 QDesktopServices.openUrl(url);
4108 if (desktop.isSupported(Desktop.Action.MAIL)) {
4109 URI uriMailTo = null;
4111 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4112 String text = browserWindow.getContentsToEmail();
4113 //text = "<b>" +text +"</b>";
4114 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4115 +"&BODY=" +text, null);
4116 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4117 +"&ATTACHMENT=d:/test.pdf", null);
4118 desktop.mail(uriMailTo);
4119 } catch (URISyntaxException e) {
4120 e.printStackTrace();
4121 } catch (IOException e) {
4122 e.printStackTrace();
4129 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4131 // Reindex all notes
4132 @SuppressWarnings("unused")
4133 private void fullReindex() {
4134 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4135 indexRunner.addWork("REINDEXALL");
4136 setMessage(tr("Database will be reindexed."));
4137 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4139 // Listener when a user wants to reindex a specific note
4140 @SuppressWarnings("unused")
4141 private void reindexNote() {
4142 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4143 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4144 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4146 if (selectedNotebookGUIDs.size() > 1)
4147 setMessage(tr("Notes will be reindexed."));
4149 setMessage(tr("Note will be reindexed."));
4150 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4153 @SuppressWarnings("unused")
4154 private void deleteNote() {
4155 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4156 if (currentNote == null)
4158 if (currentNoteGuid.equals(""))
4161 // If we are deleting non-trash notes
4162 if (currentNote.isActive()) {
4163 if (Global.verifyDelete()) {
4164 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4165 QMessageBox.StandardButton.Yes,
4166 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4170 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4171 selectedNoteGUIDs.add(currentNoteGuid);
4172 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4173 listManager.deleteNote(selectedNoteGUIDs.get(i));
4176 // If we are deleting from the trash.
4177 if (Global.verifyDelete()) {
4178 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4179 QMessageBox.StandardButton.Yes,
4180 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4184 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4185 selectedNoteGUIDs.add(currentNoteGuid);
4186 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4187 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4188 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4189 if (modelIndex != null) {
4190 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4191 String tableGuid = (String)ix.values().toArray()[0];
4192 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4193 listManager.getNoteTableModel().removeRow(j);
4198 listManager.expungeNote(selectedNoteGUIDs.get(i));
4201 currentNoteGuid = "";
4202 listManager.loadNotesIndex();
4203 noteIndexUpdated(false);
4204 refreshEvernoteNote(true);
4205 scrollToGuid(currentNoteGuid);
4206 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4209 @SuppressWarnings("unused")
4210 private void addNote() {
4211 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4212 // browserWindow.setEnabled(true);
4213 browserWindow.setReadOnly(false);
4215 Calendar currentTime = new GregorianCalendar();
4216 StringBuffer noteString = new StringBuffer(100);
4217 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4218 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4221 if (Global.overrideDefaultFont()) {
4222 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4223 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4224 noteString.append("<br clear=\"none\" />\n");
4225 noteString.append("</span>\n</font>\n");
4227 noteString.append("<br clear=\"none\" />\n");
4228 noteString.append("</en-note>");
4230 Long l = new Long(currentTime.getTimeInMillis());
4231 String randint = new String(Long.toString(l));
4233 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4235 // for the first non-archived notebook. Finally, if nothing else we
4236 // pick the first notebook in the list.
4237 String notebook = null;
4238 listManager.getNotebookIndex().get(0).getGuid();
4239 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4240 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4241 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4242 notebook = currentSelectedNotebook.text(2);
4244 boolean found = false;
4245 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4246 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4247 boolean match = false;
4248 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4249 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4251 j = listManager.getArchiveNotebookIndex().size();
4255 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4257 // Now we have a list of good notebooks, so we can look for the default
4259 for (int i=0; i<goodNotebooks.size(); i++) {
4260 if (goodNotebooks.get(i).isDefaultNotebook()) {
4261 notebook = goodNotebooks.get(i).getGuid();
4263 i = goodNotebooks.size();
4267 if (goodNotebooks.size() > 0 && !found)
4268 notebook = goodNotebooks.get(0).getGuid();
4271 notebook = listManager.getNotebookIndex().get(0).getGuid();
4274 Note newNote = new Note();
4275 newNote.setUpdateSequenceNum(0);
4276 newNote.setGuid(randint);
4277 newNote.setNotebookGuid(notebook);
4278 newNote.setTitle("");
4279 newNote.setContent(noteString.toString());
4280 newNote.setDeleted(0);
4281 newNote.setCreated(System.currentTimeMillis());
4282 newNote.setUpdated(System.currentTimeMillis());
4283 newNote.setActive(true);
4284 NoteAttributes na = new NoteAttributes();
4285 na.setLatitude(0.0);
4286 na.setLongitude(0.0);
4287 na.setAltitude(0.0);
4288 newNote.setAttributes(new NoteAttributes());
4289 newNote.setTagGuids(new ArrayList<String>());
4290 newNote.setTagNames(new ArrayList<String>());
4292 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4293 if (Global.newNoteWithSelectedTags()) {
4294 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4295 QTreeWidgetItem currentSelection;
4296 for (int i=0; i<selections.size(); i++) {
4297 currentSelection = selections.get(i);
4298 newNote.getTagGuids().add(currentSelection.text(2));
4299 newNote.getTagNames().add(currentSelection.text(0));
4303 conn.getNoteTable().addNote(newNote, true);
4304 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4305 listManager.addNote(newNote);
4306 // noteTableView.insertRow(newNote, true, -1);
4308 currentNote = newNote;
4309 currentNoteGuid = currentNote.getGuid();
4310 refreshEvernoteNote(true);
4311 listManager.countNotebookResults(listManager.getNoteIndex());
4312 browserWindow.titleLabel.setFocus();
4313 browserWindow.titleLabel.selectAll();
4314 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4316 // If the window is hidden, then we want to popup this in an external window &
4319 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4321 // Restore a note from the trash;
4322 @SuppressWarnings("unused")
4323 private void restoreNote() {
4325 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4326 selectedNoteGUIDs.add(currentNoteGuid);
4327 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4328 listManager.restoreNote(selectedNoteGUIDs.get(i));
4330 currentNoteGuid = "";
4331 listManager.loadNotesIndex();
4332 noteIndexUpdated(false);
4335 // Search a note for specific txt
4336 @SuppressWarnings("unused")
4337 private void findText() {
4339 find.setFocusOnTextField();
4341 @SuppressWarnings("unused")
4342 private void doFindText() {
4343 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4346 @SuppressWarnings("unused")
4347 private void updateNoteTitle(String guid, String title) {
4348 listManager.setNoteSynchronized(guid, false);
4350 // Signal received that note content has changed. Normally we just need the guid to remove
4351 // it from the cache.
4352 @SuppressWarnings("unused")
4353 private void invalidateNoteCache(String guid, String content) {
4354 String v = noteCache.remove(guid);
4355 // if (guid.equals(currentNoteGuid) && !noteDirty)
4356 refreshEvernoteNote(true);
4358 // Signal received that a note guid has changed
4359 @SuppressWarnings("unused")
4360 private void noteGuidChanged(String oldGuid, String newGuid) {
4361 if (noteCache.containsKey(oldGuid)) {
4362 if (!oldGuid.equals(currentNoteGuid)) {
4363 String cache = noteCache.get(oldGuid);
4364 noteCache.put(newGuid, cache);
4365 noteCache.remove(oldGuid);
4367 noteCache.remove(oldGuid);
4368 noteCache.put(newGuid, browserWindow.getContent());
4372 listManager.updateNoteGuid(oldGuid, newGuid, false);
4373 if (currentNoteGuid.equals(oldGuid)) {
4374 if (currentNote != null)
4375 currentNote.setGuid(newGuid);
4376 currentNoteGuid = newGuid;
4379 if (externalWindows.containsKey(oldGuid)) {
4380 ExternalBrowse b = externalWindows.get(oldGuid);
4381 externalWindows.remove(oldGuid);
4382 b.getBrowserWindow().getNote().setGuid(newGuid);
4383 externalWindows.put(newGuid, b);
4386 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4387 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4388 noteTableView.proxyModel.addGuid(newGuid);
4389 i=listManager.getNoteIndex().size();
4393 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4394 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4395 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4396 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4400 // Toggle the note editor button bar
4401 private void toggleEditorButtonBar() {
4402 if (browserWindow.buttonsVisible) {
4403 browserWindow.hideButtons();
4404 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4405 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4407 browserWindow.buttonsVisible = true;
4408 showEditorButtons(browserWindow);
4410 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4412 // Show editor buttons
4413 private void showEditorButtons(BrowserWindow browser) {
4414 browser.buttonLayout.setVisible(true);
4415 browser.undoAction.setVisible(false);
4417 browser.undoButton.setVisible(false);
4419 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4420 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4421 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4422 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4423 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4424 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4425 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4426 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4427 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4428 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4429 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4430 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4431 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4432 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4433 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4434 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4435 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4436 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4437 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4438 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4439 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4440 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4441 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4443 private void duplicateNote(String guid) {
4445 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
4446 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4447 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4448 oldNote.setResources(resList);
4449 duplicateNote(oldNote);
4451 private void duplicateNote(Note oldNote) {
4453 // Now that we have a good notebook guid, we need to move the conflicting note
4454 // to the local notebook
4455 Calendar currentTime = new GregorianCalendar();
4456 Long l = new Long(currentTime.getTimeInMillis());
4457 String newGuid = new String(Long.toString(l));
4459 Note newNote = oldNote.deepCopy();
4460 newNote.setUpdateSequenceNum(0);
4461 newNote.setGuid(newGuid);
4462 newNote.setDeleted(0);
4463 newNote.setActive(true);
4464 List<Resource> resList = oldNote.getResources();
4465 if (resList == null)
4466 resList = new ArrayList<Resource>();
4468 for (int i=0; i<resList.size(); i++) {
4470 while (l == prevGuid) {
4471 currentTime = new GregorianCalendar();
4472 l = new Long(currentTime.getTimeInMillis());
4475 String newResGuid = new String(Long.toString(l));
4476 resList.get(i).setNoteGuid(newGuid);
4477 resList.get(i).setGuid(newResGuid);
4478 resList.get(i).setUpdateSequenceNum(0);
4479 resList.get(i).setActive(true);
4480 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
4482 newNote.setResources(resList);
4483 listManager.addNote(newNote);
4484 conn.getNoteTable().addNote(newNote, true);
4485 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4486 noteTableView.insertRow(newNote, true, -1);
4487 listManager.countNotebookResults(listManager.getNoteIndex());
4491 @SuppressWarnings("unused")
4492 private void allNotes() {
4493 clearAttributeFilter();
4494 clearNotebookFilter();
4495 clearSavedSearchFilter();
4498 searchField.clear();
4499 if (Global.mimicEvernoteInterface) {
4500 notebookTree.selectGuid("");
4502 notebookTreeSelection();
4505 @SuppressWarnings("unused")
4506 private void mergeNotes() {
4507 logger.log(logger.HIGH, "Merging notes");
4510 String masterGuid = null;
4511 List<String> sources = new ArrayList<String>();
4513 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4514 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4515 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4516 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4518 masterGuid = (String)ix.values().toArray()[0];
4520 sources.add((String)ix.values().toArray()[0]);
4523 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4524 logger.log(logger.EXTREME, "Children count: "+sources.size());
4525 mergeNoteContents(masterGuid, sources);
4526 currentNoteGuid = masterGuid;
4527 noteIndexUpdated(false);
4528 refreshEvernoteNote(true);
4531 private void mergeNoteContents(String targetGuid, List<String> sources) {
4532 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4533 String newContent = target.getContent();
4534 newContent = newContent.replace("</en-note>", "<br></br>");
4536 for (int i=0; i<sources.size(); i++) {
4537 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4538 if (source.isSetTitle()) {
4539 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4541 String sourceContent = source.getContent();
4542 logger.log(logger.EXTREME, "Merging contents into note");
4543 logger.log(logger.EXTREME, sourceContent);
4544 logger.log(logger.EXTREME, "End of content");
4545 int startOfNote = sourceContent.indexOf("<en-note>");
4546 sourceContent = sourceContent.substring(startOfNote+9);
4547 int endOfNote = sourceContent.indexOf("</en-note>");
4548 sourceContent = sourceContent.substring(0,endOfNote);
4549 newContent = newContent + sourceContent;
4550 logger.log(logger.EXTREME, "New note content");
4551 logger.log(logger.EXTREME, newContent);
4552 logger.log(logger.EXTREME, "End of content");
4553 for (int j=0; j<source.getResourcesSize(); j++) {
4554 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4555 Resource r = source.getResources().get(j);
4556 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4558 Calendar currentTime = new GregorianCalendar();
4559 Long l = new Long(currentTime.getTimeInMillis());
4563 while (l == prevGuid) {
4564 currentTime = new GregorianCalendar();
4565 l = new Long(currentTime.getTimeInMillis());
4567 String newResGuid = new String(Long.toString(l));
4568 newRes.setNoteGuid(targetGuid);
4569 newRes.setGuid(newResGuid);
4570 newRes.setUpdateSequenceNum(0);
4571 newRes.setActive(true);
4572 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4575 logger.log(logger.EXTREME, "Updating note");
4576 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4577 for (int i=0; i<sources.size(); i++) {
4578 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4579 listManager.deleteNote(sources.get(i));
4581 logger.log(logger.EXTREME, "Exiting merge note");
4583 // A resource within a note has had a guid change
4584 @SuppressWarnings("unused")
4585 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4586 if (!oldGuid.equals(newGuid))
4587 Global.resourceMap.put(oldGuid, newGuid);
4589 // View a thumbnail of the note
4590 public void thumbnailView() {
4592 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4593 QFile thumbnail = new QFile(thumbnailName);
4594 if (!thumbnail.exists()) {
4596 QImage img = new QImage();
4597 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4598 thumbnailViewer.setThumbnail(img);
4600 thumbnailViewer.setThumbnail(thumbnailName);
4601 if (!thumbnailViewer.isVisible())
4602 thumbnailViewer.showFullScreen();
4604 // An error happened while saving a note. Inform the user
4605 @SuppressWarnings("unused")
4606 private void saveRunnerError(String guid, String msg) {
4608 String title = "*Unknown*";
4609 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4610 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4611 title = listManager.getMasterNoteIndex().get(i).getTitle();
4612 i=listManager.getMasterNoteIndex().size();
4615 msg = "An error has happened while saving the note \"" +title+
4616 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4617 "As a result, changes to the note may not be saved properly in the database."+
4618 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4619 "\nbe lost. Please review the note to recover any critical data before restarting.";
4621 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4624 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4625 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4626 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4627 // Find an idle preview object
4628 for (int i=0; i<thumbGenerators.size(); i++) {
4629 if (thumbGenerators.get(i).mutex.tryLock()) {
4630 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4631 thumbGenerators.get(i).loadContent(guid, html, zoom);
4635 if (thumbGenerators.size() >= 1) {
4636 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4640 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4641 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4642 thumbGenerators.add(preview);
4644 if (preview.mutex.tryLock()) {
4645 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4646 preview.loadContent(guid, html, zoom);
4648 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4653 //**********************************************************
4654 //**********************************************************
4655 //* Online user actions
4656 //**********************************************************
4657 //**********************************************************
4658 private void setupOnlineMenu() {
4659 if (!Global.isConnected) {
4660 menuBar.noteOnlineHistoryAction.setEnabled(false);
4661 menuBar.selectiveSyncAction.setEnabled(false);
4664 menuBar.noteOnlineHistoryAction.setEnabled(true);
4665 menuBar.selectiveSyncAction.setEnabled(true);
4668 @SuppressWarnings("unused")
4669 private void viewNoteHistory() {
4670 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4672 if (currentNote.getUpdateSequenceNum() == 0) {
4673 setMessage(tr("Note has never been synchronized."));
4674 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4678 setMessage(tr("Getting Note History"));
4680 Note currentOnlineNote = null;
4683 if (Global.isPremium())
4684 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4686 versions = new ArrayList<NoteVersionId>();
4687 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4688 } catch (EDAMUserException e) {
4689 setMessage("EDAMUserException: " +e.getMessage());
4691 } catch (EDAMSystemException e) {
4692 setMessage("EDAMSystemException: " +e.getMessage());
4694 } catch (EDAMNotFoundException e) {
4695 setMessage(tr("Note not found on server."));
4696 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4698 } catch (TException e) {
4699 setMessage("EDAMTransactionException: " +e.getMessage());
4703 // If we've gotten this far, we have a good note.
4704 if (historyWindow == null) {
4705 historyWindow = new OnlineNoteHistory(logger, conn);
4706 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4707 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4708 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4710 historyWindow.historyCombo.clear();
4712 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4713 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4715 historyWindow.setCurrent(isDirty);
4717 loadHistoryWindowContent(currentOnlineNote);
4718 historyWindow.load(versions);
4719 setMessage(tr("History retrieved"));
4721 historyWindow.exec();
4723 private Note reloadHistoryWindow(String selection) {
4725 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4726 String dateTimeFormat = new String(fmt);
4727 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4731 for (int i=0; i<versions.size(); i++) {
4732 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4733 if (versionDate.toString().equals(selection))
4737 if (index > -1 || selection.indexOf("Current") > -1) {
4738 Note historyNote = null;
4741 usn = versions.get(index).getUpdateSequenceNum();
4742 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4744 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4745 } catch (EDAMUserException e) {
4746 setMessage("EDAMUserException: " +e.getMessage());
4749 } catch (EDAMSystemException e) {
4750 setMessage("EDAMSystemException: " +e.getMessage());
4753 } catch (EDAMNotFoundException e) {
4754 setMessage("EDAMNotFoundException: " +e.getMessage());
4757 } catch (TException e) {
4758 setMessage("EDAMTransactionException: " +e.getMessage());
4764 if (historyNote != null)
4765 historyWindow.setContent(historyNote);
4771 private void loadHistoryWindowContent(Note note) {
4772 note.setUpdateSequenceNum(0);
4773 historyWindow.setContent(note);
4775 @SuppressWarnings("unused")
4776 private void restoreHistoryNoteAsNew() {
4777 setMessage(tr("Restoring as new note."));
4778 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4779 setMessage(tr("Note has been restored as a new note."));
4781 @SuppressWarnings("unused")
4782 private void restoreHistoryNote() {
4783 setMessage(tr("Restoring note."));
4784 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
4785 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
4788 for (int i=0; i<n.getResourcesSize(); i++) {
4789 n.getResources().get(i).setActive(true);
4790 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
4792 listManager.addNote(n);
4793 conn.getNoteTable().addNote(n, true);
4794 refreshEvernoteNote(true);
4795 setMessage(tr("Note has been restored."));
4797 @SuppressWarnings("unused")
4798 private void setupSelectiveSync() {
4800 // Get a list of valid notebooks
4801 List<Notebook> notebooks = null;
4802 List<Tag> tags = null;
4804 notebooks = syncRunner.noteStore.listNotebooks(syncRunner.authToken);
4805 tags = syncRunner.noteStore.listTags(syncRunner.authToken);
4806 } catch (EDAMUserException e) {
4807 setMessage("EDAMUserException: " +e.getMessage());
4809 } catch (EDAMSystemException e) {
4810 setMessage("EDAMSystemException: " +e.getMessage());
4812 } catch (TException e) {
4813 setMessage("EDAMTransactionException: " +e.getMessage());
4817 // Split up notebooks into synchronized & non-synchronized
4818 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
4819 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4821 for (int i=notebooks.size()-1; i>=0; i--) {
4822 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
4823 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
4824 ignoredBooks.add(notebooks.get(i));
4825 j=dbIgnoredNotebooks.size();
4830 // split up tags into synchronized & non-synchronized
4831 List<Tag> ignoredTags = new ArrayList<Tag>();
4832 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
4834 for (int i=tags.size()-1; i>=0; i--) {
4835 for (int j=0; j<dbIgnoredTags.size(); j++) {
4836 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
4837 ignoredTags.add(tags.get(i));
4838 j=dbIgnoredTags.size();
4843 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags);
4845 if (!ignore.okClicked())
4850 // Clear out old notebooks & add the new ones
4851 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4852 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
4853 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
4856 List<String> newNotebooks = new ArrayList<String>();
4857 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
4858 String text = ignore.getIgnoredBookList().takeItem(i).text();
4859 for (int j=0; j<notebooks.size(); j++) {
4860 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
4861 Notebook n = notebooks.get(j);
4862 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
4864 newNotebooks.add(n.getGuid());
4869 // Clear out old tags & add new ones
4870 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
4871 for (int i=0; i<oldIgnoreTags.size(); i++) {
4872 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
4875 List<String> newTags = new ArrayList<String>();
4876 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
4877 String text = ignore.getIgnoredTagList().takeItem(i).text();
4878 for (int j=0; j<tags.size(); j++) {
4879 if (tags.get(j).getName().equalsIgnoreCase(text)) {
4880 Tag t = tags.get(j);
4881 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
4882 newTags.add(t.getGuid());
4888 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags);
4894 //**********************************************************
4895 //**********************************************************
4896 //* XML Modifying methods
4897 //**********************************************************
4898 //**********************************************************
4899 // An error has happended fetching a resource. let the user know
4900 private void resourceErrorMessage() {
4903 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4904 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4905 "In a perfect world this wouldn't happen, but it has.\n" +
4906 "It is embarasing when a program like me, designed to save all your\n"+
4907 "precious data, has a problem finding data.\n\n" +
4908 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
4909 "In the mean time, I'm not going to let you make changes to this note.\n" +
4910 "Don't get angry. I'm doing it to prevent you from messing up\n"+
4911 "this note on the Evernote servers. Sorry."+
4912 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4914 browserWindow.setReadOnly(true);
4920 //**********************************************************
4921 //**********************************************************
4923 //**********************************************************
4924 //**********************************************************
4925 // We should now do a sync with Evernote
4926 private void syncTimer() {
4927 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
4928 syncRunner.syncNeeded = true;
4929 syncRunner.disableUploads = Global.disableUploads;
4931 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
4933 private void syncStart() {
4934 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
4936 if (!syncRunning && Global.isConnected) {
4937 syncRunner.setConnected(true);
4938 syncRunner.setKeepRunning(Global.keepRunning);
4939 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
4941 if (syncThreadsReady > 0) {
4942 indexRunner.interrupt = true;
4943 saveNoteIndexWidth();
4944 saveNoteColumnPositions();
4945 if (syncRunner.addWork("SYNC")) {
4947 syncRunner.syncNeeded = true;
4952 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
4954 @SuppressWarnings("unused")
4955 private void syncThreadComplete(Boolean refreshNeeded) {
4956 setMessage(tr("Finalizing Synchronization"));
4958 syncRunning = false;
4959 syncRunner.syncNeeded = false;
4960 synchronizeAnimationTimer.stop();
4961 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
4963 if (currentNote == null) {
4964 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
4966 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
4967 noteIndexUpdated(false);
4968 noteTableView.selectionModel().blockSignals(true);
4969 scrollToGuid(currentNoteGuid);
4970 noteTableView.selectionModel().blockSignals(false);
4971 refreshEvernoteNote(false);
4972 scrollToGuid(currentNoteGuid);
4974 if (!syncRunner.error)
4975 setMessage(tr("Synchronization Complete"));
4977 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
4978 logger.log(logger.MEDIUM, "Sync complete.");
4980 public void saveUploadAmount(long t) {
4981 Global.saveUploadAmount(t);
4983 public void saveUserInformation(User user) {
4984 Global.saveUserInformation(user);
4986 public void saveEvernoteUpdateCount(int i) {
4987 Global.saveEvernoteUpdateCount(i);
4989 public void refreshLists() {
4990 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
4992 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
4993 tagIndexUpdated(true);
4994 notebookIndexUpdated();
4995 savedSearchIndexUpdated();
4996 listManager.loadNotesIndex();
4998 noteTableView.selectionModel().blockSignals(true);
4999 noteIndexUpdated(true);
5000 noteTableView.selectionModel().blockSignals(false);
5001 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5005 @SuppressWarnings("unused")
5006 private void authTimer() {
5007 Calendar cal = Calendar.getInstance();
5009 // If we are not connected let's get out of here
5010 if (!Global.isConnected)
5013 // If this is the first time through, then we need to set this
5014 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5015 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5017 // long now = new Date().getTime();
5018 // if (now > Global.authRefreshTime && Global.isConnected) {
5019 syncRunner.authRefreshNeeded = true;
5023 @SuppressWarnings("unused")
5024 private void authRefreshComplete(boolean goodSync) {
5025 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5026 Global.isConnected = syncRunner.isConnected;
5028 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5029 authTimer.start(1000*60*15);
5030 logger.log(logger.LOW, "Authentication token has been renewed");
5031 // setMessage("Authentication token has been renewed.");
5033 authTimer.start(1000*60*5);
5034 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5035 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5037 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5041 @SuppressWarnings("unused")
5042 private synchronized void indexTimer() {
5043 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5046 if (!indexDisabled && indexRunner.idle) {
5047 indexRunner.addWork("SCAN");
5049 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5052 @SuppressWarnings("unused")
5053 private void indexStarted() {
5054 setMessage(tr("Indexing notes"));
5056 @SuppressWarnings("unused")
5057 private void indexComplete() {
5058 setMessage(tr("Index complete"));
5060 @SuppressWarnings("unused")
5061 private synchronized void toggleNoteIndexing() {
5062 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5063 indexDisabled = !indexDisabled;
5065 setMessage(tr("Indexing is now enabled."));
5067 setMessage(tr("Indexing is now disabled."));
5068 menuBar.disableIndexing.setChecked(indexDisabled);
5069 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5072 @SuppressWarnings("unused")
5073 private void threadMonitorCheck() {
5078 alive = listManager.threadCheck(Global.tagCounterThreadId);
5081 if (tagDeadCount > MAX)
5082 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5083 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5087 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5089 notebookThreadDeadCount++;
5090 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5091 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5093 notebookThreadDeadCount=0;
5095 alive = listManager.threadCheck(Global.trashCounterThreadId);
5098 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5099 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5103 alive = listManager.threadCheck(Global.saveThreadId);
5105 saveThreadDeadCount++;
5106 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5107 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5109 saveThreadDeadCount=0;
5111 if (!syncThread.isAlive()) {
5112 syncThreadDeadCount++;
5113 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5114 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5116 syncThreadDeadCount=0;
5118 if (!indexThread.isAlive()) {
5119 indexThreadDeadCount++;
5120 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5121 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5123 indexThreadDeadCount=0;
5128 private void thumbnailTimer() {
5129 if (Global.enableThumbnails() && conn.getNoteTable().getThumbnailNeededCount() > 1) {
5130 thumbnailTimer.setInterval(10*1000);
5131 thumbnailRunner.addWork("SCAN");
5133 thumbnailTimer.setInterval(60*1000);
5137 //**************************************************
5138 //* Backup & Restore
5139 //**************************************************
5140 @SuppressWarnings("unused")
5141 private void databaseBackup() {
5142 QFileDialog fd = new QFileDialog(this);
5143 fd.setFileMode(FileMode.AnyFile);
5144 fd.setConfirmOverwrite(true);
5145 fd.setWindowTitle(tr("Backup Database"));
5146 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5147 fd.setAcceptMode(AcceptMode.AcceptSave);
5148 fd.setDirectory(System.getProperty("user.home"));
5149 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5155 setMessage(tr("Backing up database"));
5157 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5159 ExportData noteWriter = new ExportData(conn, true);
5160 String fileName = fd.selectedFiles().get(0);
5162 if (!fileName.endsWith(".nnex"))
5163 fileName = fileName +".nnex";
5164 noteWriter.exportData(fileName);
5165 setMessage(tr("Database backup completed."));
5170 @SuppressWarnings("unused")
5171 private void databaseRestore() {
5172 if (QMessageBox.question(this, tr("Confirmation"),
5173 tr("This is used to restore a database from backups.\n" +
5174 "It is HIGHLY recommened that this only be used to populate\n" +
5175 "an empty database. Restoring into a database that\n already has data" +
5176 " can cause problems.\n\nAre you sure you want to continue?"),
5177 QMessageBox.StandardButton.Yes,
5178 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5183 QFileDialog fd = new QFileDialog(this);
5184 fd.setFileMode(FileMode.ExistingFile);
5185 fd.setConfirmOverwrite(true);
5186 fd.setWindowTitle(tr("Restore Database"));
5187 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5188 fd.setAcceptMode(AcceptMode.AcceptOpen);
5189 fd.setDirectory(System.getProperty("user.home"));
5190 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5196 setMessage(tr("Restoring database"));
5197 ImportData noteReader = new ImportData(conn, true);
5198 noteReader.importData(fd.selectedFiles().get(0));
5200 if (noteReader.lastError != 0) {
5201 setMessage(noteReader.getErrorMessage());
5202 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5207 listManager.loadNoteTitleColors();
5209 refreshEvernoteNote(true);
5210 setMessage(tr("Database has been restored."));
5213 @SuppressWarnings("unused")
5214 private void exportNotes() {
5215 QFileDialog fd = new QFileDialog(this);
5216 fd.setFileMode(FileMode.AnyFile);
5217 fd.setConfirmOverwrite(true);
5218 fd.setWindowTitle(tr("Backup Database"));
5219 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5220 fd.setAcceptMode(AcceptMode.AcceptSave);
5221 fd.setDirectory(System.getProperty("user.home"));
5222 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5228 setMessage(tr("Exporting Notes"));
5231 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5232 selectedNoteGUIDs.add(currentNoteGuid);
5234 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5235 String fileName = fd.selectedFiles().get(0);
5237 if (!fileName.endsWith(".nnex"))
5238 fileName = fileName +".nnex";
5239 noteWriter.exportData(fileName);
5240 setMessage(tr("Export completed."));
5246 @SuppressWarnings("unused")
5247 private void importNotes() {
5248 QFileDialog fd = new QFileDialog(this);
5249 fd.setFileMode(FileMode.ExistingFile);
5250 fd.setConfirmOverwrite(true);
5251 fd.setWindowTitle(tr("Import Notes"));
5252 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5253 fd.setAcceptMode(AcceptMode.AcceptOpen);
5254 fd.setDirectory(System.getProperty("user.home"));
5255 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5261 setMessage("Importing Notes");
5264 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5265 selectedNoteGUIDs.add(currentNoteGuid);
5267 ImportData noteReader = new ImportData(conn, false);
5268 String fileName = fd.selectedFiles().get(0);
5270 if (!fileName.endsWith(".nnex"))
5271 fileName = fileName +".nnex";
5272 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5273 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5275 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5277 noteReader.importData(fileName);
5279 if (noteReader.lastError != 0) {
5280 setMessage(noteReader.getErrorMessage());
5281 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5286 listManager.loadNoteTitleColors();
5288 refreshEvernoteNote(false);
5289 setMessage(tr("Notes have been imported."));
5292 setMessage("Import completed.");
5299 //**************************************************
5300 //* Duplicate a note
5301 //**************************************************
5302 @SuppressWarnings("unused")
5303 private void duplicateNote() {
5305 duplicateNote(currentNoteGuid);
5310 //**************************************************
5312 //**************************************************
5313 public void setupFolderImports() {
5314 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5316 if (importKeepWatcher == null)
5317 importKeepWatcher = new QFileSystemWatcher();
5318 if (importDeleteWatcher == null) {
5319 importDeleteWatcher = new QFileSystemWatcher();
5320 for (int i=0; i<records.size(); i++) {
5321 if (!records.get(i).keep)
5322 folderImportDelete(records.get(i).folder);
5328 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5329 for (int i=0; i<records.size(); i++) {
5330 if (records.get(i).keep)
5331 importKeepWatcher.addPath(records.get(i).folder);
5333 importDeleteWatcher.addPath(records.get(i).folder);
5336 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5337 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5339 // Look at the files already there so we don't import them again if a new file is created
5340 if (importedFiles == null) {
5341 importedFiles = new ArrayList<String>();
5342 for (int j=0; j<records.size(); j++) {
5343 QDir dir = new QDir(records.get(j).folder);
5344 List<QFileInfo> list = dir.entryInfoList();
5345 for (int k=0; k<list.size(); k++) {
5346 if (list.get(k).isFile())
5347 importedFiles.add(list.get(k).absoluteFilePath());
5352 public void folderImport() {
5353 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5354 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5356 if (!dialog.okClicked())
5359 // We have some sort of update.
5360 if (importKeepWatcher.directories().size() > 0)
5361 importKeepWatcher.removePaths(importKeepWatcher.directories());
5362 if (importDeleteWatcher.directories().size() > 0)
5363 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5365 conn.getWatchFolderTable().expungeAll();
5366 // Start building from the table
5367 for (int i=0; i<dialog.table.rowCount(); i++) {
5368 QTableWidgetItem item = dialog.table.item(i, 0);
5369 String dir = item.text();
5370 item = dialog.table.item(i, 1);
5371 String notebook = item.text();
5372 item = dialog.table.item(i, 2);
5374 if (item.text().equalsIgnoreCase("Keep"))
5379 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5380 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5382 setupFolderImports();
5385 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5387 String whichOS = System.getProperty("os.name");
5388 if (whichOS.contains("Windows"))
5389 dirName = dirName.replace('/','\\');
5391 FileImporter importer = new FileImporter(logger, conn);
5393 QDir dir = new QDir(dirName);
5394 List<QFileInfo> list = dir.entryInfoList();
5395 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5397 for (int i=0; i<list.size(); i++){
5399 boolean redundant = false;
5400 // Check if we've already imported this one or if it existed before
5401 for (int j=0; j<importedFiles.size(); j++) {
5402 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5407 importer.setFileInfo(list.get(i));
5408 importer.setFileName(list.get(i).absoluteFilePath());
5411 if (list.get(i).isFile() && importer.isValidType()) {
5413 if (!importer.importFile()) {
5414 // If we can't get to the file, it is probably locked. We'll try again later.
5415 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5416 importFilesKeep.add(list.get(i).absoluteFilePath());
5420 Note newNote = importer.getNote();
5421 newNote.setNotebookGuid(notebook);
5422 newNote.setTitle(dir.at(i));
5423 listManager.addNote(newNote);
5424 conn.getNoteTable().addNote(newNote, true);
5425 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5426 noteTableView.insertRow(newNote, true, -1);
5427 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5428 listManager.countNotebookResults(listManager.getNoteIndex());
5429 importedFiles.add(list.get(i).absoluteFilePath());
5437 public void folderImportDelete(String dirName) {
5439 String whichOS = System.getProperty("os.name");
5440 if (whichOS.contains("Windows"))
5441 dirName = dirName.replace('/','\\');
5443 FileImporter importer = new FileImporter(logger, conn);
5444 QDir dir = new QDir(dirName);
5445 List<QFileInfo> list = dir.entryInfoList();
5446 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5448 for (int i=0; i<list.size(); i++){
5449 importer.setFileInfo(list.get(i));
5450 importer.setFileName(list.get(i).absoluteFilePath());
5452 if (list.get(i).isFile() && importer.isValidType()) {
5454 if (!importer.importFile()) {
5455 // If we can't get to the file, it is probably locked. We'll try again later.
5456 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5457 importFilesKeep.add(list.get(i).absoluteFilePath());
5461 Note newNote = importer.getNote();
5462 newNote.setNotebookGuid(notebook);
5463 newNote.setTitle(dir.at(i));
5464 listManager.addNote(newNote);
5465 conn.getNoteTable().addNote(newNote, true);
5466 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5467 noteTableView.insertRow(newNote, true, -1);
5468 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5469 listManager.countNotebookResults(listManager.getNoteIndex());
5470 dir.remove(dir.at(i));
5476 //**************************************************
5478 //**************************************************
5479 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5480 logger.log(logger.HIGH, "Entering exernalFileEdited");
5482 // Strip URL prefix and base dir path
5483 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5484 String name = fileName.replace(dPath, "");
5485 int pos = name.lastIndexOf('.');
5488 guid = guid.substring(0,pos);
5490 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5492 guid = name.substring(0, pos);
5495 QFile file = new QFile(fileName);
5496 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5497 // If we can't get to the file, it is probably locked. We'll try again later.
5498 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5499 externalFiles.add(fileName);
5502 QByteArray binData = file.readAll();
5504 if (binData.size() == 0) {
5505 // If we can't get to the file, it is probably locked. We'll try again later.
5506 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5507 externalFiles.add(fileName);
5511 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5513 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5514 if (r == null || r.getData() == null || r.getData().getBody() == null)
5516 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5517 MessageDigest md = MessageDigest.getInstance("MD5");
5518 md.update(binData.toByteArray());
5519 byte[] hash = md.digest();
5520 String newHash = Global.byteArrayToHexString(hash);
5521 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5522 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5524 if (externalWindows.containsKey(r.getNoteGuid())) {
5525 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5526 r.getGuid(), oldHash, newHash);
5528 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5529 Data data = r.getData();
5530 data.setBody(binData.toByteArray());
5531 data.setBodyHash(hash);
5532 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5534 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5536 if (r.getNoteGuid().equals(currentNoteGuid)) {
5537 QWebSettings.setMaximumPagesInCache(0);
5538 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5539 refreshEvernoteNote(true);
5540 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5543 if (externalWindows.containsKey(r.getNoteGuid())) {
5544 QWebSettings.setMaximumPagesInCache(0);
5545 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5546 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5550 logger.log(logger.HIGH, "Exiting externalFielEdited");
5552 // This is a timer event that tries to save any external files that were edited. This
5553 // is only needed if we couldn't save a file earlier.
5554 public void externalFileEditedSaver() {
5555 for (int i=externalFiles.size()-1; i>=0; i--) {
5557 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5558 externalFileEdited(externalFiles.get(i));
5559 externalFiles.remove(i);
5560 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5562 for (int i=0; i<importFilesKeep.size(); i++) {
5564 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5565 folderImportKeep(importFilesKeep.get(i));
5566 importFilesKeep.remove(i);
5567 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5569 for (int i=0; i<importFilesDelete.size(); i++) {
5570 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5571 folderImportDelete(importFilesDelete.get(i));
5572 importFilesDelete.remove(i);
5579 // If an attachment on the current note was edited, we need to update the current notes's hash
5580 // Update a note content's hash. This happens if a resource is edited outside of NN
5581 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5582 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5584 for (;position>-1;) {
5585 endPos = browser.getContent().indexOf(">", position+1);
5586 String oldSegment = browser.getContent().substring(position,endPos);
5587 int hashPos = oldSegment.indexOf("hash=\"");
5588 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5589 String hash = oldSegment.substring(hashPos+6, hashEnd);
5590 if (hash.equalsIgnoreCase(oldHash)) {
5591 String newSegment = oldSegment.replace(oldHash, newHash);
5592 String content = browser.getContent().substring(0,position) +
5594 browser.getContent().substring(endPos);
5595 browser.getBrowser().setContent(new QByteArray(content));;
5598 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5603 //*************************************************
5604 //* Minimize to tray
5605 //*************************************************
5607 public void changeEvent(QEvent e) {
5608 if (e.type() == QEvent.Type.WindowStateChange) {
5609 if (isMinimized() && Global.showTrayIcon()) {
5611 QTimer.singleShot(10, this, "hide()");
5615 windowMaximized = true;
5617 windowMaximized = false;
5621 //*************************************************
5622 //* Check database userid & passwords
5623 //*************************************************
5624 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5625 Connection connection;
5628 Class.forName("org.h2.Driver");
5629 } catch (ClassNotFoundException e1) {
5630 e1.printStackTrace();
5635 String passwordString = null;
5636 if (cypherPassword==null || cypherPassword.trim().equals(""))
5637 passwordString = userPassword;
5639 passwordString = cypherPassword+" "+userPassword;
5640 connection = DriverManager.getConnection(url,userid,passwordString);
5641 } catch (SQLException e) {
5646 } catch (SQLException e) {
5647 e.printStackTrace();