2 * This file is part of NeverNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QModelIndex;
79 import com.trolltech.qt.core.QSize;
80 import com.trolltech.qt.core.QTemporaryFile;
81 import com.trolltech.qt.core.QTextCodec;
82 import com.trolltech.qt.core.QThreadPool;
83 import com.trolltech.qt.core.QTimer;
84 import com.trolltech.qt.core.QTranslator;
85 import com.trolltech.qt.core.QUrl;
86 import com.trolltech.qt.core.Qt;
87 import com.trolltech.qt.core.Qt.BGMode;
88 import com.trolltech.qt.core.Qt.ItemDataRole;
89 import com.trolltech.qt.core.Qt.SortOrder;
90 import com.trolltech.qt.core.Qt.WidgetAttribute;
91 import com.trolltech.qt.gui.QAbstractItemView;
92 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
93 import com.trolltech.qt.gui.QAction;
94 import com.trolltech.qt.gui.QApplication;
95 import com.trolltech.qt.gui.QCloseEvent;
96 import com.trolltech.qt.gui.QColor;
97 import com.trolltech.qt.gui.QComboBox;
98 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
99 import com.trolltech.qt.gui.QCursor;
100 import com.trolltech.qt.gui.QDesktopServices;
101 import com.trolltech.qt.gui.QDialog;
102 import com.trolltech.qt.gui.QFileDialog;
103 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
104 import com.trolltech.qt.gui.QFileDialog.FileMode;
105 import com.trolltech.qt.gui.QGridLayout;
106 import com.trolltech.qt.gui.QHBoxLayout;
107 import com.trolltech.qt.gui.QIcon;
108 import com.trolltech.qt.gui.QImage;
109 import com.trolltech.qt.gui.QLabel;
110 import com.trolltech.qt.gui.QListWidget;
111 import com.trolltech.qt.gui.QMainWindow;
112 import com.trolltech.qt.gui.QMenu;
113 import com.trolltech.qt.gui.QMessageBox;
114 import com.trolltech.qt.gui.QMessageBox.StandardButton;
115 import com.trolltech.qt.gui.QPainter;
116 import com.trolltech.qt.gui.QPalette.ColorRole;
117 import com.trolltech.qt.gui.QPixmap;
118 import com.trolltech.qt.gui.QPrintDialog;
119 import com.trolltech.qt.gui.QPrinter;
120 import com.trolltech.qt.gui.QSizePolicy;
121 import com.trolltech.qt.gui.QSizePolicy.Policy;
122 import com.trolltech.qt.gui.QSpinBox;
123 import com.trolltech.qt.gui.QSplashScreen;
124 import com.trolltech.qt.gui.QSplitter;
125 import com.trolltech.qt.gui.QStatusBar;
126 import com.trolltech.qt.gui.QSystemTrayIcon;
127 import com.trolltech.qt.gui.QTableWidgetItem;
128 import com.trolltech.qt.gui.QTextEdit;
129 import com.trolltech.qt.gui.QToolBar;
130 import com.trolltech.qt.gui.QTreeWidgetItem;
131 import com.trolltech.qt.network.QNetworkAccessManager;
132 import com.trolltech.qt.network.QNetworkReply;
133 import com.trolltech.qt.network.QNetworkRequest;
134 import com.trolltech.qt.webkit.QWebPage.WebAction;
135 import com.trolltech.qt.webkit.QWebSettings;
137 import cx.fbn.nevernote.config.InitializationException;
138 import cx.fbn.nevernote.config.StartupConfig;
139 import cx.fbn.nevernote.dialog.AccountDialog;
140 import cx.fbn.nevernote.dialog.ConfigDialog;
141 import cx.fbn.nevernote.dialog.DBEncryptDialog;
142 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
143 import cx.fbn.nevernote.dialog.DatabaseStatus;
144 import cx.fbn.nevernote.dialog.FindDialog;
145 import cx.fbn.nevernote.dialog.IgnoreSync;
146 import cx.fbn.nevernote.dialog.LoginDialog;
147 import cx.fbn.nevernote.dialog.NotebookArchive;
148 import cx.fbn.nevernote.dialog.NotebookEdit;
149 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
150 import cx.fbn.nevernote.dialog.PublishNotebook;
151 import cx.fbn.nevernote.dialog.SavedSearchEdit;
152 import cx.fbn.nevernote.dialog.SetIcon;
153 import cx.fbn.nevernote.dialog.ShareNotebook;
154 import cx.fbn.nevernote.dialog.StackNotebook;
155 import cx.fbn.nevernote.dialog.TagEdit;
156 import cx.fbn.nevernote.dialog.ThumbnailViewer;
157 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
158 import cx.fbn.nevernote.dialog.WatchFolder;
159 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
160 import cx.fbn.nevernote.filters.FilterEditorTags;
161 import cx.fbn.nevernote.gui.AttributeTreeWidget;
162 import cx.fbn.nevernote.gui.BrowserWindow;
163 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
164 import cx.fbn.nevernote.gui.ExternalBrowse;
165 import cx.fbn.nevernote.gui.MainMenuBar;
166 import cx.fbn.nevernote.gui.NotebookTreeWidget;
167 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
168 import cx.fbn.nevernote.gui.TableView;
169 import cx.fbn.nevernote.gui.TagTreeWidget;
170 import cx.fbn.nevernote.gui.Thumbnailer;
171 import cx.fbn.nevernote.gui.TrashTreeWidget;
172 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
173 import cx.fbn.nevernote.sql.DatabaseConnection;
174 import cx.fbn.nevernote.sql.WatchFolderRecord;
175 import cx.fbn.nevernote.threads.IndexRunner;
176 import cx.fbn.nevernote.threads.SyncRunner;
177 import cx.fbn.nevernote.threads.ThumbnailRunner;
178 import cx.fbn.nevernote.utilities.AESEncrypter;
179 import cx.fbn.nevernote.utilities.ApplicationLogger;
180 import cx.fbn.nevernote.utilities.FileImporter;
181 import cx.fbn.nevernote.utilities.FileUtils;
182 import cx.fbn.nevernote.utilities.ListManager;
183 import cx.fbn.nevernote.utilities.SyncTimes;
184 import cx.fbn.nevernote.xml.ExportData;
185 import cx.fbn.nevernote.xml.ImportData;
186 import cx.fbn.nevernote.xml.NoteFormatter;
189 public class NeverNote extends QMainWindow{
191 QStatusBar statusBar; // Application status bar
193 DatabaseConnection conn;
195 MainMenuBar menuBar; // Main menu bar
196 FindDialog find; // Text search in note dialog
197 List<String> emitLog; // Messages displayed in the status bar;
198 QSystemTrayIcon trayIcon; // little tray icon
199 QMenu trayMenu; // System tray menu
200 QAction trayExitAction; // Exit the application
201 QAction trayShowAction; // toggle the show/hide action
202 QAction trayAddNoteAction; // Add a note from the system tray
203 QNetworkAccessManager versionChecker; // Used when checking for new versions
205 NotebookTreeWidget notebookTree; // List of notebooks
206 AttributeTreeWidget attributeTree; // List of note attributes
207 TagTreeWidget tagTree; // list of user created tags
208 SavedSearchTreeWidget savedSearchTree; // list of saved searches
209 TrashTreeWidget trashTree; // Trashcan
210 TableView noteTableView; // List of notes (the widget).
212 public BrowserWindow browserWindow; // Window containing browser & labels
213 public QToolBar toolBar; // The tool bar under the menu
214 QComboBox searchField; // search filter bar on the toolbar;
215 boolean searchPerformed = false; // Search was done?
216 QuotaProgressBar quotaBar; // The current quota usage
218 ApplicationLogger logger;
219 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
220 List<String> selectedTagGUIDs; // List of selected tag GUIDs
221 List<String> selectedNoteGUIDs; // List of selected notes
222 String selectedSavedSearchGUID; // Currently selected saved searches
223 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
225 NoteFilter filter; // Note filter
226 String currentNoteGuid; // GUID of the current note
227 Note currentNote; // The currently viewed note
228 boolean noteDirty; // Has the note been changed?
229 boolean inkNote; // if this is an ink note, it is read only
230 boolean readOnly; // Is this note read-only?
233 ListManager listManager; // DB runnable task
235 List<QTemporaryFile> tempFiles; // Array of temporary files;
237 QTimer indexTimer; // timer to start the index thread
238 IndexRunner indexRunner; // thread to index notes
241 QTimer syncTimer; // Sync on an interval
242 QTimer syncDelayTimer; // Sync delay to free up database
243 SyncRunner syncRunner; // thread to do a sync.
244 QThread syncThread; // Thread which talks to evernote
245 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
246 QThread thumbnailThread; // Thread that generates pretty pictures
247 QTimer saveTimer; // Timer to save note contents
249 QTimer authTimer; // Refresh authentication
250 QTimer externalFileSaveTimer; // Save files altered externally
251 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
252 List<String> externalFiles; // External files to save later
253 List<String> importFilesKeep; // Auto-import files to save later
254 List<String> importFilesDelete; // Auto-import files to save later
256 int indexTime; // how often to try and index
257 boolean indexRunning; // Is indexing running?
258 boolean indexDisabled; // Is indexing disabled?
260 int syncThreadsReady; // number of sync threads that are free
261 int syncTime; // Sync interval
262 boolean syncRunning; // Is sync running?
263 boolean automaticSync; // do sync automatically?
264 QTreeWidgetItem attributeTreeSelected;
266 QAction prevButton; // Go to the previous item viewed
267 QAction nextButton; // Go to the next item in the history
268 QAction downButton; // Go to the next item in the list
269 QAction upButton; // Go to the prev. item in the list;
270 QAction synchronizeButton; // Synchronize with Evernote
271 QAction allNotesButton; // Reset & view all notes
272 QTimer synchronizeAnimationTimer; // Timer to change animation button
273 int synchronizeIconAngle; // Used to rotate sync icon
274 QAction printButton; // Print Button
275 QAction tagButton; // Tag edit button
276 QAction attributeButton; // Attribute information button
277 QAction emailButton; // Email button
278 QAction deleteButton; // Delete button
279 QAction newButton; // new Note Button;
280 QSpinBox zoomSpinner; // Zoom zoom
281 QAction searchClearButton; // Clear the search field
283 QSplitter mainLeftRightSplitter; // main splitter for left/right side
284 QSplitter leftSplitter1; // first left hand splitter
285 QSplitter browserIndexSplitter; // splitter between note index & note text
287 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
288 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
289 List<String> importedFiles; // History of imported files (so we don't import twice)
291 OnlineNoteHistory historyWindow; // online history window
292 List<NoteVersionId> versions; // history versions
294 QTimer threadMonitorTimer; // Timer to watch threads.
295 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
296 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
297 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
298 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
299 int tagDeadCount=0; // number of consecutive dead times for the tag thread
300 int trashDeadCount=0; // number of consecutive dead times for the trash thread
301 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
303 HashMap<String, String> noteCache; // Cash of note content
304 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
305 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
306 List<String> historyGuids; // GUIDs of previously viewed items
307 int historyPosition; // Position within the viewed items
308 boolean fromHistory; // Is this from the history queue?
309 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
310 List<Thumbnailer> thumbGenerators; // generate preview image
311 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
312 boolean encryptOnShutdown; // should I encrypt when I close?
313 boolean decryptOnShutdown; // should I decrypt on shutdown;
314 String encryptCipher; // What cipher should I use?
315 Signal0 minimizeToTray;
316 boolean windowMaximized = false; // Keep track of the window state for restores
317 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
318 List<QPixmap> syncIcons; // Array of icons used in sync animation
319 private boolean closeAction = false; // Used to say when to close or when to minimize
320 private static Logger log = Logger.getLogger(NeverNote.class);
323 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
326 //***************************************************************
327 //***************************************************************
328 //** Constructor & main entry point
329 //***************************************************************
330 //***************************************************************
331 // Application Constructor
332 @SuppressWarnings("static-access")
333 public NeverNote(DatabaseConnection dbConn) {
335 if (conn.getConnection() == null) {
336 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
337 "is accessing the database or NeverNote is already running.\n\n" +
338 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
340 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
344 thread().setPriority(Thread.MAX_PRIORITY);
346 logger = new ApplicationLogger("nevernote.log");
347 logger.log(logger.HIGH, "Starting Application");
349 decryptOnShutdown = false;
350 encryptOnShutdown = false;
351 conn.checkDatabaseVersion();
355 // Start building the invalid XML tables
356 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
357 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
359 for (int i=0; i<elements.size(); i++) {
360 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
363 logger.log(logger.EXTREME, "Starting GUI build");
365 QTranslator nevernoteTranslator = new QTranslator();
366 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
367 QApplication.instance().installTranslator(nevernoteTranslator);
369 Global.originalPalette = QApplication.palette();
370 QApplication.setStyle(Global.getStyle());
371 if (Global.useStandardPalette())
372 QApplication.setPalette(QApplication.style().standardPalette());
373 setWindowTitle("NeverNote");
375 mainLeftRightSplitter = new QSplitter();
376 setCentralWidget(mainLeftRightSplitter);
377 leftSplitter1 = new QSplitter();
378 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
380 browserIndexSplitter = new QSplitter();
381 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
383 //* Setup threads & thread timers
384 int indexRunnerCount = Global.getIndexThreads();
385 indexRunnerCount = 1;
386 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
388 logger.log(logger.EXTREME, "Building list manager");
389 listManager = new ListManager(conn, logger);
391 logger.log(logger.EXTREME, "Building index runners & timers");
392 indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
393 indexThread = new QThread(indexRunner, "Index Thread");
394 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
397 synchronizeAnimationTimer = new QTimer();
398 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
400 indexTimer = new QTimer();
401 indexTime = 1000*Global.getIndexThreadSleepInterval();
402 indexTimer.start(indexTime); // Start indexing timer
403 indexTimer.timeout.connect(this, "indexTimer()");
404 indexDisabled = false;
405 indexRunning = false;
407 logger.log(logger.EXTREME, "Setting sync thread & timers");
409 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
410 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
411 syncTimer = new QTimer();
412 syncTimer.timeout.connect(this, "syncTimer()");
413 syncRunner.status.message.connect(this, "setMessage(String)");
414 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
415 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
418 automaticSync = true;
419 syncTimer.start(syncTime*60*1000);
421 automaticSync = false;
424 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
425 syncThread = new QThread(syncRunner, "Synchronization Thread");
429 logger.log(logger.EXTREME, "Starting thumnail thread");
430 pdfReadyQueue = new ArrayList<String>();
431 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
432 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
433 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
434 thumbnailThread.start();
435 thumbGenerators = new ArrayList<Thumbnailer>();
436 thumbnailTimer = new QTimer();
437 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
439 thumbnailTimer.setInterval(60*1000); // Thumbnail every minute
440 thumbnailTimer.start();
442 logger.log(logger.EXTREME, "Starting authentication timer");
443 authTimer = new QTimer();
444 authTimer.timeout.connect(this, "authTimer()");
445 authTimer.start(1000*60*15);
446 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
448 logger.log(logger.EXTREME, "Setting save note timer");
449 saveTimer = new QTimer();
450 saveTimer.timeout.connect(this, "saveNote()");
451 if (Global.getAutoSaveInterval() > 0) {
452 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
455 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
457 logger.log(logger.EXTREME, "Starting external file monitor timer");
458 externalFileSaveTimer = new QTimer();
459 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
460 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
461 externalFiles = new ArrayList<String>();
462 importFilesDelete = new ArrayList<String>();
463 importFilesKeep = new ArrayList<String>();
464 externalFileSaveTimer.start();
466 notebookTree = new NotebookTreeWidget(conn);
467 attributeTree = new AttributeTreeWidget();
468 tagTree = new TagTreeWidget(conn);
469 savedSearchTree = new SavedSearchTreeWidget();
470 trashTree = new TrashTreeWidget();
471 noteTableView = new TableView(logger, listManager);
473 QGridLayout leftGrid = new QGridLayout();
474 leftSplitter1.setLayout(leftGrid);
475 leftGrid.addWidget(notebookTree, 1, 1);
476 leftGrid.addWidget(tagTree,2,1);
477 leftGrid.addWidget(attributeTree,3,1);
478 leftGrid.addWidget(savedSearchTree,4,1);
479 leftGrid.addWidget(trashTree, 5, 1);
481 // Setup the browser window
482 noteCache = new HashMap<String,String>();
483 readOnlyCache = new HashMap<String, Boolean>();
484 inkNoteCache = new HashMap<String, Boolean>();
485 browserWindow = new BrowserWindow(conn);
487 mainLeftRightSplitter.addWidget(leftSplitter1);
488 mainLeftRightSplitter.addWidget(browserIndexSplitter);
490 if (Global.getListView() == Global.View_List_Wide) {
491 browserIndexSplitter.addWidget(noteTableView);
492 browserIndexSplitter.addWidget(browserWindow);
494 mainLeftRightSplitter.addWidget(noteTableView);
495 mainLeftRightSplitter.addWidget(browserWindow);
498 searchField = new QComboBox();
499 searchField.setEditable(true);
500 searchField.activatedIndex.connect(this, "searchFieldChanged()");
501 searchField.setDuplicatesEnabled(false);
502 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
504 quotaBar = new QuotaProgressBar();
506 // Setup the thumbnail viewer
507 thumbnailViewer = new ThumbnailViewer();
508 thumbnailViewer.upArrow.connect(this, "upAction()");
509 thumbnailViewer.downArrow.connect(this, "downAction()");
510 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
511 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
513 //Setup external browser manager
514 externalWindows = new HashMap<String, ExternalBrowse>();
516 listManager.loadNotesIndex();
517 initializeNotebookTree();
519 initializeSavedSearchTree();
520 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
521 attributeTreeSelected = null;
522 initializeNoteTable();
524 selectedNoteGUIDs = new ArrayList<String>();
525 statusBar = new QStatusBar();
526 setStatusBar(statusBar);
527 menuBar = new MainMenuBar(this);
528 emitLog = new ArrayList<String>();
530 tagTree.setDeleteAction(menuBar.tagDeleteAction);
531 tagTree.setEditAction(menuBar.tagEditAction);
532 tagTree.setAddAction(menuBar.tagAddAction);
533 tagTree.setIconAction(menuBar.tagIconAction);
534 tagTree.setVisible(Global.isWindowVisible("tagTree"));
535 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
536 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
537 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
539 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
540 notebookTree.setEditAction(menuBar.notebookEditAction);
541 notebookTree.setAddAction(menuBar.notebookAddAction);
542 notebookTree.setIconAction(menuBar.notebookIconAction);
543 notebookTree.setStackAction(menuBar.notebookStackAction);
544 notebookTree.setPublishAction(menuBar.notebookPublishAction);
545 notebookTree.setShareAction(menuBar.notebookShareAction);
546 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
547 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
548 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
549 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
550 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
552 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
553 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
554 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
555 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
556 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
557 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
558 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
560 noteTableView.setAddAction(menuBar.noteAdd);
561 noteTableView.setDeleteAction(menuBar.noteDelete);
562 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
563 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
564 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
565 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
566 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
567 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
568 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
569 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
570 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
572 quotaBar.setMouseClickAction(menuBar.accountAction);
575 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
576 trashTree.setEmptyAction(menuBar.emptyTrashAction);
577 trashTree.setVisible(Global.isWindowVisible("trashTree"));
578 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
579 trashTree.updateCounts(listManager.getTrashCount());
580 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
581 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
583 noteTableView.setVisible(Global.isWindowVisible("noteList"));
584 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
586 if (!Global.isWindowVisible("editorButtonBar"))
587 toggleEditorButtonBar();
588 if (!Global.isWindowVisible("leftPanel"))
589 menuBar.hideLeftSide.setChecked(true);
590 if (Global.isWindowVisible("noteInformation"))
591 toggleNoteInformation();
595 find = new FindDialog();
596 find.getOkButton().clicked.connect(this, "doFindText()");
598 // Setup the tray icon menu bar
599 trayShowAction = new QAction("Show/Hide", this);
600 trayExitAction = new QAction("Exit", this);
601 trayAddNoteAction = new QAction("Add Note", this);
603 trayExitAction.triggered.connect(this, "closeNeverNote()");
604 trayAddNoteAction.triggered.connect(this, "addNote()");
605 trayShowAction.triggered.connect(this, "trayToggleVisible()");
607 trayMenu = new QMenu(this);
608 trayMenu.addAction(trayAddNoteAction);
609 trayMenu.addAction(trayShowAction);
610 trayMenu.addAction(trayExitAction);
613 trayIcon = new QSystemTrayIcon(this);
614 trayIcon.setToolTip("NeverNote");
615 trayIcon.setContextMenu(trayMenu);
616 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
619 currentNoteGuid = Global.getLastViewedNoteGuid();
620 historyGuids = new ArrayList<String>();
624 if (!currentNoteGuid.trim().equals("")) {
625 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
628 noteIndexUpdated(true);
630 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
631 if (menuBar.showEditorBar.isChecked())
632 showEditorButtons(browserWindow);
633 tagIndexUpdated(true);
634 savedSearchIndexUpdated();
635 notebookIndexUpdated();
637 setupSyncSignalListeners();
638 setupBrowserSignalListeners();
639 setupIndexListeners();
642 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
643 tagTree.showAllTags(true);
645 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
646 setWindowIcon(appIcon);
647 trayIcon.setIcon(appIcon);
648 if (Global.showTrayIcon())
653 scrollToGuid(currentNoteGuid);
654 if (Global.automaticLogin()) {
656 if (Global.isConnected)
659 setupFolderImports();
662 restoreWindowState(true);
664 if (Global.mimicEvernoteInterface) {
665 notebookTree.selectGuid("");
668 threadMonitorTimer = new QTimer();
669 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
670 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
672 historyGuids.add(currentNoteGuid);
675 menuBar.blockSignals(true);
676 menuBar.narrowListView.blockSignals(true);
677 menuBar.wideListView.blockSignals(true);
678 if (Global.getListView() == Global.View_List_Narrow) {
679 menuBar.narrowListView.setChecked(true);
682 menuBar.wideListView.setChecked(true);
684 menuBar.blockSignals(false);
685 menuBar.narrowListView.blockSignals(false);
686 menuBar.wideListView.blockSignals(false);
688 if (Global.getListView() == Global.View_List_Wide) {
689 browserIndexSplitter.addWidget(noteTableView);
690 browserIndexSplitter.addWidget(browserWindow);
692 mainLeftRightSplitter.addWidget(noteTableView);
693 mainLeftRightSplitter.addWidget(browserWindow);
696 int sortCol = Global.getSortColumn();
697 int sortOrder = Global.getSortOrder();
698 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
699 if (Global.checkVersionUpgrade())
704 public static void main(String[] args) {
705 log.setLevel(Level.FATAL);
706 QApplication.initialize(args);
707 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
708 QSplashScreen splash = new QSplashScreen(pixmap);
711 DatabaseConnection dbConn;
714 initializeGlobalSettings(args);
716 showSplash = Global.isWindowVisible("SplashScreen");
720 dbConn = setupDatabaseConnection();
722 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
723 Global.getFileManager().purgeResDirectory(true);
725 } catch (InitializationException e) {
728 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
732 NeverNote application = new NeverNote(dbConn);
734 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
735 if (Global.startMinimized())
736 application.showMinimized();
738 if (Global.wasWindowMaximized())
739 application.showMaximized();
745 splash.finish(application);
747 System.out.println("Goodbye.");
752 * Open the internal database, or create if not present
754 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
756 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
757 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
759 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
760 boolean dbExists = f.exists();
762 Global.setDatabaseUrl("");
764 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
765 boolean goodCheck = false;
767 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
769 if (!dialog.okPressed())
771 Global.cipherPassword = dialog.getPassword();
772 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
773 Global.getDatabaseUserPassword(), Global.cipherPassword);
776 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
780 // Encrypt the database upon shutdown
781 private void encryptOnShutdown() {
782 String dbPath= Global.getFileManager().getDbDirPath("");
783 String dbName = "NeverNote";
785 Statement st = conn.getConnection().createStatement();
786 st.execute("shutdown");
787 if (QMessageBox.question(this, "Are you sure",
788 "Are you sure you wish to encrypt the database?",
789 QMessageBox.StandardButton.Yes,
790 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
791 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
792 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
793 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
795 } catch (SQLException e) {
800 // Decrypt the database upon shutdown
801 private void decryptOnShutdown() {
802 String dbPath= Global.getFileManager().getDbDirPath("");
803 String dbName = "NeverNote";
805 Statement st = conn.getConnection().createStatement();
806 st.execute("shutdown");
807 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
808 encryptCipher = "AES";
810 encryptCipher = "XTEA";
811 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
812 "Are you sure you wish to decrypt the database?"),
813 QMessageBox.StandardButton.Yes,
814 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
816 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
817 Global.setDatabaseUrl("");
818 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
820 } catch (SQLException e) {
825 * Encrypt/Decrypt the local database
827 public void doDatabaseEncrypt() {
828 // The database is not currently encrypted
829 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
830 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
831 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
832 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
833 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
834 "Do you wish to proceed?"),
835 QMessageBox.StandardButton.Yes,
836 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
839 DBEncryptDialog dialog = new DBEncryptDialog();
841 if (dialog.okPressed()) {
842 Global.cipherPassword = dialog.getPassword();
843 encryptOnShutdown = true;
844 encryptCipher = dialog.getEncryptionMethod();
847 DBEncryptDialog dialog = new DBEncryptDialog();
848 dialog.setWindowTitle("Database Decryption");
849 dialog.hideEncryption();
851 if (dialog.okPressed()) {
852 if (!dialog.getPassword().equals(Global.cipherPassword)) {
853 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
856 decryptOnShutdown = true;
863 private static void initializeGlobalSettings(String[] args) throws InitializationException {
864 StartupConfig startupConfig = new StartupConfig();
866 for (String arg : args) {
867 String lower = arg.toLowerCase();
868 if (lower.startsWith("--name="))
869 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
870 if (lower.startsWith("--home="))
871 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
872 if (lower.startsWith("--disable-viewing"))
873 startupConfig.setDisableViewing(true);
875 Global.setup(startupConfig);
880 public void closeEvent(QCloseEvent event) {
881 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
886 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
889 if (currentNote!= null & browserWindow!=null) {
890 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
891 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
894 setMessage(tr("Beginning shutdown."));
896 // Close down external windows
897 Collection<ExternalBrowse> windows = externalWindows.values();
898 Iterator<ExternalBrowse> iterator = windows.iterator();
899 while (iterator.hasNext()) {
900 ExternalBrowse browser = iterator.next();
901 browser.windowClosing.disconnect();
906 externalFileEditedSaver();
907 if (Global.isConnected && Global.synchronizeOnClose()) {
908 setMessage(tr("Performing synchronization before closing."));
909 syncRunner.addWork("SYNC");
911 setMessage("Closing Program.");
912 threadMonitorTimer.stop();
914 syncRunner.addWork("STOP");
915 syncRunner.keepRunning = false;
916 thumbnailRunner.addWork("STOP");
917 syncRunner.keepRunning = false;
918 indexRunner.addWork("STOP");
919 syncRunner.keepRunning = false;
924 if (tempFiles != null)
927 browserWindow.noteSignal.tagsChanged.disconnect();
928 browserWindow.noteSignal.titleChanged.disconnect();
929 browserWindow.noteSignal.noteChanged.disconnect();
930 browserWindow.noteSignal.notebookChanged.disconnect();
931 browserWindow.noteSignal.createdDateChanged.disconnect();
932 browserWindow.noteSignal.alteredDateChanged.disconnect();
933 syncRunner.searchSignal.listChanged.disconnect();
934 syncRunner.tagSignal.listChanged.disconnect();
935 syncRunner.notebookSignal.listChanged.disconnect();
936 syncRunner.noteIndexSignal.listChanged.disconnect();
939 Global.saveWindowVisible("toolBar", toolBar.isVisible());
940 saveNoteColumnPositions();
941 saveNoteIndexWidth();
943 int width = notebookTree.columnWidth(0);
944 Global.setColumnWidth("notebookTreeName", width);
945 width = tagTree.columnWidth(0);
946 Global.setColumnWidth("tagTreeName", width);
948 Global.saveWindowMaximized(isMaximized());
949 Global.saveCurrentNoteGuid(currentNoteGuid);
951 int sortCol = noteTableView.proxyModel.sortColumn();
952 int sortOrder = noteTableView.proxyModel.sortOrder().value();
953 Global.setSortColumn(sortCol);
954 Global.setSortOrder(sortOrder);
958 Global.keepRunning = false;
960 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
961 if (indexRunner.thread().isAlive())
962 indexRunner.thread().join(50);
963 if (!indexRunner.thread().isAlive())
964 logger.log(logger.MEDIUM, "Index thread has stopped");
966 logger.log(logger.MEDIUM, "Index thread still running - bypassing");
967 } catch (InterruptedException e1) {
968 e1.printStackTrace();
970 if (!syncRunner.isIdle()) {
972 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
974 logger.log(logger.MEDIUM, "Sync thread has stopped");
975 } catch (InterruptedException e1) {
976 e1.printStackTrace();
980 if (encryptOnShutdown) {
983 if (decryptOnShutdown) {
986 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
989 @SuppressWarnings("unused")
990 private void closeNeverNote() {
994 public void setMessage(String s) {
995 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
996 logger.log(logger.HIGH, "Message: " +s);
997 statusBar.showMessage(s);
999 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1002 private void waitCursor(boolean wait) {
1004 if (QApplication.overrideCursor() == null)
1005 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1008 while (QApplication.overrideCursor() != null)
1009 QApplication.restoreOverrideCursor();
1013 private void setupIndexListeners() {
1014 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1015 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1016 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1017 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1019 private void setupSyncSignalListeners() {
1020 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1021 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1022 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1023 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1024 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1026 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1027 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1028 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1030 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1031 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1032 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1033 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1035 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1038 private void setupBrowserSignalListeners() {
1039 setupBrowserWindowListeners(browserWindow, true);
1042 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1043 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1044 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1045 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1046 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1047 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1048 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1049 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1050 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1051 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1052 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1053 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1054 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1055 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1056 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1057 if (master) browser.focusLost.connect(this, "saveNote()");
1058 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1061 //***************************************************************
1062 //***************************************************************
1063 //* Settings and look & feel
1064 //***************************************************************
1065 //***************************************************************
1066 @SuppressWarnings("unused")
1067 private void settings() {
1068 logger.log(logger.HIGH, "Entering NeverNote.settings");
1069 saveNoteColumnPositions();
1070 saveNoteIndexWidth();
1072 ConfigDialog settings = new ConfigDialog(this);
1073 String dateFormat = Global.getDateFormat();
1074 String timeFormat = Global.getTimeFormat();
1076 indexTime = 1000*Global.getIndexThreadSleepInterval();
1077 indexTimer.start(indexTime); // reset indexing timer
1080 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1081 if (Global.showTrayIcon())
1086 if (menuBar.showEditorBar.isChecked())
1087 showEditorButtons(browserWindow);
1089 // Reset the save timer
1090 if (Global.getAutoSaveInterval() > 0)
1091 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1095 // This is a hack to force a reload of the index in case the date or time changed.
1096 // if (!dateFormat.equals(Global.getDateFormat()) ||
1097 // !timeFormat.equals(Global.getTimeFormat())) {
1099 readOnlyCache.clear();
1100 inkNoteCache.clear();
1101 noteIndexUpdated(true);
1104 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1106 // Restore things to the way they were
1107 private void restoreWindowState(boolean mainWindow) {
1108 // We need to name things or this doesn't work.
1109 setObjectName("NeverNote");
1110 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1111 browserIndexSplitter.setObjectName("browserIndexSplitter");
1112 leftSplitter1.setObjectName("leftSplitter1");
1114 // Restore the actual positions.
1116 restoreGeometry(Global.restoreGeometry(objectName()));
1117 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1118 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1119 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1122 // Save window positions for the next start
1123 private void saveWindowState() {
1124 Global.saveGeometry(objectName(), saveGeometry());
1125 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1126 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1127 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1129 // Load the style sheet
1130 private void loadStyleSheet() {
1131 String fileName = Global.getFileManager().getQssDirPath("default.qss");
1132 QFile file = new QFile(fileName);
1133 file.open(OpenModeFlag.ReadOnly);
1134 String styleSheet = file.readAll().toString();
1136 setStyleSheet(styleSheet);
1138 // Save column positions for the next time
1139 private void saveNoteColumnPositions() {
1140 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1141 Global.setColumnPosition("noteTableCreationPosition", position);
1142 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1143 Global.setColumnPosition("noteTableTagPosition", position);
1144 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1145 Global.setColumnPosition("noteTableNotebookPosition", position);
1146 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1147 Global.setColumnPosition("noteTableChangedPosition", position);
1148 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1149 Global.setColumnPosition("noteTableAuthorPosition", position);
1150 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1151 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1152 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1153 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1154 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1155 Global.setColumnPosition("noteTableTitlePosition", position);
1156 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1157 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1158 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1159 Global.setColumnPosition("noteTableGuidPosition", position);
1160 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1161 Global.setColumnPosition("noteTableThumbnailPosition", position);
1164 // Save column widths for the next time
1165 private void saveNoteIndexWidth() {
1167 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1168 Global.setColumnWidth("noteTableCreationPosition", width);
1169 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1170 Global.setColumnWidth("noteTableChangedPosition", width);
1171 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1172 Global.setColumnWidth("noteTableGuidPosition", width);
1173 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1174 Global.setColumnWidth("noteTableNotebookPosition", width);
1175 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1176 Global.setColumnWidth("noteTableTagPosition", width);
1177 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1178 Global.setColumnWidth("noteTableTitlePosition", width);
1179 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1180 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1181 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1182 Global.setColumnWidth("noteTableAuthorPosition", width);
1183 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1184 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1185 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1186 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1187 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1188 Global.setColumnWidth("noteTableThumbnailPosition", width);
1189 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1190 Global.setColumnWidth("noteTableGuidPosition", width);
1194 //***************************************************************
1195 //***************************************************************
1196 //** These functions deal with Notebook menu items
1197 //***************************************************************
1198 //***************************************************************
1199 // Setup the tree containing the user's notebooks.
1200 private void initializeNotebookTree() {
1201 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1202 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1203 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1204 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1205 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1207 // Listener when a notebook is selected
1208 private void notebookTreeSelection() {
1209 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1212 clearAttributeFilter();
1213 clearSavedSearchFilter();
1214 if (Global.mimicEvernoteInterface) {
1216 searchField.clear();
1218 menuBar.noteRestoreAction.setVisible(false);
1219 menuBar.notebookEditAction.setEnabled(true);
1220 menuBar.notebookDeleteAction.setEnabled(true);
1221 menuBar.notebookPublishAction.setEnabled(true);
1222 menuBar.notebookShareAction.setEnabled(true);
1223 menuBar.notebookIconAction.setEnabled(true);
1224 menuBar.notebookStackAction.setEnabled(true);
1225 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1226 selectedNotebookGUIDs.clear();
1228 String stackName = "";
1229 if (selections.size() > 0) {
1230 guid = (selections.get(0).text(2));
1231 stackName = selections.get(0).text(0);
1233 if (!Global.mimicEvernoteInterface) {
1234 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1235 if (selections.size()==0) {
1236 selectedNotebookGUIDs.clear();
1237 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1238 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1240 menuBar.notebookEditAction.setEnabled(false);
1241 menuBar.notebookDeleteAction.setEnabled(false);
1242 menuBar.notebookStackAction.setEnabled(false);
1243 menuBar.notebookIconAction.setEnabled(false);
1246 if (!guid.equals("") && !guid.equals("STACK")) {
1247 selectedNotebookGUIDs.add(guid);
1248 menuBar.notebookIconAction.setEnabled(true);
1250 menuBar.notebookIconAction.setEnabled(true);
1251 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1252 Notebook book = listManager.getNotebookIndex().get(j);
1253 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1254 selectedNotebookGUIDs.add(book.getGuid());
1257 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1258 listManager.loadNotesIndex();
1259 noteIndexUpdated(false);
1260 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1263 private void clearNotebookFilter() {
1264 notebookTree.blockSignals(true);
1265 notebookTree.clearSelection();
1266 menuBar.noteRestoreAction.setVisible(false);
1267 menuBar.notebookEditAction.setEnabled(false);
1268 menuBar.notebookDeleteAction.setEnabled(false);
1269 selectedNotebookGUIDs.clear();
1270 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1271 notebookTree.blockSignals(false);
1273 // Triggered when the notebook DB has been updated
1274 private void notebookIndexUpdated() {
1275 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1277 // Get the possible icons
1278 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1279 notebookTree.setIcons(icons);
1281 if (selectedNotebookGUIDs == null)
1282 selectedNotebookGUIDs = new ArrayList<String>();
1283 List<Notebook> books = conn.getNotebookTable().getAll();
1284 for (int i=books.size()-1; i>=0; i--) {
1285 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1286 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1288 j=listManager.getArchiveNotebookIndex().size();
1294 listManager.countNotebookResults(listManager.getNoteIndex());
1295 notebookTree.blockSignals(true);
1296 notebookTree.load(books, listManager.getLocalNotebooks());
1297 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1298 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1300 selectedNotebookGUIDs.remove(i);
1302 notebookTree.blockSignals(false);
1304 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1306 // Show/Hide note information
1307 private void toggleNotebookWindow() {
1308 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1309 if (notebookTree.isVisible())
1310 notebookTree.hide();
1312 notebookTree.show();
1313 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1314 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1315 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1317 // Add a new notebook
1318 @SuppressWarnings("unused")
1319 private void addNotebook() {
1320 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1321 NotebookEdit edit = new NotebookEdit();
1322 edit.setNotebooks(listManager.getNotebookIndex());
1325 if (!edit.okPressed())
1328 Calendar currentTime = new GregorianCalendar();
1329 Long l = new Long(currentTime.getTimeInMillis());
1330 String randint = new String(Long.toString(l));
1332 Notebook newBook = new Notebook();
1333 newBook.setUpdateSequenceNum(0);
1334 newBook.setGuid(randint);
1335 newBook.setName(edit.getNotebook());
1336 newBook.setServiceCreated(new Date().getTime());
1337 newBook.setServiceUpdated(new Date().getTime());
1338 newBook.setDefaultNotebook(false);
1339 newBook.setPublished(false);
1341 listManager.getNotebookIndex().add(newBook);
1343 listManager.getLocalNotebooks().add(newBook.getGuid());
1344 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1345 notebookIndexUpdated();
1346 listManager.countNotebookResults(listManager.getNoteIndex());
1347 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1348 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1350 // Edit an existing notebook
1351 @SuppressWarnings("unused")
1352 private void stackNotebook() {
1353 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1354 StackNotebook edit = new StackNotebook();
1356 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1357 QTreeWidgetItem currentSelection;
1358 for (int i=0; i<selections.size(); i++) {
1359 currentSelection = selections.get(0);
1360 String guid = currentSelection.text(2);
1361 if (guid.equalsIgnoreCase("")) {
1362 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1365 if (guid.equalsIgnoreCase("STACK")) {
1366 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1371 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1376 if (!edit.okPressed())
1379 String stack = edit.getStackName();
1381 for (int i=0; i<selections.size(); i++) {
1382 currentSelection = selections.get(i);
1383 String guid = currentSelection.text(2);
1384 listManager.updateNotebookStack(guid, stack);
1386 notebookIndexUpdated();
1387 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1389 // Edit an existing notebook
1390 @SuppressWarnings("unused")
1391 private void editNotebook() {
1392 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1393 NotebookEdit edit = new NotebookEdit();
1395 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1396 QTreeWidgetItem currentSelection;
1397 currentSelection = selections.get(0);
1398 edit.setNotebook(currentSelection.text(0));
1400 String guid = currentSelection.text(2);
1401 if (!guid.equalsIgnoreCase("STACK")) {
1402 edit.setTitle(tr("Edit Notebook"));
1403 edit.setNotebooks(listManager.getNotebookIndex());
1404 edit.setLocalCheckboxEnabled(false);
1405 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1406 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1407 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1408 i=listManager.getNotebookIndex().size();
1412 edit.setTitle(tr("Edit Stack"));
1413 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1414 edit.hideLocalCheckbox();
1415 edit.hideDefaultCheckbox();
1420 if (!edit.okPressed())
1424 if (guid.equalsIgnoreCase("STACK")) {
1425 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1426 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1427 if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1428 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1430 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1431 currentSelection.setText(0, edit.getNotebook());
1435 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1436 currentSelection.setText(0, edit.getNotebook());
1438 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1439 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1440 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1441 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1442 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1443 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1444 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1445 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1447 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1448 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1449 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1450 linkedNotebook.setShareName(edit.getNotebook());
1451 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1453 i=listManager.getNotebookIndex().size();
1457 // Build a list of non-closed notebooks
1458 List<Notebook> nbooks = new ArrayList<Notebook>();
1459 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1460 boolean found=false;
1461 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1462 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1466 nbooks.add(listManager.getNotebookIndex().get(i));
1470 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1471 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1472 browserWindow.setNotebookList(filteredBooks);
1473 Iterator<String> set = externalWindows.keySet().iterator();
1474 while(set.hasNext())
1475 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1476 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1478 // Publish a notebook
1479 @SuppressWarnings("unused")
1480 private void publishNotebook() {
1481 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1482 QTreeWidgetItem currentSelection;
1483 currentSelection = selections.get(0);
1484 String guid = currentSelection.text(2);
1486 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1491 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1492 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1493 n = listManager.getNotebookIndex().get(i);
1495 i = listManager.getNotebookIndex().size();
1501 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1504 if (!publish.okClicked())
1507 Publishing p = publish.getPublishing();
1508 boolean isPublished = !publish.isStopPressed();
1509 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1510 n.setPublished(isPublished);
1512 listManager.getNotebookIndex().set(position, n);
1513 notebookIndexUpdated();
1515 // Publish a notebook
1516 @SuppressWarnings("unused")
1517 private void shareNotebook() {
1518 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1519 QTreeWidgetItem currentSelection;
1520 currentSelection = selections.get(0);
1521 String guid = currentSelection.text(2);
1523 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1527 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1528 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1529 n = listManager.getNotebookIndex().get(i);
1530 i = listManager.getNotebookIndex().size();
1534 String authToken = null;
1535 if (syncRunner.isConnected)
1536 authToken = syncRunner.authToken;
1537 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1542 // Delete an existing notebook
1543 @SuppressWarnings("unused")
1544 private void deleteNotebook() {
1545 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1546 boolean stacksFound = false;
1547 boolean notebooksFound = false;
1548 boolean assigned = false;
1549 // Check if any notes have this notebook
1550 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1551 for (int i=0; i<selections.size(); i++) {
1552 QTreeWidgetItem currentSelection;
1553 currentSelection = selections.get(i);
1554 String guid = currentSelection.text(2);
1555 if (!guid.equalsIgnoreCase("STACK")) {
1556 notebooksFound = true;
1557 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1558 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1559 if (noteGuid.equals(guid)) {
1561 j=listManager.getNoteIndex().size();
1562 i=selections.size();
1570 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1571 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1575 if (conn.getNotebookTable().getAll().size() == 1) {
1576 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1580 // If all notebooks are clear, verify the delete
1581 String msg1 = new String(tr("Delete selected notebooks?"));
1582 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1583 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1584 " not deleted unless selected?"));
1586 if (stacksFound && notebooksFound)
1588 if (!stacksFound && notebooksFound)
1590 if (stacksFound && !notebooksFound)
1592 if (QMessageBox.question(this, tr("Confirmation"), msg,
1593 QMessageBox.StandardButton.Yes,
1594 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1598 // If confirmed, delete the notebook
1599 for (int i=selections.size()-1; i>=0; i--) {
1600 QTreeWidgetItem currentSelection;
1601 currentSelection = selections.get(i);
1602 String guid = currentSelection.text(2);
1603 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1604 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1605 listManager.renameStack(currentSelection.text(0), "");
1607 conn.getNotebookTable().expungeNotebook(guid, true);
1608 listManager.deleteNotebook(guid);
1612 notebookIndexUpdated();
1613 // notebookTreeSelection();
1614 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1615 // listManager.countNotebookResults(listManager.getNoteIndex());
1616 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1618 // A note's notebook has been updated
1619 @SuppressWarnings("unused")
1620 private void updateNoteNotebook(String guid, String notebookGuid) {
1622 // Update the list manager
1623 listManager.updateNoteNotebook(guid, notebookGuid);
1624 listManager.countNotebookResults(listManager.getNoteIndex());
1625 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1627 // Find the name of the notebook
1628 String notebookName = null;
1629 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1630 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1631 notebookName = listManager.getNotebookIndex().get(i).getName();
1636 // If we found the name, update the browser window
1637 if (notebookName != null) {
1638 updateListNoteNotebook(guid, notebookName);
1639 if (guid.equals(currentNoteGuid)) {
1640 int pos = browserWindow.notebookBox.findText(notebookName);
1642 browserWindow.notebookBox.setCurrentIndex(pos);
1646 // If we're dealing with the current note, then we need to be sure and update the notebook there
1647 if (guid.equals(currentNoteGuid)) {
1648 if (currentNote != null) {
1649 currentNote.setNotebookGuid(notebookGuid);
1653 // Open/close notebooks
1654 @SuppressWarnings("unused")
1655 private void closeNotebooks() {
1656 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1658 if (!na.okClicked())
1662 listManager.getArchiveNotebookIndex().clear();
1664 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1665 String text = na.getClosedBookList().takeItem(i).text();
1666 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1667 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1668 Notebook n = listManager.getNotebookIndex().get(j);
1669 conn.getNotebookTable().setArchived(n.getGuid(),true);
1670 listManager.getArchiveNotebookIndex().add(n);
1671 j=listManager.getNotebookIndex().size();
1676 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1677 String text = na.getOpenBookList().takeItem(i).text();
1678 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1679 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1680 Notebook n = listManager.getNotebookIndex().get(j);
1681 conn.getNotebookTable().setArchived(n.getGuid(),false);
1682 j=listManager.getNotebookIndex().size();
1686 notebookTreeSelection();
1687 listManager.loadNotesIndex();
1688 notebookIndexUpdated();
1689 noteIndexUpdated(false);
1690 reloadTagTree(true);
1691 // noteIndexUpdated(false);
1693 // Build a list of non-closed notebooks
1694 List<Notebook> nbooks = new ArrayList<Notebook>();
1695 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1696 boolean found=false;
1697 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1698 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1702 nbooks.add(listManager.getNotebookIndex().get(i));
1705 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1706 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1707 browserWindow.setNotebookList(filteredBooks);
1709 // Update any external windows
1710 Iterator<String> set = externalWindows.keySet().iterator();
1711 while(set.hasNext())
1712 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1716 // Change the notebook's icon
1717 @SuppressWarnings("unused")
1718 private void setNotebookIcon() {
1719 boolean stackSelected = false;
1720 boolean allNotebookSelected = false;
1722 QTreeWidgetItem currentSelection;
1723 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1724 if (selections.size() == 0)
1727 currentSelection = selections.get(0);
1728 String guid = currentSelection.text(2);
1729 if (guid.equalsIgnoreCase(""))
1730 allNotebookSelected = true;
1731 if (guid.equalsIgnoreCase("STACK"))
1732 stackSelected = true;
1734 QIcon currentIcon = currentSelection.icon(0);
1738 if (!stackSelected && !allNotebookSelected) {
1739 icon = conn.getNotebookTable().getIcon(guid);
1741 dialog = new SetIcon(currentIcon);
1742 dialog.setUseDefaultIcon(true);
1744 dialog = new SetIcon(icon);
1745 dialog.setUseDefaultIcon(false);
1748 if (stackSelected) {
1749 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1751 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1754 dialog = new SetIcon(currentIcon);
1755 dialog.setUseDefaultIcon(true);
1757 dialog = new SetIcon(icon);
1758 dialog.setUseDefaultIcon(false);
1762 if (dialog.okPressed()) {
1763 QIcon newIcon = dialog.getIcon();
1764 if (stackSelected) {
1765 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1766 if (newIcon == null) {
1767 newIcon = new QIcon(iconPath+"books2.png");
1769 currentSelection.setIcon(0,newIcon);
1772 if (allNotebookSelected) {
1773 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1774 if (newIcon == null) {
1775 newIcon = new QIcon(iconPath+"notebook-green.png");
1777 currentSelection.setIcon(0,newIcon);
1780 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1781 if (newIcon == null) {
1782 boolean isPublished = false;;
1783 boolean found = false;
1784 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1785 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1786 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1790 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1792 currentSelection.setIcon(0, newIcon);
1798 //***************************************************************
1799 //***************************************************************
1800 //** These functions deal with Tag menu items
1801 //***************************************************************
1802 //***************************************************************
1803 // Add a new notebook
1804 @SuppressWarnings("unused")
1805 private void addTag() {
1806 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1807 TagEdit edit = new TagEdit();
1808 edit.setTagList(listManager.getTagIndex());
1811 if (!edit.okPressed())
1814 Calendar currentTime = new GregorianCalendar();
1815 Long l = new Long(currentTime.getTimeInMillis());
1816 String randint = new String(Long.toString(l));
1818 Tag newTag = new Tag();
1819 newTag.setUpdateSequenceNum(0);
1820 newTag.setGuid(randint);
1821 newTag.setName(edit.getTag());
1822 conn.getTagTable().addTag(newTag, true);
1823 listManager.getTagIndex().add(newTag);
1824 reloadTagTree(true);
1826 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1828 @SuppressWarnings("unused")
1829 private void reloadTagTree() {
1830 reloadTagTree(false);
1832 private void reloadTagTree(boolean reload) {
1833 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1834 tagIndexUpdated(reload);
1835 boolean filter = false;
1836 listManager.countTagResults(listManager.getNoteIndex());
1837 if (notebookTree.selectedItems().size() > 0
1838 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1840 if (tagTree.selectedItems().size() > 0)
1842 tagTree.showAllTags(!filter);
1843 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1845 // Edit an existing tag
1846 @SuppressWarnings("unused")
1847 private void editTag() {
1848 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1849 TagEdit edit = new TagEdit();
1850 edit.setTitle("Edit Tag");
1851 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1852 QTreeWidgetItem currentSelection;
1853 currentSelection = selections.get(0);
1854 edit.setTag(currentSelection.text(0));
1855 edit.setTagList(listManager.getTagIndex());
1858 if (!edit.okPressed())
1861 String guid = currentSelection.text(2);
1862 currentSelection.setText(0,edit.getTag());
1864 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1865 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1866 listManager.getTagIndex().get(i).setName(edit.getTag());
1867 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1868 updateListTagName(guid);
1869 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1870 browserWindow.setTag(getTagNamesForNote(currentNote));
1871 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1875 browserWindow.setTag(getTagNamesForNote(currentNote));
1876 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1878 // Delete an existing tag
1879 @SuppressWarnings("unused")
1880 private void deleteTag() {
1881 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1883 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1884 QMessageBox.StandardButton.Yes,
1885 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1889 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1890 for (int i=selections.size()-1; i>=0; i--) {
1891 QTreeWidgetItem currentSelection;
1892 currentSelection = selections.get(i);
1893 removeTagItem(currentSelection.text(2));
1895 tagIndexUpdated(true);
1897 listManager.countTagResults(listManager.getNoteIndex());
1898 // tagTree.updateCounts(listManager.getTagCounter());
1899 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1901 // Remove a tag tree item. Go recursively down & remove the children too
1902 private void removeTagItem(String guid) {
1903 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1904 String parent = listManager.getTagIndex().get(j).getParentGuid();
1905 if (parent != null && parent.equals(guid)) {
1906 //Remove this tag's children
1907 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1910 //Now, remove this tag
1911 removeListTagName(guid);
1912 conn.getTagTable().expungeTag(guid, true);
1913 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1914 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1915 listManager.getTagIndex().remove(a);
1920 // Setup the tree containing the user's tags
1921 private void initializeTagTree() {
1922 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1923 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1924 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
1925 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1926 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1927 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1929 // Listener when a tag is selected
1930 private void tagTreeSelection() {
1931 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1934 clearAttributeFilter();
1935 clearSavedSearchFilter();
1937 menuBar.noteRestoreAction.setVisible(false);
1939 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1940 QTreeWidgetItem currentSelection;
1941 selectedTagGUIDs.clear();
1942 for (int i=0; i<selections.size(); i++) {
1943 currentSelection = selections.get(i);
1944 selectedTagGUIDs.add(currentSelection.text(2));
1946 if (selections.size() > 0) {
1947 menuBar.tagEditAction.setEnabled(true);
1948 menuBar.tagDeleteAction.setEnabled(true);
1949 menuBar.tagIconAction.setEnabled(true);
1952 menuBar.tagEditAction.setEnabled(false);
1953 menuBar.tagDeleteAction.setEnabled(false);
1954 menuBar.tagIconAction.setEnabled(true);
1956 listManager.setSelectedTags(selectedTagGUIDs);
1957 listManager.loadNotesIndex();
1958 noteIndexUpdated(false);
1959 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1961 // trigger the tag index to be refreshed
1962 @SuppressWarnings("unused")
1963 private void tagIndexUpdated() {
1964 tagIndexUpdated(true);
1966 private void tagIndexUpdated(boolean reload) {
1967 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1968 if (selectedTagGUIDs == null)
1969 selectedTagGUIDs = new ArrayList<String>();
1971 listManager.reloadTagIndex();
1973 tagTree.blockSignals(true);
1975 tagTree.setIcons(conn.getTagTable().getAllIcons());
1976 tagTree.load(listManager.getTagIndex());
1978 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1979 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1981 selectedTagGUIDs.remove(i);
1983 tagTree.blockSignals(false);
1985 browserWindow.setTag(getTagNamesForNote(currentNote));
1986 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1988 // Show/Hide note information
1989 private void toggleTagWindow() {
1990 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1991 if (tagTree.isVisible())
1995 menuBar.hideTags.setChecked(tagTree.isVisible());
1996 Global.saveWindowVisible("tagTree", tagTree.isVisible());
1997 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1999 // A note's tags have been updated
2000 @SuppressWarnings("unused")
2001 private void updateNoteTags(String guid, List<String> tags) {
2002 // Save any new tags. We'll need them later.
2003 List<String> newTags = new ArrayList<String>();
2004 for (int i=0; i<tags.size(); i++) {
2005 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2006 newTags.add(tags.get(i));
2009 listManager.saveNoteTags(guid, tags);
2010 listManager.countTagResults(listManager.getNoteIndex());
2011 StringBuffer names = new StringBuffer("");
2012 for (int i=0; i<tags.size(); i++) {
2013 names = names.append(tags.get(i));
2014 if (i<tags.size()-1) {
2015 names.append(Global.tagDelimeter + " ");
2018 browserWindow.setTag(names.toString());
2021 // Now, we need to add any new tags to the tag tree
2022 for (int i=0; i<newTags.size(); i++)
2023 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2025 // Get a string containing all tag names for a note
2026 private String getTagNamesForNote(Note n) {
2027 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2028 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2030 StringBuffer buffer = new StringBuffer(100);
2031 Vector<String> v = new Vector<String>();
2032 List<String> guids = n.getTagGuids();
2037 for (int i=0; i<guids.size(); i++) {
2038 v.add(listManager.getTagNameByGuid(guids.get(i)));
2040 Comparator<String> comparator = Collections.reverseOrder();
2041 Collections.sort(v,comparator);
2042 Collections.reverse(v);
2044 for (int i = 0; i<v.size(); i++) {
2046 buffer.append(", ");
2047 buffer.append(v.get(i));
2050 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2051 return buffer.toString();
2053 // Tags were added via dropping notes from the note list
2054 @SuppressWarnings("unused")
2055 private void tagsAdded(String noteGuid, String tagGuid) {
2056 String tagName = null;
2057 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2058 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2059 tagName = listManager.getTagIndex().get(i).getName();
2060 i=listManager.getTagIndex().size();
2063 if (tagName == null)
2066 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2067 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2068 List<String> tagNames = new ArrayList<String>();
2069 tagNames.add(new String(tagName));
2070 Note n = listManager.getMasterNoteIndex().get(i);
2071 for (int j=0; j<n.getTagNames().size(); j++) {
2072 tagNames.add(new String(n.getTagNames().get(j)));
2074 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2075 if (n.getGuid().equals(currentNoteGuid)) {
2076 Collections.sort(tagNames);
2077 String display = "";
2078 for (int j=0; j<tagNames.size(); j++) {
2079 display = display+tagNames.get(j);
2080 if (j+2<tagNames.size())
2081 display = display+Global.tagDelimeter+" ";
2083 browserWindow.setTag(display);
2085 i=listManager.getMasterNoteIndex().size();
2090 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2092 private void clearTagFilter() {
2093 tagTree.blockSignals(true);
2094 tagTree.clearSelection();
2095 menuBar.noteRestoreAction.setVisible(false);
2096 menuBar.tagEditAction.setEnabled(false);
2097 menuBar.tagDeleteAction.setEnabled(false);
2098 menuBar.tagIconAction.setEnabled(false);
2099 selectedTagGUIDs.clear();
2100 listManager.setSelectedTags(selectedTagGUIDs);
2101 tagTree.blockSignals(false);
2103 // Change the icon for a tag
2104 @SuppressWarnings("unused")
2105 private void setTagIcon() {
2106 QTreeWidgetItem currentSelection;
2107 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2108 if (selections.size() == 0)
2111 currentSelection = selections.get(0);
2112 String guid = currentSelection.text(2);
2114 QIcon currentIcon = currentSelection.icon(0);
2115 QIcon icon = conn.getTagTable().getIcon(guid);
2118 dialog = new SetIcon(currentIcon);
2119 dialog.setUseDefaultIcon(true);
2121 dialog = new SetIcon(icon);
2122 dialog.setUseDefaultIcon(false);
2125 if (dialog.okPressed()) {
2126 QIcon newIcon = dialog.getIcon();
2127 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2128 if (newIcon == null)
2129 newIcon = new QIcon(iconPath+"tag.png");
2130 currentSelection.setIcon(0, newIcon);
2136 //***************************************************************
2137 //***************************************************************
2138 //** These functions deal with Saved Search menu items
2139 //***************************************************************
2140 //***************************************************************
2141 // Add a new notebook
2142 @SuppressWarnings("unused")
2143 private void addSavedSearch() {
2144 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2145 SavedSearchEdit edit = new SavedSearchEdit();
2146 edit.setSearchList(listManager.getSavedSearchIndex());
2149 if (!edit.okPressed())
2152 Calendar currentTime = new GregorianCalendar();
2153 Long l = new Long(currentTime.getTimeInMillis());
2154 String randint = new String(Long.toString(l));
2156 SavedSearch search = new SavedSearch();
2157 search.setUpdateSequenceNum(0);
2158 search.setGuid(randint);
2159 search.setName(edit.getName());
2160 search.setQuery(edit.getQuery());
2161 search.setFormat(QueryFormat.USER);
2162 listManager.getSavedSearchIndex().add(search);
2163 conn.getSavedSearchTable().addSavedSearch(search, true);
2164 savedSearchIndexUpdated();
2165 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2167 // Edit an existing tag
2168 @SuppressWarnings("unused")
2169 private void editSavedSearch() {
2170 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2171 SavedSearchEdit edit = new SavedSearchEdit();
2172 edit.setTitle(tr("Edit Search"));
2173 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2174 QTreeWidgetItem currentSelection;
2175 currentSelection = selections.get(0);
2176 String guid = currentSelection.text(1);
2177 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2178 edit.setName(currentSelection.text(0));
2179 edit.setQuery(s.getQuery());
2180 edit.setSearchList(listManager.getSavedSearchIndex());
2183 if (!edit.okPressed())
2186 List<SavedSearch> list = listManager.getSavedSearchIndex();
2187 SavedSearch search = null;
2188 boolean found = false;
2189 for (int i=0; i<list.size(); i++) {
2190 search = list.get(i);
2191 if (search.getGuid().equals(guid)) {
2198 search.setName(edit.getName());
2199 search.setQuery(edit.getQuery());
2200 conn.getSavedSearchTable().updateSavedSearch(search, true);
2201 savedSearchIndexUpdated();
2202 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2204 // Delete an existing tag
2205 @SuppressWarnings("unused")
2206 private void deleteSavedSearch() {
2207 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2209 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2210 QMessageBox.StandardButton.Yes,
2211 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2215 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2216 for (int i=selections.size()-1; i>=0; i--) {
2217 QTreeWidgetItem currentSelection;
2218 currentSelection = selections.get(i);
2219 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2220 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2221 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2222 listManager.getSavedSearchIndex().remove(j);
2223 j=listManager.getSavedSearchIndex().size()+1;
2226 selections.remove(i);
2228 savedSearchIndexUpdated();
2229 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2231 // Setup the tree containing the user's tags
2232 private void initializeSavedSearchTree() {
2233 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2234 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2235 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2237 // Listener when a tag is selected
2238 @SuppressWarnings("unused")
2239 private void savedSearchTreeSelection() {
2240 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2242 clearNotebookFilter();
2245 clearAttributeFilter();
2247 String currentGuid = selectedSavedSearchGUID;
2248 menuBar.savedSearchEditAction.setEnabled(true);
2249 menuBar.savedSearchDeleteAction.setEnabled(true);
2250 menuBar.savedSearchIconAction.setEnabled(true);
2251 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2252 QTreeWidgetItem currentSelection;
2253 selectedSavedSearchGUID = "";
2254 for (int i=0; i<selections.size(); i++) {
2255 currentSelection = selections.get(i);
2256 if (currentSelection.text(1).equals(currentGuid)) {
2257 currentSelection.setSelected(false);
2259 selectedSavedSearchGUID = currentSelection.text(1);
2261 // i = selections.size() +1;
2264 // There is the potential for no notebooks to be selected if this
2265 // happens then we make it look like all notebooks were selecetd.
2266 // If that happens, just select the "all notebooks"
2267 if (selections.size()==0) {
2268 clearSavedSearchFilter();
2270 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2272 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2274 private void clearSavedSearchFilter() {
2275 menuBar.savedSearchEditAction.setEnabled(false);
2276 menuBar.savedSearchDeleteAction.setEnabled(false);
2277 menuBar.savedSearchIconAction.setEnabled(false);
2278 savedSearchTree.blockSignals(true);
2279 savedSearchTree.clearSelection();
2280 savedSearchTree.blockSignals(false);
2281 selectedSavedSearchGUID = "";
2282 searchField.setEditText("");
2283 searchPerformed = false;
2284 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2286 // trigger the tag index to be refreshed
2287 private void savedSearchIndexUpdated() {
2288 if (selectedSavedSearchGUID == null)
2289 selectedSavedSearchGUID = new String();
2290 savedSearchTree.blockSignals(true);
2291 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2292 savedSearchTree.load(listManager.getSavedSearchIndex());
2293 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2294 savedSearchTree.blockSignals(false);
2296 // trigger when the saved search selection changes
2297 @SuppressWarnings("unused")
2298 private void updateSavedSearchSelection() {
2299 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2301 menuBar.savedSearchEditAction.setEnabled(true);
2302 menuBar.savedSearchDeleteAction.setEnabled(true);
2303 menuBar.savedSearchIconAction.setEnabled(true);
2304 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2306 if (selections.size() > 0) {
2307 menuBar.savedSearchEditAction.setEnabled(true);
2308 menuBar.savedSearchDeleteAction.setEnabled(true);
2309 menuBar.savedSearchIconAction.setEnabled(true);
2310 selectedSavedSearchGUID = selections.get(0).text(1);
2311 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2312 searchField.setEditText(s.getQuery());
2314 menuBar.savedSearchEditAction.setEnabled(false);
2315 menuBar.savedSearchDeleteAction.setEnabled(false);
2316 menuBar.savedSearchIconAction.setEnabled(false);
2317 selectedSavedSearchGUID = "";
2318 searchField.setEditText("");
2320 searchFieldChanged();
2322 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2326 // Show/Hide note information
2327 private void toggleSavedSearchWindow() {
2328 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2329 if (savedSearchTree.isVisible())
2330 savedSearchTree.hide();
2332 savedSearchTree.show();
2333 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2335 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2336 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2338 // Change the icon for a saved search
2339 @SuppressWarnings("unused")
2340 private void setSavedSearchIcon() {
2341 QTreeWidgetItem currentSelection;
2342 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2343 if (selections.size() == 0)
2346 currentSelection = selections.get(0);
2347 String guid = currentSelection.text(1);
2349 QIcon currentIcon = currentSelection.icon(0);
2350 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2353 dialog = new SetIcon(currentIcon);
2354 dialog.setUseDefaultIcon(true);
2356 dialog = new SetIcon(icon);
2357 dialog.setUseDefaultIcon(false);
2360 if (dialog.okPressed()) {
2361 QIcon newIcon = dialog.getIcon();
2362 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2363 if (newIcon == null)
2364 newIcon = new QIcon(iconPath+"search.png");
2365 currentSelection.setIcon(0, newIcon);
2373 //***************************************************************
2374 //***************************************************************
2375 //** These functions deal with Help menu & tool menu items
2376 //***************************************************************
2377 //***************************************************************
2378 // Show database status
2379 @SuppressWarnings("unused")
2380 private void databaseStatus() {
2382 int dirty = conn.getNoteTable().getDirtyCount();
2383 int unindexed = conn.getNoteTable().getUnindexedCount();
2384 DatabaseStatus status = new DatabaseStatus();
2385 status.setUnsynchronized(dirty);
2386 status.setUnindexed(unindexed);
2387 status.setNoteCount(conn.getNoteTable().getNoteCount());
2388 status.setNotebookCount(listManager.getNotebookIndex().size());
2389 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2390 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2391 status.setTagCount(listManager.getTagIndex().size());
2392 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2393 status.setWordCount(conn.getWordsTable().getWordCount());
2397 // Compact the database
2398 @SuppressWarnings("unused")
2399 private void compactDatabase() {
2400 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2401 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2402 "but please be aware that depending upon the size of your database this can be time consuming " +
2403 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2404 QMessageBox.StandardButton.Yes,
2405 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2408 setMessage("Compacting database.");
2410 listManager.compactDatabase();
2412 setMessage("Database compact is complete.");
2413 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2415 @SuppressWarnings("unused")
2416 private void accountInformation() {
2417 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2418 AccountDialog dialog = new AccountDialog();
2420 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2422 @SuppressWarnings("unused")
2423 private void releaseNotes() {
2424 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2425 QDialog dialog = new QDialog(this);
2426 QHBoxLayout layout = new QHBoxLayout();
2427 QTextEdit textBox = new QTextEdit();
2428 layout.addWidget(textBox);
2429 textBox.setReadOnly(true);
2430 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2431 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2432 QIODevice.OpenModeFlag.Text)))
2434 textBox.setText(file.readAll().toString());
2436 dialog.setWindowTitle(tr("Release Notes"));
2437 dialog.setLayout(layout);
2439 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2441 // Called when user picks Log from the help menu
2442 @SuppressWarnings("unused")
2443 private void logger() {
2444 logger.log(logger.HIGH, "Entering NeverNote.logger");
2445 QDialog dialog = new QDialog(this);
2446 QHBoxLayout layout = new QHBoxLayout();
2447 QListWidget textBox = new QListWidget();
2448 layout.addWidget(textBox);
2449 textBox.addItems(emitLog);
2451 dialog.setLayout(layout);
2452 dialog.setWindowTitle(tr("Mesasge Log"));
2454 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2456 // Menu option "help/about" was selected
2457 @SuppressWarnings("unused")
2458 private void about() {
2459 logger.log(logger.HIGH, "Entering NeverNote.about");
2460 QMessageBox.about(this,
2461 tr("About NeverNote"),
2462 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2464 +tr("<hr></center>Evernote"
2465 +"An Open Source Evernote Client.<br><br>"
2466 +"Licensed under GPL v2. <br><hr><br>"
2467 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2468 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2469 +"PDFRenderer is licened under the LGPL<br>"
2470 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2471 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2472 +"Jazzy is licened under the LGPL<br>"
2473 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2474 logger.log(logger.HIGH, "Leaving NeverNote.about");
2476 // Hide the entire left hand side
2477 @SuppressWarnings("unused")
2478 private void toggleLeftSide() {
2481 hidden = !menuBar.hideLeftSide.isChecked();
2482 menuBar.hideLeftSide.setChecked(!hidden);
2484 if (notebookTree.isVisible() != hidden)
2485 toggleNotebookWindow();
2486 if (savedSearchTree.isVisible() != hidden)
2487 toggleSavedSearchWindow();
2488 if (tagTree.isVisible() != hidden)
2490 if (attributeTree.isVisible() != hidden)
2491 toggleAttributesWindow();
2492 if (trashTree.isVisible() != hidden)
2493 toggleTrashWindow();
2495 Global.saveWindowVisible("leftPanel", hidden);
2498 public void checkForUpdates() {
2499 // Send off thread to check for a new version
2500 versionChecker = new QNetworkAccessManager(this);
2501 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2502 QNetworkRequest request = new QNetworkRequest();
2503 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2504 versionChecker.get(request);
2506 @SuppressWarnings("unused")
2507 private void upgradeFileRead(QNetworkReply reply) {
2508 if (!reply.isReadable())
2511 String winVersion = Global.version;
2512 String osxVersion = Global.version;
2513 String linuxVersion = Global.version;
2514 String linux64Version = Global.version;
2515 String version = Global.version;
2517 // Determine the versions available
2518 QByteArray data = reply.readLine();
2519 while (data != null && !reply.atEnd()) {
2520 String line = data.toString();
2522 if (line.contains(":"))
2523 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2526 if (line.toLowerCase().contains("windows"))
2527 winVersion = lineVersion;
2528 else if (line.toLowerCase().contains("os-x"))
2529 osxVersion = lineVersion;
2530 else if (line.toLowerCase().contains("linux amd64"))
2531 linux64Version = lineVersion;
2532 else if (line.toLowerCase().contains("linux i386"))
2533 linuxVersion = lineVersion;
2534 else if (line.toLowerCase().contains("default"))
2535 version = lineVersion;
2537 // Read the next line
2538 data = reply.readLine();
2541 // Now we need to determine what system we are on.
2542 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2543 version = winVersion;
2544 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2545 version = osxVersion;
2546 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2547 if (System.getProperty("os.arch").contains("amd64") ||
2548 System.getProperty("os.arch").contains("x86_64") ||
2549 System.getProperty("os.arch").contains("i686"))
2550 version = linux64Version;
2552 version = linuxVersion;
2556 if (Global.version.equals(version))
2559 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2561 if (dialog.remindMe())
2562 Global.setCheckVersionUpgrade(true);
2564 Global.setCheckVersionUpgrade(false);
2568 //***************************************************************
2569 //***************************************************************
2570 //** These functions deal with the Toolbar
2571 //***************************************************************
2572 //***************************************************************
2573 // Text in the search bar has been cleared
2574 private void searchFieldCleared() {
2577 // This is done because we want to force a reload of
2578 // images. Some images we may want to highlight the text.
2579 readOnlyCache.clear();
2580 inkNoteCache.clear();
2582 QWebSettings.setMaximumPagesInCache(0);
2583 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2585 searchField.setEditText("");
2586 saveNoteColumnPositions();
2587 saveNoteIndexWidth();
2588 noteIndexUpdated(true);
2589 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2590 currentNote = listManager.getNoteIndex().get(0);
2591 currentNoteGuid = currentNote.getGuid();
2593 if (currentNote != null)
2594 loadNoteBrowserInformation(browserWindow);
2596 // text in the search bar changed. We only use this to tell if it was cleared,
2597 // otherwise we trigger off searchFieldChanged.
2598 @SuppressWarnings("unused")
2599 private void searchFieldTextChanged(String text) {
2600 QWebSettings.setMaximumPagesInCache(0);
2601 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2603 if (text.trim().equals("")) {
2604 searchFieldCleared();
2605 if (searchPerformed) {
2607 // This is done because we want to force a reload of
2608 // images. Some images we may want to highlight the text.
2610 readOnlyCache.clear();
2611 inkNoteCache.clear();
2613 listManager.setEnSearch("");
2614 listManager.loadNotesIndex();
2615 refreshEvernoteNote(true);
2616 noteIndexUpdated(false);
2618 searchPerformed = false;
2621 // Text in the toolbar has changed
2622 private void searchFieldChanged() {
2623 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2625 readOnlyCache.clear();
2626 inkNoteCache.clear();
2627 saveNoteColumnPositions();
2628 saveNoteIndexWidth();
2629 String text = searchField.currentText();
2630 listManager.setEnSearch(text.trim());
2631 listManager.loadNotesIndex();
2632 //--->>> noteIndexUpdated(true);
2633 noteIndexUpdated(false);
2634 refreshEvernoteNote(true);
2635 searchPerformed = true;
2636 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2639 // Build the window tool bar
2640 private void setupToolBar() {
2641 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2642 toolBar = addToolBar(tr("Tool Bar"));
2643 menuBar.setupToolBarVisible();
2644 if (!Global.isWindowVisible("toolBar"))
2645 toolBar.setVisible(false);
2647 toolBar.setVisible(true);
2649 prevButton = toolBar.addAction("Previous");
2650 QIcon prevIcon = new QIcon(iconPath+"back.png");
2651 prevButton.setIcon(prevIcon);
2652 prevButton.triggered.connect(this, "previousViewedAction()");
2653 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2655 nextButton = toolBar.addAction("Next");
2656 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2657 nextButton.setIcon(nextIcon);
2658 nextButton.triggered.connect(this, "nextViewedAction()");
2659 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2661 upButton = toolBar.addAction("Up");
2662 QIcon upIcon = new QIcon(iconPath+"up.png");
2663 upButton.setIcon(upIcon);
2664 upButton.triggered.connect(this, "upAction()");
2665 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2668 downButton = toolBar.addAction("Down");
2669 QIcon downIcon = new QIcon(iconPath+"down.png");
2670 downButton.setIcon(downIcon);
2671 downButton.triggered.connect(this, "downAction()");
2672 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2674 synchronizeButton = toolBar.addAction("Synchronize");
2675 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2676 synchronizeIconAngle = 0;
2677 synchronizeButton.triggered.connect(this, "evernoteSync()");
2678 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2680 printButton = toolBar.addAction("Print");
2681 QIcon printIcon = new QIcon(iconPath+"print.png");
2682 printButton.setIcon(printIcon);
2683 printButton.triggered.connect(this, "printNote()");
2684 togglePrintButton(Global.isToolbarButtonVisible("print"));
2686 tagButton = toolBar.addAction("Tag");
2687 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2688 tagButton.setIcon(tagIcon);
2689 tagButton.triggered.connect(browserWindow, "modifyTags()");
2690 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2692 attributeButton = toolBar.addAction("Attributes");
2693 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2694 attributeButton.setIcon(attributeIcon);
2695 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2696 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2698 emailButton = toolBar.addAction("Email");
2699 QIcon emailIcon = new QIcon(iconPath+"email.png");
2700 emailButton.setIcon(emailIcon);
2701 emailButton.triggered.connect(this, "emailNote()");
2702 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2704 deleteButton = toolBar.addAction("Delete");
2705 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2706 deleteButton.setIcon(deleteIcon);
2707 deleteButton.triggered.connect(this, "deleteNote()");
2708 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2710 newButton = toolBar.addAction("New");
2711 QIcon newIcon = new QIcon(iconPath+"new.png");
2712 newButton.triggered.connect(this, "addNote()");
2713 newButton.setIcon(newIcon);
2714 toggleNewButton(Global.isToolbarButtonVisible("new"));
2716 allNotesButton = toolBar.addAction("All Notes");
2717 QIcon allIcon = new QIcon(iconPath+"books.png");
2718 allNotesButton.triggered.connect(this, "allNotes()");
2719 allNotesButton.setIcon(allIcon);
2720 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2722 toolBar.addSeparator();
2723 toolBar.addWidget(new QLabel(tr("Quota:")));
2724 toolBar.addWidget(quotaBar);
2725 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2727 toolBar.addSeparator();
2730 zoomSpinner = new QSpinBox();
2731 zoomSpinner.setMinimum(10);
2732 zoomSpinner.setMaximum(1000);
2733 zoomSpinner.setAccelerated(true);
2734 zoomSpinner.setSingleStep(10);
2735 zoomSpinner.setValue(100);
2736 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2737 toolBar.addWidget(new QLabel(tr("Zoom")));
2738 toolBar.addWidget(zoomSpinner);
2740 //toolBar.addWidget(new QLabel(" "));
2741 toolBar.addSeparator();
2742 toolBar.addWidget(new QLabel(tr(" Search:")));
2743 toolBar.addWidget(searchField);
2744 QSizePolicy sizePolicy = new QSizePolicy();
2745 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2746 searchField.setSizePolicy(sizePolicy);
2747 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2749 searchClearButton = toolBar.addAction("Search Clear");
2750 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2751 searchClearButton.setIcon(searchClearIcon);
2752 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2753 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2755 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2757 // Update the sychronize button picture
2759 public QMenu createPopupMenu() {
2760 QMenu contextMenu = super.createPopupMenu();
2762 contextMenu.addSeparator();
2763 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2764 contextMenu.addAction(prevAction);
2765 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2767 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2768 contextMenu.addAction(nextAction);
2769 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2771 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2772 contextMenu.addAction(upAction);
2773 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2775 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2776 contextMenu.addAction(downAction);
2777 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2779 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2780 contextMenu.addAction(synchronizeAction);
2781 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2783 QAction printAction = addContextAction("print", tr("Print"));
2784 contextMenu.addAction(printAction);
2785 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2787 QAction tagAction = addContextAction("tag", tr("Tag"));
2788 contextMenu.addAction(tagAction);
2789 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2791 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2792 contextMenu.addAction(attributeAction);
2793 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2795 QAction emailAction = addContextAction("email", tr("Email"));
2796 contextMenu.addAction(emailAction);
2797 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2799 QAction deleteAction = addContextAction("delete", tr("Delete"));
2800 contextMenu.addAction(deleteAction);
2801 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2803 QAction newAction = addContextAction("new", tr("Add"));
2804 contextMenu.addAction(newAction);
2805 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2807 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2808 contextMenu.addAction(allNotesAction);
2809 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2811 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2812 contextMenu.addAction(searchClearAction);
2813 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2818 private QAction addContextAction(String config, String name) {
2819 QAction newAction = new QAction(this);
2820 newAction.setText(name);
2821 newAction.setCheckable(true);
2822 newAction.setChecked(Global.isToolbarButtonVisible(config));
2825 private void togglePrevArrowButton(Boolean toggle) {
2826 prevButton.setVisible(toggle);
2827 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2829 private void toggleNextArrowButton(Boolean toggle) {
2830 nextButton.setVisible(toggle);
2831 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2833 private void toggleUpArrowButton(Boolean toggle) {
2834 upButton.setVisible(toggle);
2835 Global.saveToolbarButtonsVisible("upArrow", toggle);
2837 private void toggleDownArrowButton(Boolean toggle) {
2838 downButton.setVisible(toggle);
2839 Global.saveToolbarButtonsVisible("downArrow", toggle);
2841 private void toggleSynchronizeButton(Boolean toggle) {
2842 synchronizeButton.setVisible(toggle);
2843 Global.saveToolbarButtonsVisible("synchronize", toggle);
2845 private void togglePrintButton(Boolean toggle) {
2846 printButton.setVisible(toggle);
2847 Global.saveToolbarButtonsVisible("print", toggle);
2849 private void toggleTagButton(Boolean toggle) {
2850 tagButton.setVisible(toggle);
2851 Global.saveToolbarButtonsVisible("tag", toggle);
2853 private void toggleAttributeButton(Boolean toggle) {
2854 attributeButton.setVisible(toggle);
2855 Global.saveToolbarButtonsVisible("attribute", toggle);
2857 private void toggleEmailButton(Boolean toggle) {
2858 emailButton.setVisible(toggle);
2859 Global.saveToolbarButtonsVisible("email", toggle);
2861 private void toggleDeleteButton(Boolean toggle) {
2862 deleteButton.setVisible(toggle);
2863 Global.saveToolbarButtonsVisible("delete", toggle);
2865 private void toggleNewButton(Boolean toggle) {
2866 newButton.setVisible(toggle);
2867 Global.saveToolbarButtonsVisible("new", toggle);
2869 private void toggleAllNotesButton(Boolean toggle) {
2870 allNotesButton.setVisible(toggle);
2871 Global.saveToolbarButtonsVisible("allNotes", toggle);
2873 private void toggleSearchClearButton(Boolean toggle) {
2874 searchClearButton.setVisible(toggle);
2875 Global.saveToolbarButtonsVisible("searchClear", toggle);
2882 @SuppressWarnings("unused")
2883 private void updateSyncButton() {
2885 if (syncIcons == null) {
2886 syncIcons = new ArrayList<QPixmap>();
2888 synchronizeIconAngle = 0;
2889 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2891 for (int i=0; i<=360; i++) {
2892 QPixmap rotatedPix = new QPixmap(pix.size());
2893 QPainter p = new QPainter(rotatedPix);
2894 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2895 QSize size = pix.size();
2896 p.translate(size.width()/2, size.height()/2);
2899 p.setBackgroundMode(BGMode.OpaqueMode);
2900 p.translate(-size.width()/2, -size.height()/2);
2901 p.drawPixmap(0,0, pix);
2903 syncIcons.add(rotatedPix);
2907 synchronizeIconAngle++;
2908 if (synchronizeIconAngle > 359)
2909 synchronizeIconAngle=0;
2910 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2913 // Synchronize with Evernote
2914 @SuppressWarnings("unused")
2915 private void evernoteSync() {
2916 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2917 if (!Global.isConnected)
2919 if (Global.isConnected)
2920 synchronizeAnimationTimer.start(5);
2921 // synchronizeAnimationTimer.start(200);
2923 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2925 private void updateQuotaBar() {
2926 long limit = Global.getUploadLimit();
2927 long amount = Global.getUploadAmount();
2928 if (amount>0 && limit>0) {
2929 int percent =(int)(amount*100/limit);
2930 quotaBar.setValue(percent);
2932 quotaBar.setValue(0);
2935 @SuppressWarnings("unused")
2936 private void zoomChanged() {
2937 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2940 //****************************************************************
2941 //****************************************************************
2942 //* System Tray functions
2943 //****************************************************************
2944 //****************************************************************
2945 private void trayToggleVisible() {
2950 if (windowMaximized)
2957 @SuppressWarnings("unused")
2958 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2959 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2960 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2961 trayToggleVisible();
2966 //***************************************************************
2967 //***************************************************************
2968 //** These functions deal with the trash tree
2969 //***************************************************************
2970 //***************************************************************
2971 // Setup the tree containing the trash.
2972 @SuppressWarnings("unused")
2973 private void trashTreeSelection() {
2974 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2976 clearNotebookFilter();
2978 clearAttributeFilter();
2979 clearSavedSearchFilter();
2981 String tempGuid = currentNoteGuid;
2983 // currentNoteGuid = "";
2984 currentNote = new Note();
2985 selectedNoteGUIDs.clear();
2986 listManager.getSelectedNotebooks().clear();
2987 listManager.getSelectedTags().clear();
2988 listManager.setSelectedSavedSearch("");
2989 browserWindow.clear();
2991 // toggle the add buttons
2992 newButton.setEnabled(!newButton.isEnabled());
2993 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2994 menuBar.noteAdd.setVisible(true);
2996 List<QTreeWidgetItem> selections = trashTree.selectedItems();
2997 if (selections.size() == 0) {
2998 currentNoteGuid = trashNoteGuid;
2999 trashNoteGuid = tempGuid;
3000 Global.showDeleted = false;
3001 menuBar.noteRestoreAction.setEnabled(false);
3002 menuBar.noteRestoreAction.setVisible(false);
3005 currentNoteGuid = trashNoteGuid;
3006 trashNoteGuid = tempGuid;
3007 menuBar.noteRestoreAction.setEnabled(true);
3008 menuBar.noteRestoreAction.setVisible(true);
3009 Global.showDeleted = true;
3011 listManager.loadNotesIndex();
3012 noteIndexUpdated(false);
3013 //// browserWindow.setEnabled(newButton.isEnabled());
3014 browserWindow.setReadOnly(!newButton.isEnabled());
3015 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3017 // Empty the trash file
3018 @SuppressWarnings("unused")
3019 private void emptyTrash() {
3020 // browserWindow.clear();
3021 listManager.emptyTrash();
3022 if (trashTree.selectedItems().size() > 0) {
3023 listManager.getSelectedNotebooks().clear();
3024 listManager.getSelectedTags().clear();
3025 listManager.setSelectedSavedSearch("");
3026 newButton.setEnabled(!newButton.isEnabled());
3027 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3028 menuBar.noteAdd.setVisible(true);
3029 browserWindow.clear();
3032 clearNotebookFilter();
3033 clearSavedSearchFilter();
3034 clearAttributeFilter();
3036 Global.showDeleted = false;
3037 menuBar.noteRestoreAction.setEnabled(false);
3038 menuBar.noteRestoreAction.setVisible(false);
3040 listManager.loadNotesIndex();
3041 //--->>> noteIndexUpdated(true);
3042 noteIndexUpdated(false);
3045 // Show/Hide trash window
3046 private void toggleTrashWindow() {
3047 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3048 if (trashTree.isVisible())
3052 menuBar.hideTrash.setChecked(trashTree.isVisible());
3054 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3055 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3057 private void clearTrashFilter() {
3058 Global.showDeleted = false;
3059 newButton.setEnabled(true);
3060 menuBar.noteAdd.setEnabled(true);
3061 menuBar.noteAdd.setVisible(true);
3062 trashTree.blockSignals(true);
3063 trashTree.clearSelection();
3064 trashTree.blockSignals(false);
3069 //***************************************************************
3070 //***************************************************************
3071 //** These functions deal with connection settings
3072 //***************************************************************
3073 //***************************************************************
3074 // SyncRunner had a problem and things are disconnected
3075 @SuppressWarnings("unused")
3076 private void remoteErrorDisconnect() {
3077 menuBar.connectAction.setText(tr("Connect"));
3078 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3079 menuBar.synchronizeAction.setEnabled(false);
3080 Global.isConnected = false;
3081 synchronizeAnimationTimer.stop();
3084 // Do a manual connect/disconnect
3085 private void remoteConnect() {
3086 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3088 if (Global.isConnected) {
3089 Global.isConnected = false;
3090 syncRunner.enDisconnect();
3091 setupConnectMenuOptions();
3096 AESEncrypter aes = new AESEncrypter();
3098 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3099 } catch (FileNotFoundException e) {
3100 // File not found, so we'll just get empty strings anyway.
3102 String userid = aes.getUserid();
3103 String password = aes.getPassword();
3104 if (!userid.equals("") && !password.equals("")) {
3105 Global.username = userid;
3106 Global.password = password;
3109 // Show the login dialog box
3110 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3111 LoginDialog login = new LoginDialog();
3114 if (!login.okPressed()) {
3118 Global.username = login.getUserid();
3119 Global.password = login.getPassword();
3121 syncRunner.username = Global.username;
3122 syncRunner.password = Global.password;
3123 syncRunner.userStoreUrl = Global.userStoreUrl;
3124 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3125 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3127 if (Global.getProxyValue("url").equals("")) {
3128 System.setProperty("http.proxyHost","") ;
3129 System.setProperty("http.proxyPort", "") ;
3130 System.setProperty("https.proxyHost","") ;
3131 System.setProperty("https.proxyPort", "") ;
3134 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3135 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3136 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3137 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3139 if (Global.getProxyValue("userid").equals("")) {
3140 Authenticator.setDefault(new Authenticator() {
3142 protected PasswordAuthentication getPasswordAuthentication() {
3144 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3150 syncRunner.enConnect();
3151 Global.isConnected = syncRunner.isConnected;
3153 setupConnectMenuOptions();
3154 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3156 private void setupConnectMenuOptions() {
3157 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3158 if (!Global.isConnected) {
3159 menuBar.connectAction.setText(tr("Connect"));
3160 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3161 menuBar.synchronizeAction.setEnabled(false);
3163 menuBar.connectAction.setText(tr("Disconnect"));
3164 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3165 menuBar.synchronizeAction.setEnabled(true);
3167 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3172 //***************************************************************
3173 //***************************************************************
3174 //** These functions deal with the GUI Attribute tree
3175 //***************************************************************
3176 //***************************************************************
3177 @SuppressWarnings("unused")
3178 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3180 // clearTagFilter();
3181 // clearNotebookFilter();
3183 // clearSavedSearchFilter();
3185 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3186 if (item.childCount() > 0) {
3187 item.setSelected(false);
3189 Global.createdBeforeFilter.reset();
3190 Global.createdSinceFilter.reset();
3191 Global.changedBeforeFilter.reset();
3192 Global.changedSinceFilter.reset();
3193 Global.containsFilter.reset();
3194 attributeTreeSelected = item;
3195 DateAttributeFilterTable f = null;
3196 f = findDateAttributeFilterTable(item.parent());
3198 f.select(item.parent().indexOfChild(item));
3200 Global.containsFilter.select(item.parent().indexOfChild(item));
3203 listManager.loadNotesIndex();
3204 noteIndexUpdated(false);
3207 attributeTreeSelected = null;
3208 item.setSelected(false);
3209 Global.createdBeforeFilter.reset();
3210 Global.createdSinceFilter.reset();
3211 Global.changedBeforeFilter.reset();
3212 Global.changedSinceFilter.reset();
3213 Global.containsFilter.reset();
3214 listManager.loadNotesIndex();
3215 noteIndexUpdated(false);
3217 // This determines what attribute filter we need, depending upon the selection
3218 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3219 if (w.parent() != null && w.childCount() > 0) {
3220 QTreeWidgetItem parent = w.parent();
3221 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3222 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3223 return Global.createdSinceFilter;
3224 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3225 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3226 return Global.createdBeforeFilter;
3227 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3228 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3229 return Global.changedSinceFilter;
3230 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3231 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3232 return Global.changedBeforeFilter;
3237 // Show/Hide attribute search window
3238 private void toggleAttributesWindow() {
3239 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3240 if (attributeTree.isVisible())
3241 attributeTree.hide();
3243 attributeTree.show();
3244 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3246 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3247 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3249 private void clearAttributeFilter() {
3250 Global.createdBeforeFilter.reset();
3251 Global.createdSinceFilter.reset();
3252 Global.changedBeforeFilter.reset();
3253 Global.changedSinceFilter.reset();
3254 Global.containsFilter.reset();
3255 attributeTreeSelected = null;
3256 attributeTree.blockSignals(true);
3257 attributeTree.clearSelection();
3258 attributeTree.blockSignals(false);
3262 //***************************************************************
3263 //***************************************************************
3264 //** These functions deal with the GUI Note index table
3265 //***************************************************************
3266 //***************************************************************
3267 // Initialize the note list table
3268 private void initializeNoteTable() {
3269 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3270 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3271 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3272 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3274 // Show/Hide trash window
3275 @SuppressWarnings("unused")
3276 private void toggleNoteListWindow() {
3277 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3278 if (noteTableView.isVisible())
3279 noteTableView.hide();
3281 noteTableView.show();
3282 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3284 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3285 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3287 // Handle the event that a user selects a note from the table
3288 @SuppressWarnings("unused")
3289 private void noteTableSelection() {
3290 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3292 if (historyGuids.size() == 0) {
3293 historyGuids.add(currentNoteGuid);
3294 historyPosition = 1;
3296 noteTableView.showColumn(Global.noteTableGuidPosition);
3298 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3299 if (!Global.isColumnVisible("guid"))
3300 noteTableView.hideColumn(Global.noteTableGuidPosition);
3302 if (selections.size() > 0) {
3304 menuBar.noteDuplicateAction.setEnabled(true);
3305 menuBar.noteOnlineHistoryAction.setEnabled(true);
3306 menuBar.noteMergeAction.setEnabled(true);
3307 selectedNoteGUIDs.clear();
3308 if (selections.size() != 1 || Global.showDeleted) {
3309 menuBar.noteDuplicateAction.setEnabled(false);
3311 if (selections.size() != 1 || !Global.isConnected) {
3312 menuBar.noteOnlineHistoryAction.setEnabled(false);
3314 if (selections.size() == 1) {
3315 menuBar.noteMergeAction.setEnabled(false);
3317 for (int i=0; i<selections.size(); i++) {
3318 int row = selections.get(i).row();
3320 upButton.setEnabled(false);
3322 upButton.setEnabled(true);
3323 if (row < listManager.getNoteTableModel().rowCount()-1)
3324 downButton.setEnabled(true);
3326 downButton.setEnabled(false);
3327 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3328 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3329 currentNoteGuid = (String)ix.values().toArray()[0];
3330 selectedNoteGUIDs.add(currentNoteGuid);
3334 nextButton.setEnabled(true);
3335 prevButton.setEnabled(true);
3337 int endPosition = historyGuids.size()-1;
3338 for (int j=historyPosition; j<=endPosition; j++) {
3339 historyGuids.remove(historyGuids.size()-1);
3341 historyGuids.add(currentNoteGuid);
3342 historyPosition = historyGuids.size();
3344 if (historyPosition <= 1)
3345 prevButton.setEnabled(false);
3346 if (historyPosition == historyGuids.size())
3347 nextButton.setEnabled(false);
3349 fromHistory = false;
3350 scrollToGuid(currentNoteGuid);
3351 refreshEvernoteNote(true);
3352 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3354 // Trigger a refresh when the note db has been updated
3355 private void noteIndexUpdated(boolean reload) {
3356 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3358 refreshEvernoteNoteList();
3359 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3360 noteTableView.load(reload);
3361 scrollToGuid(currentNoteGuid);
3362 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3364 // Called when the list of notes is updated
3365 private void refreshEvernoteNoteList() {
3366 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3367 browserWindow.setDisabled(false);
3368 if (selectedNoteGUIDs == null)
3369 selectedNoteGUIDs = new ArrayList<String>();
3370 selectedNoteGUIDs.clear(); // clear out old entries
3372 String saveCurrentNoteGuid = new String();
3373 String tempNoteGuid = new String();
3375 historyGuids.clear();
3376 historyPosition = 0;
3377 prevButton.setEnabled(false);
3378 nextButton.setEnabled(false);
3380 if (currentNoteGuid == null)
3381 currentNoteGuid = new String();
3383 //determine current note guid
3384 for (Note note : listManager.getNoteIndex()) {
3385 tempNoteGuid = note.getGuid();
3386 if (currentNoteGuid.equals(tempNoteGuid)) {
3387 saveCurrentNoteGuid = tempNoteGuid;
3391 if (listManager.getNoteIndex().size() == 0) {
3392 currentNoteGuid = "";
3394 browserWindow.clear();
3395 browserWindow.setDisabled(true);
3398 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() > 0) {
3399 currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
3400 currentNoteGuid = currentNote.getGuid();
3401 refreshEvernoteNote(true);
3403 //we can reload if note not dirty
3404 // refreshEvernoteNote(!noteDirty);
3405 refreshEvernoteNote(false);
3407 reloadTagTree(false);
3409 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3411 // Called when the previous arrow button is clicked
3412 @SuppressWarnings("unused")
3413 private void previousViewedAction() {
3414 if (!prevButton.isEnabled())
3416 if (historyPosition == 0)
3419 if (historyPosition <= 0)
3421 String historyGuid = historyGuids.get(historyPosition-1);
3423 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3424 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3425 if (modelIndex != null) {
3426 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3427 String tableGuid = (String)ix.values().toArray()[0];
3428 if (tableGuid.equals(historyGuid)) {
3429 noteTableView.selectRow(i);
3435 @SuppressWarnings("unused")
3436 private void nextViewedAction() {
3437 if (!nextButton.isEnabled())
3439 String historyGuid = historyGuids.get(historyPosition);
3442 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3443 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3444 if (modelIndex != null) {
3445 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3446 String tableGuid = (String)ix.values().toArray()[0];
3447 if (tableGuid.equals(historyGuid)) {
3448 noteTableView.selectRow(i);
3454 // Called when the up arrow is clicked
3455 @SuppressWarnings("unused")
3456 private void upAction() {
3457 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3458 int row = selections.get(0).row();
3460 noteTableView.selectRow(row-1);
3463 // Called when the down arrow is clicked
3464 @SuppressWarnings("unused")
3465 private void downAction() {
3466 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3467 int row = selections.get(0).row();
3468 int max = listManager.getNoteTableModel().rowCount();
3470 noteTableView.selectRow(row+1);
3473 // Update a tag string for a specific note in the list
3474 @SuppressWarnings("unused")
3475 private void updateListTags(String guid, List<String> tags) {
3476 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3477 StringBuffer tagBuffer = new StringBuffer();
3478 for (int i=0; i<tags.size(); i++) {
3479 tagBuffer.append(tags.get(i));
3480 if (i<tags.size()-1)
3481 tagBuffer.append(", ");
3484 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3485 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3486 if (modelIndex != null) {
3487 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3488 String tableGuid = (String)ix.values().toArray()[0];
3489 if (tableGuid.equals(guid)) {
3490 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3491 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3492 noteTableView.proxyModel.invalidate();
3497 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3499 // Update a title for a specific note in the list
3500 @SuppressWarnings("unused")
3501 private void updateListAuthor(String guid, String author) {
3502 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3504 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3505 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3506 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3507 if (modelIndex != null) {
3508 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3509 String tableGuid = (String)ix.values().toArray()[0];
3510 if (tableGuid.equals(guid)) {
3511 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3512 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3513 noteTableView.proxyModel.invalidate();
3519 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3521 private void updateListNoteNotebook(String guid, String notebook) {
3522 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3523 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3524 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3526 // Update a title for a specific note in the list
3527 @SuppressWarnings("unused")
3528 private void updateListSourceUrl(String guid, String url) {
3529 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3531 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3532 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3533 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3534 if (modelIndex != null) {
3535 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3536 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3537 String tableGuid = (String)ix.values().toArray()[0];
3538 if (tableGuid.equals(guid)) {
3539 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3540 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3541 noteTableView.proxyModel.invalidate();
3546 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3548 @SuppressWarnings("unused")
3549 private void updateListGuid(String oldGuid, String newGuid) {
3550 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3552 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3553 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3554 if (modelIndex != null) {
3555 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3556 String tableGuid = (String)ix.values().toArray()[0];
3557 if (tableGuid.equals(oldGuid)) {
3558 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3559 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3564 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3566 private void updateListTagName(String guid) {
3567 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3569 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3570 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3571 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3573 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3574 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3575 if (modelIndex != null) {
3576 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3577 String noteGuid = (String)ix.values().toArray()[0];
3578 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3579 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3580 i=listManager.getNoteTableModel().rowCount();
3586 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3588 private void removeListTagName(String guid) {
3589 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3591 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3592 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3593 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3594 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3595 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3598 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3599 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3600 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3601 if (modelIndex != null) {
3602 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3603 String noteGuid = (String)ix.values().toArray()[0];
3604 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3605 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3606 i=listManager.getNoteTableModel().rowCount();
3612 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3614 private void updateListNotebookName(String oldName, String newName) {
3615 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3617 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3618 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3619 if (modelIndex != null) {
3620 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3621 String tableName = (String)ix.values().toArray()[0];
3622 if (tableName.equalsIgnoreCase(oldName)) {
3623 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3627 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3629 @SuppressWarnings("unused")
3630 private void updateListDateCreated(String guid, QDateTime date) {
3631 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3633 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3634 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3635 if (modelIndex != null) {
3636 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3637 String tableGuid = (String)ix.values().toArray()[0];
3638 if (tableGuid.equals(guid)) {
3639 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3640 noteTableView.proxyModel.invalidate();
3645 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3647 @SuppressWarnings("unused")
3648 private void updateListDateSubject(String guid, QDateTime date) {
3649 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3651 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3652 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3653 if (modelIndex != null) {
3654 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3655 String tableGuid = (String)ix.values().toArray()[0];
3656 if (tableGuid.equals(guid)) {
3657 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3658 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3659 noteTableView.proxyModel.invalidate();
3664 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3666 private void updateListDateChanged(String guid, QDateTime date) {
3667 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3669 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3670 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3671 if (modelIndex != null) {
3672 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3673 String tableGuid = (String)ix.values().toArray()[0];
3674 if (tableGuid.equals(guid)) {
3675 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3676 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3681 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3683 private void updateListDateChanged() {
3684 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3685 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3686 updateListDateChanged(currentNoteGuid, date);
3687 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3690 private void scrollToCurrentGuid() {
3691 //scrollToGuid(currentNoteGuid);
3692 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3693 if (selections.size() == 0)
3695 QModelIndex index = selections.get(0);
3696 int row = selections.get(0).row();
3697 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3700 // Scroll to a particular index item
3701 private void scrollToGuid(String guid) {
3702 if (currentNote == null || guid == null)
3704 if (currentNote.isActive() && Global.showDeleted) {
3705 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3706 if (!listManager.getNoteIndex().get(i).isActive()) {
3707 currentNote = listManager.getNoteIndex().get(i);
3708 currentNoteGuid = currentNote.getGuid();
3709 i = listManager.getNoteIndex().size();
3714 if (!currentNote.isActive() && !Global.showDeleted) {
3715 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3716 if (listManager.getNoteIndex().get(i).isActive()) {
3717 currentNote = listManager.getNoteIndex().get(i);
3718 currentNoteGuid = currentNote.getGuid();
3719 i = listManager.getNoteIndex().size();
3725 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3726 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3727 if (currentNoteGuid.equals(index.data())) {
3728 // noteTableView.setCurrentIndex(index);
3729 noteTableView.selectRow(i);
3730 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3731 i=listManager.getNoteTableModel().rowCount();
3734 noteTableView.repaint();
3736 // Show/Hide columns
3737 private void showColumns() {
3738 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3739 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3740 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3741 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3742 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3743 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3744 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3745 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3746 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3747 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3748 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3750 // Title color has changed
3751 @SuppressWarnings("unused")
3752 private void titleColorChanged(Integer color) {
3753 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3755 QColor backgroundColor = new QColor();
3756 QColor foregroundColor = new QColor(QColor.black);
3757 backgroundColor.setRgb(color);
3759 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3760 foregroundColor.setRgb(QColor.white.rgb());
3762 if (selectedNoteGUIDs.size() == 0)
3763 selectedNoteGUIDs.add(currentNoteGuid);
3765 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3766 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3767 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3768 if (modelIndex != null) {
3769 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3770 String tableGuid = (String)ix.values().toArray()[0];
3771 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3772 for (int k=0; k<Global.noteTableColumnCount; k++) {
3773 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3774 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3775 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3777 i=listManager.getNoteTableModel().rowCount();
3782 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3784 // Wide list was chosen
3785 public void narrowListView() {
3786 saveNoteColumnPositions();
3787 saveNoteIndexWidth();
3789 int sortCol = noteTableView.proxyModel.sortColumn();
3790 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3791 Global.setSortColumn(sortCol);
3792 Global.setSortOrder(sortOrder);
3794 Global.setListView(Global.View_List_Narrow);
3796 menuBar.wideListView.blockSignals(true);
3797 menuBar.narrowListView.blockSignals(true);
3799 menuBar.wideListView.setChecked(false);
3800 menuBar.narrowListView.setChecked(true);
3802 menuBar.wideListView.blockSignals(false);
3803 menuBar.narrowListView.blockSignals(false);
3805 mainLeftRightSplitter.addWidget(noteTableView);
3806 mainLeftRightSplitter.addWidget(browserWindow);
3807 restoreWindowState(false);
3808 noteTableView.repositionColumns();
3809 noteTableView.resizeColumnWidths();
3810 noteTableView.resizeRowHeights();
3812 sortCol = Global.getSortColumn();
3813 sortOrder = Global.getSortOrder();
3814 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3817 noteTableView.load(false);
3818 scrollToCurrentGuid();
3820 public void wideListView() {
3821 int sortCol = noteTableView.proxyModel.sortColumn();
3822 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3823 Global.setSortColumn(sortCol);
3824 Global.setSortOrder(sortOrder);
3827 saveNoteColumnPositions();
3828 saveNoteIndexWidth();
3829 Global.setListView(Global.View_List_Wide);
3831 menuBar.wideListView.blockSignals(true);
3832 menuBar.narrowListView.blockSignals(true);
3834 menuBar.wideListView.setChecked(true);
3835 menuBar.narrowListView.setChecked(false);
3837 menuBar.wideListView.blockSignals(false);
3838 menuBar.narrowListView.blockSignals(false);
3839 browserIndexSplitter.setVisible(true);
3840 browserIndexSplitter.addWidget(noteTableView);
3841 browserIndexSplitter.addWidget(browserWindow);
3842 restoreWindowState(false);
3843 noteTableView.repositionColumns();
3844 noteTableView.resizeColumnWidths();
3845 noteTableView.resizeRowHeights();
3847 sortCol = Global.getSortColumn();
3848 sortOrder = Global.getSortOrder();
3849 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3852 noteTableView.load(false);
3853 scrollToCurrentGuid();
3857 //***************************************************************
3858 //***************************************************************
3859 //** External editor window functions
3860 //***************************************************************
3861 //***************************************************************
3862 private void listDoubleClick() {
3864 if (externalWindows.containsKey(currentNoteGuid)) {
3865 externalWindows.get(currentNoteGuid).raise();
3868 // We have a new external editor to create
3869 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3870 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3871 newBrowser.setWindowIcon(appIcon);
3872 externalWindows.put(currentNoteGuid, newBrowser);
3873 showEditorButtons(newBrowser.getBrowserWindow());
3874 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3875 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3876 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3877 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3878 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3879 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3881 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3882 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3883 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3887 @SuppressWarnings("unused")
3888 private void externalWindowTitleEdited(String guid, String text) {
3889 if (guid.equals(currentNoteGuid)) {
3890 browserWindow.setTitle(text);
3893 @SuppressWarnings({ "rawtypes", "unused" })
3894 private void externalWindowTagsEdited(String guid, List values) {
3895 StringBuffer line = new StringBuffer(100);
3896 for (int i=0; i<values.size(); i++) {
3898 line.append(Global.tagDelimeter+" ");
3899 line.append(values.get(i));
3901 if (guid.equals(currentNoteGuid)) {
3902 browserWindow.setTag(line.toString());
3905 @SuppressWarnings("unused")
3906 private void externalWindowClosing(String guid) {
3907 externalWindows.remove(guid);
3912 //***************************************************************
3913 //***************************************************************
3914 //** These functions deal with Note specific things
3915 //***************************************************************
3916 //***************************************************************
3917 @SuppressWarnings("unused")
3918 private void setNoteDirty() {
3919 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
3920 // Find if the note is being edited externally. If it is, update it.
3921 if (externalWindows.containsKey(currentNoteGuid)) {
3922 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3923 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
3924 ExternalBrowse window = externalWindows.get(currentNoteGuid);
3925 window.getBrowserWindow().getBrowser().setContent(unicode);
3928 // If the note is dirty, then it is unsynchronized by default.
3932 // Set the note as dirty and check if its status is synchronized in the display table
3934 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
3935 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
3939 // If this wasn't already marked as unsynchronized, then we need to update the table
3940 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
3941 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
3942 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3943 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3944 if (modelIndex != null) {
3945 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3946 String tableGuid = (String)ix.values().toArray()[0];
3947 if (tableGuid.equals(currentNoteGuid)) {
3948 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3954 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
3956 @SuppressWarnings("unused")
3957 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
3958 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3959 QByteArray unicode = codec.fromUnicode(content);
3960 noteCache.remove(guid);
3961 noteCache.put(guid, unicode.toString());
3962 if (guid.equals(currentNoteGuid)) {
3964 browserWindow.getBrowser().setContent(unicode);
3967 thumbnailRunner.addWork("GENERATE "+ guid);
3968 saveNote(guid, browser);
3972 private void saveNote() {
3974 saveNote(currentNoteGuid, browserWindow);
3975 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
3979 private void saveNote(String guid, BrowserWindow window) {
3980 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
3981 logger.log(logger.EXTREME, "Note is dirty.");
3984 logger.log(logger.EXTREME, "Saving to cache");
3985 QTextCodec codec = QTextCodec.codecForLocale();
3986 // QTextDecoder decoder = codec.makeDecoder();
3987 codec = QTextCodec.codecForName("UTF-8");
3988 QByteArray unicode = codec.fromUnicode(window.getContent());
3989 noteCache.put(guid, unicode.toString());
3991 logger.log(logger.EXTREME, "updating list manager");
3992 listManager.updateNoteContent(guid, window.getContent());
3993 logger.log(logger.EXTREME, "Updating title");
3994 listManager.updateNoteTitle(guid, window.getTitle());
3995 updateListDateChanged();
3997 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
3998 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3999 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4000 currentNote = listManager.getNoteIndex().get(i);
4001 i = listManager.getNoteIndex().size();
4006 // Get a note from Evernote (and put it in the browser)
4007 private void refreshEvernoteNote(boolean reload) {
4008 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4010 if (Global.disableViewing) {
4011 browserWindow.setEnabled(false);
4016 if (Global.showDeleted)
4018 Global.cryptCounter =0;
4019 if (currentNoteGuid.equals("")) {
4020 browserWindow.setReadOnly(true);
4028 browserWindow.loadingData(true);
4030 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4031 if (currentNote == null)
4034 loadNoteBrowserInformation(browserWindow);
4037 private void loadNoteBrowserInformation(BrowserWindow browser) {
4038 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4039 formatter.setNote(currentNote, Global.pdfPreview());
4040 formatter.setHighlight(listManager.getEnSearch());
4042 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4043 js = new QByteArray();
4044 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4045 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4046 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>");
4047 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4048 js.append("<style> img { max-width:100%; }</style>");
4049 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4050 js.append("</head>");
4051 formatter.setNote(currentNote, Global.pdfPreview());
4052 js.append(formatter.rebuildNoteHTML());
4053 js.append("</HTML>");
4054 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4055 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4056 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4057 browser.getBrowser().setContent(js);
4058 noteCache.put(currentNoteGuid, js.toString());
4060 if (formatter.resourceError)
4061 resourceErrorMessage();
4062 readOnly = formatter.readOnly;
4063 inkNote = formatter.inkNote;
4065 readOnlyCache.put(currentNoteGuid, true);
4067 inkNoteCache.put(currentNoteGuid, true);
4069 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4070 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4071 js = new QByteArray(cachedContent);
4072 browser.getBrowser().setContent(js);
4073 if (readOnlyCache.containsKey(currentNoteGuid))
4075 if (inkNoteCache.containsKey(currentNoteGuid))
4078 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4079 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4082 if (readOnly || inkNote)
4083 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4085 browser.getBrowser().page().setContentEditable(true);
4086 browser.setReadOnly(readOnly);
4087 deleteButton.setEnabled(!readOnly);
4088 tagButton.setEnabled(!readOnly);
4089 menuBar.noteDelete.setEnabled(!readOnly);
4090 menuBar.noteTags.setEnabled(!readOnly);
4091 browser.setNote(currentNote);
4093 if (conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4094 deleteButton.setEnabled(false);
4095 menuBar.notebookDeleteAction.setEnabled(false);
4097 deleteButton.setEnabled(true);
4098 menuBar.notebookDeleteAction.setEnabled(true);
4101 // Build a list of non-closed notebooks
4102 List<Notebook> nbooks = new ArrayList<Notebook>();
4103 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4104 boolean found=false;
4105 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4106 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4110 nbooks.add(listManager.getNotebookIndex().get(i));
4113 browser.setTitle(currentNote.getTitle());
4114 browser.setTag(getTagNamesForNote(currentNote));
4115 browser.setAuthor(currentNote.getAttributes().getAuthor());
4117 browser.setAltered(currentNote.getUpdated());
4118 browser.setCreation(currentNote.getCreated());
4119 if (currentNote.getAttributes().getSubjectDate() > 0)
4120 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4122 browser.setSubjectDate(currentNote.getCreated());
4123 browser.setUrl(currentNote.getAttributes().getSourceURL());
4125 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4126 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4127 browser.setAllTags(tagList);
4129 browser.setCurrentTags(currentNote.getTagNames());
4131 scrollToGuid(currentNoteGuid);
4133 browser.loadingData(false);
4134 if (thumbnailViewer.isActiveWindow())
4137 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4138 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4141 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4143 // Save a generated thumbnail
4144 private void toggleNoteInformation() {
4145 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4146 browserWindow.toggleInformation();
4147 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4148 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4149 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4151 // Listener triggered when a print button is pressed
4152 @SuppressWarnings("unused")
4153 private void printNote() {
4154 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4156 QPrintDialog dialog = new QPrintDialog();
4157 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4158 QPrinter printer = dialog.printer();
4159 browserWindow.getBrowser().print(printer);
4161 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4164 // Listener triggered when the email button is pressed
4165 @SuppressWarnings("unused")
4166 private void emailNote() {
4167 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4169 if (Desktop.isDesktopSupported()) {
4170 Desktop desktop = Desktop.getDesktop();
4172 String text2 = browserWindow.getContentsToEmail();
4173 QUrl url = new QUrl("mailto:");
4174 url.addQueryItem("subject", currentNote.getTitle());
4175 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4176 url.addQueryItem("body", text2);
4177 QDesktopServices.openUrl(url);
4181 if (desktop.isSupported(Desktop.Action.MAIL)) {
4182 URI uriMailTo = null;
4184 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4185 String text = browserWindow.getContentsToEmail();
4186 //text = "<b>" +text +"</b>";
4187 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4188 +"&BODY=" +text, null);
4189 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4190 +"&ATTACHMENT=d:/test.pdf", null);
4191 desktop.mail(uriMailTo);
4192 } catch (URISyntaxException e) {
4193 e.printStackTrace();
4194 } catch (IOException e) {
4195 e.printStackTrace();
4202 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4204 // Reindex all notes
4205 @SuppressWarnings("unused")
4206 private void fullReindex() {
4207 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4208 indexRunner.addWork("REINDEXALL");
4209 setMessage(tr("Database will be reindexed."));
4210 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4212 // Listener when a user wants to reindex a specific note
4213 @SuppressWarnings("unused")
4214 private void reindexNote() {
4215 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4216 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4217 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4219 if (selectedNotebookGUIDs.size() > 1)
4220 setMessage(tr("Notes will be reindexed."));
4222 setMessage(tr("Note will be reindexed."));
4223 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4226 @SuppressWarnings("unused")
4227 private void deleteNote() {
4228 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4229 if (currentNote == null)
4231 if (currentNoteGuid.equals(""))
4234 // If we are deleting non-trash notes
4235 if (currentNote.isActive()) {
4236 if (Global.verifyDelete()) {
4237 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4238 QMessageBox.StandardButton.Yes,
4239 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4243 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4244 selectedNoteGUIDs.add(currentNoteGuid);
4245 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4246 listManager.deleteNote(selectedNoteGUIDs.get(i));
4249 // If we are deleting from the trash.
4250 if (Global.verifyDelete()) {
4251 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4252 QMessageBox.StandardButton.Yes,
4253 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4257 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4258 selectedNoteGUIDs.add(currentNoteGuid);
4259 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4260 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4261 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4262 if (modelIndex != null) {
4263 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4264 String tableGuid = (String)ix.values().toArray()[0];
4265 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4266 listManager.getNoteTableModel().removeRow(j);
4271 listManager.expungeNote(selectedNoteGUIDs.get(i));
4274 currentNoteGuid = "";
4275 listManager.loadNotesIndex();
4276 noteIndexUpdated(false);
4277 refreshEvernoteNote(true);
4278 scrollToGuid(currentNoteGuid);
4279 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4282 @SuppressWarnings("unused")
4283 private void addNote() {
4284 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4285 // browserWindow.setEnabled(true);
4286 browserWindow.setReadOnly(false);
4288 Calendar currentTime = new GregorianCalendar();
4289 StringBuffer noteString = new StringBuffer(100);
4290 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4291 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4294 if (Global.overrideDefaultFont()) {
4295 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4296 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4297 noteString.append("<br clear=\"none\" />\n");
4298 noteString.append("</span>\n</font>\n");
4300 noteString.append("<br clear=\"none\" />\n");
4301 noteString.append("</en-note>");
4303 Long l = new Long(currentTime.getTimeInMillis());
4304 String randint = new String(Long.toString(l));
4306 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4308 // for the first non-archived notebook. Finally, if nothing else we
4309 // pick the first notebook in the list.
4310 String notebook = null;
4311 listManager.getNotebookIndex().get(0).getGuid();
4312 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4313 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4314 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4315 notebook = currentSelectedNotebook.text(2);
4317 boolean found = false;
4318 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4319 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4320 boolean match = false;
4321 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4322 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4324 j = listManager.getArchiveNotebookIndex().size();
4328 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4330 // Now we have a list of good notebooks, so we can look for the default
4332 for (int i=0; i<goodNotebooks.size(); i++) {
4333 if (goodNotebooks.get(i).isDefaultNotebook()) {
4334 notebook = goodNotebooks.get(i).getGuid();
4336 i = goodNotebooks.size();
4340 if (goodNotebooks.size() > 0 && !found)
4341 notebook = goodNotebooks.get(0).getGuid();
4344 notebook = listManager.getNotebookIndex().get(0).getGuid();
4347 Note newNote = new Note();
4348 newNote.setUpdateSequenceNum(0);
4349 newNote.setGuid(randint);
4350 newNote.setNotebookGuid(notebook);
4351 newNote.setTitle("");
4352 newNote.setContent(noteString.toString());
4353 newNote.setDeleted(0);
4354 newNote.setCreated(System.currentTimeMillis());
4355 newNote.setUpdated(System.currentTimeMillis());
4356 newNote.setActive(true);
4357 NoteAttributes na = new NoteAttributes();
4358 na.setLatitude(0.0);
4359 na.setLongitude(0.0);
4360 na.setAltitude(0.0);
4361 newNote.setAttributes(new NoteAttributes());
4362 newNote.setTagGuids(new ArrayList<String>());
4363 newNote.setTagNames(new ArrayList<String>());
4365 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4366 if (Global.newNoteWithSelectedTags()) {
4367 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4368 QTreeWidgetItem currentSelection;
4369 for (int i=0; i<selections.size(); i++) {
4370 currentSelection = selections.get(i);
4371 newNote.getTagGuids().add(currentSelection.text(2));
4372 newNote.getTagNames().add(currentSelection.text(0));
4376 conn.getNoteTable().addNote(newNote, true);
4377 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4378 listManager.addNote(newNote);
4379 // noteTableView.insertRow(newNote, true, -1);
4381 currentNote = newNote;
4382 currentNoteGuid = currentNote.getGuid();
4383 refreshEvernoteNote(true);
4384 listManager.countNotebookResults(listManager.getNoteIndex());
4385 browserWindow.titleLabel.setFocus();
4386 browserWindow.titleLabel.selectAll();
4387 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4389 // If the window is hidden, then we want to popup this in an external window &
4392 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4394 // Restore a note from the trash;
4395 @SuppressWarnings("unused")
4396 private void restoreNote() {
4398 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4399 selectedNoteGUIDs.add(currentNoteGuid);
4400 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4401 listManager.restoreNote(selectedNoteGUIDs.get(i));
4403 currentNoteGuid = "";
4404 listManager.loadNotesIndex();
4405 noteIndexUpdated(false);
4408 // Search a note for specific txt
4409 @SuppressWarnings("unused")
4410 private void findText() {
4412 find.setFocusOnTextField();
4414 @SuppressWarnings("unused")
4415 private void doFindText() {
4416 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4419 @SuppressWarnings("unused")
4420 private void updateNoteTitle(String guid, String title) {
4421 listManager.setNoteSynchronized(guid, false);
4423 // Signal received that note content has changed. Normally we just need the guid to remove
4424 // it from the cache.
4425 @SuppressWarnings("unused")
4426 private void invalidateNoteCache(String guid, String content) {
4427 String v = noteCache.remove(guid);
4428 // if (guid.equals(currentNoteGuid) && !noteDirty)
4429 refreshEvernoteNote(true);
4431 // Signal received that a note guid has changed
4432 @SuppressWarnings("unused")
4433 private void noteGuidChanged(String oldGuid, String newGuid) {
4434 if (noteCache.containsKey(oldGuid)) {
4435 if (!oldGuid.equals(currentNoteGuid)) {
4436 String cache = noteCache.get(oldGuid);
4437 noteCache.put(newGuid, cache);
4438 noteCache.remove(oldGuid);
4440 noteCache.remove(oldGuid);
4441 noteCache.put(newGuid, browserWindow.getContent());
4445 listManager.updateNoteGuid(oldGuid, newGuid, false);
4446 if (currentNoteGuid.equals(oldGuid)) {
4447 if (currentNote != null)
4448 currentNote.setGuid(newGuid);
4449 currentNoteGuid = newGuid;
4452 if (externalWindows.containsKey(oldGuid)) {
4453 ExternalBrowse b = externalWindows.get(oldGuid);
4454 externalWindows.remove(oldGuid);
4455 b.getBrowserWindow().getNote().setGuid(newGuid);
4456 externalWindows.put(newGuid, b);
4459 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4460 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4461 noteTableView.proxyModel.addGuid(newGuid);
4462 i=listManager.getNoteIndex().size();
4466 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4467 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4468 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4469 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4473 // Toggle the note editor button bar
4474 private void toggleEditorButtonBar() {
4475 if (browserWindow.buttonsVisible) {
4476 browserWindow.hideButtons();
4477 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4478 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4480 browserWindow.buttonsVisible = true;
4481 showEditorButtons(browserWindow);
4483 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4485 // Show editor buttons
4486 private void showEditorButtons(BrowserWindow browser) {
4487 browser.buttonLayout.setVisible(true);
4488 browser.undoAction.setVisible(false);
4490 browser.undoButton.setVisible(false);
4492 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4493 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4494 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4495 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4496 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4497 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4498 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4499 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4500 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4501 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4502 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4503 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4504 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4505 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4506 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4507 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4508 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4509 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4510 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4511 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4512 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4513 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4514 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4516 private void duplicateNote(String guid) {
4518 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
4519 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4520 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4521 oldNote.setResources(resList);
4522 duplicateNote(oldNote);
4524 private void duplicateNote(Note oldNote) {
4526 // Now that we have a good notebook guid, we need to move the conflicting note
4527 // to the local notebook
4528 Calendar currentTime = new GregorianCalendar();
4529 Long l = new Long(currentTime.getTimeInMillis());
4530 String newGuid = new String(Long.toString(l));
4532 Note newNote = oldNote.deepCopy();
4533 newNote.setUpdateSequenceNum(0);
4534 newNote.setGuid(newGuid);
4535 newNote.setDeleted(0);
4536 newNote.setActive(true);
4537 List<Resource> resList = oldNote.getResources();
4538 if (resList == null)
4539 resList = new ArrayList<Resource>();
4541 for (int i=0; i<resList.size(); i++) {
4543 while (l == prevGuid) {
4544 currentTime = new GregorianCalendar();
4545 l = new Long(currentTime.getTimeInMillis());
4548 String newResGuid = new String(Long.toString(l));
4549 resList.get(i).setNoteGuid(newGuid);
4550 resList.get(i).setGuid(newResGuid);
4551 resList.get(i).setUpdateSequenceNum(0);
4552 resList.get(i).setActive(true);
4553 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
4555 newNote.setResources(resList);
4556 listManager.addNote(newNote);
4557 conn.getNoteTable().addNote(newNote, true);
4558 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4559 noteTableView.insertRow(newNote, true, -1);
4560 listManager.countNotebookResults(listManager.getNoteIndex());
4564 @SuppressWarnings("unused")
4565 private void allNotes() {
4566 clearAttributeFilter();
4567 clearNotebookFilter();
4568 clearSavedSearchFilter();
4571 searchField.clear();
4572 if (Global.mimicEvernoteInterface) {
4573 notebookTree.selectGuid("");
4575 notebookTreeSelection();
4578 @SuppressWarnings("unused")
4579 private void mergeNotes() {
4580 logger.log(logger.HIGH, "Merging notes");
4583 String masterGuid = null;
4584 List<String> sources = new ArrayList<String>();
4586 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4587 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4588 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4589 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4591 masterGuid = (String)ix.values().toArray()[0];
4593 sources.add((String)ix.values().toArray()[0]);
4596 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4597 logger.log(logger.EXTREME, "Children count: "+sources.size());
4598 mergeNoteContents(masterGuid, sources);
4599 currentNoteGuid = masterGuid;
4600 noteIndexUpdated(false);
4601 refreshEvernoteNote(true);
4604 private void mergeNoteContents(String targetGuid, List<String> sources) {
4605 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4606 String newContent = target.getContent();
4607 newContent = newContent.replace("</en-note>", "<br></br>");
4609 for (int i=0; i<sources.size(); i++) {
4610 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4611 if (source.isSetTitle()) {
4612 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4614 String sourceContent = source.getContent();
4615 logger.log(logger.EXTREME, "Merging contents into note");
4616 logger.log(logger.EXTREME, sourceContent);
4617 logger.log(logger.EXTREME, "End of content");
4618 int startOfNote = sourceContent.indexOf("<en-note>");
4619 sourceContent = sourceContent.substring(startOfNote+9);
4620 int endOfNote = sourceContent.indexOf("</en-note>");
4621 sourceContent = sourceContent.substring(0,endOfNote);
4622 newContent = newContent + sourceContent;
4623 logger.log(logger.EXTREME, "New note content");
4624 logger.log(logger.EXTREME, newContent);
4625 logger.log(logger.EXTREME, "End of content");
4626 for (int j=0; j<source.getResourcesSize(); j++) {
4627 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4628 Resource r = source.getResources().get(j);
4629 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4631 Calendar currentTime = new GregorianCalendar();
4632 Long l = new Long(currentTime.getTimeInMillis());
4636 while (l == prevGuid) {
4637 currentTime = new GregorianCalendar();
4638 l = new Long(currentTime.getTimeInMillis());
4640 String newResGuid = new String(Long.toString(l));
4641 newRes.setNoteGuid(targetGuid);
4642 newRes.setGuid(newResGuid);
4643 newRes.setUpdateSequenceNum(0);
4644 newRes.setActive(true);
4645 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4648 logger.log(logger.EXTREME, "Updating note");
4649 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4650 for (int i=0; i<sources.size(); i++) {
4651 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4652 listManager.deleteNote(sources.get(i));
4654 logger.log(logger.EXTREME, "Exiting merge note");
4656 // A resource within a note has had a guid change
4657 @SuppressWarnings("unused")
4658 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4659 if (!oldGuid.equals(newGuid))
4660 Global.resourceMap.put(oldGuid, newGuid);
4662 // View a thumbnail of the note
4663 public void thumbnailView() {
4665 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4666 QFile thumbnail = new QFile(thumbnailName);
4667 if (!thumbnail.exists()) {
4669 QImage img = new QImage();
4670 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4671 thumbnailViewer.setThumbnail(img);
4673 thumbnailViewer.setThumbnail(thumbnailName);
4674 if (!thumbnailViewer.isVisible())
4675 thumbnailViewer.showFullScreen();
4677 // An error happened while saving a note. Inform the user
4678 @SuppressWarnings("unused")
4679 private void saveRunnerError(String guid, String msg) {
4681 String title = "*Unknown*";
4682 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4683 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4684 title = listManager.getMasterNoteIndex().get(i).getTitle();
4685 i=listManager.getMasterNoteIndex().size();
4688 msg = "An error has happened while saving the note \"" +title+
4689 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4690 "As a result, changes to the note may not be saved properly in the database."+
4691 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4692 "\nbe lost. Please review the note to recover any critical data before restarting.";
4694 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4697 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4698 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4699 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4700 // Find an idle preview object
4701 for (int i=0; i<thumbGenerators.size(); i++) {
4702 if (thumbGenerators.get(i).mutex.tryLock()) {
4703 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4704 thumbGenerators.get(i).loadContent(guid, html, zoom);
4708 if (thumbGenerators.size() >= 1) {
4709 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4713 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4714 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4715 thumbGenerators.add(preview);
4717 if (preview.mutex.tryLock()) {
4718 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4719 preview.loadContent(guid, html, zoom);
4721 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4726 //**********************************************************
4727 //**********************************************************
4728 //* Online user actions
4729 //**********************************************************
4730 //**********************************************************
4731 private void setupOnlineMenu() {
4732 if (!Global.isConnected) {
4733 menuBar.noteOnlineHistoryAction.setEnabled(false);
4734 menuBar.selectiveSyncAction.setEnabled(false);
4737 menuBar.noteOnlineHistoryAction.setEnabled(true);
4738 menuBar.selectiveSyncAction.setEnabled(true);
4741 @SuppressWarnings("unused")
4742 private void viewNoteHistory() {
4743 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4745 if (currentNote.getUpdateSequenceNum() == 0) {
4746 setMessage(tr("Note has never been synchronized."));
4747 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4751 setMessage(tr("Getting Note History"));
4753 Note currentOnlineNote = null;
4756 if (Global.isPremium())
4757 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4759 versions = new ArrayList<NoteVersionId>();
4760 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4761 } catch (EDAMUserException e) {
4762 setMessage("EDAMUserException: " +e.getMessage());
4764 } catch (EDAMSystemException e) {
4765 setMessage("EDAMSystemException: " +e.getMessage());
4767 } catch (EDAMNotFoundException e) {
4768 setMessage(tr("Note not found on server."));
4769 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4771 } catch (TException e) {
4772 setMessage("EDAMTransactionException: " +e.getMessage());
4776 // If we've gotten this far, we have a good note.
4777 if (historyWindow == null) {
4778 historyWindow = new OnlineNoteHistory(logger, conn);
4779 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4780 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4781 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4783 historyWindow.historyCombo.clear();
4785 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4786 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4788 historyWindow.setCurrent(isDirty);
4790 loadHistoryWindowContent(currentOnlineNote);
4791 historyWindow.load(versions);
4792 setMessage(tr("History retrieved"));
4794 historyWindow.exec();
4796 private Note reloadHistoryWindow(String selection) {
4798 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4799 String dateTimeFormat = new String(fmt);
4800 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4804 for (int i=0; i<versions.size(); i++) {
4805 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4806 if (versionDate.toString().equals(selection))
4810 if (index > -1 || selection.indexOf("Current") > -1) {
4811 Note historyNote = null;
4814 usn = versions.get(index).getUpdateSequenceNum();
4815 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4817 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4818 } catch (EDAMUserException e) {
4819 setMessage("EDAMUserException: " +e.getMessage());
4822 } catch (EDAMSystemException e) {
4823 setMessage("EDAMSystemException: " +e.getMessage());
4826 } catch (EDAMNotFoundException e) {
4827 setMessage("EDAMNotFoundException: " +e.getMessage());
4830 } catch (TException e) {
4831 setMessage("EDAMTransactionException: " +e.getMessage());
4837 if (historyNote != null)
4838 historyWindow.setContent(historyNote);
4844 private void loadHistoryWindowContent(Note note) {
4845 note.setUpdateSequenceNum(0);
4846 historyWindow.setContent(note);
4848 @SuppressWarnings("unused")
4849 private void restoreHistoryNoteAsNew() {
4850 setMessage(tr("Restoring as new note."));
4851 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4852 setMessage(tr("Note has been restored as a new note."));
4854 @SuppressWarnings("unused")
4855 private void restoreHistoryNote() {
4856 setMessage(tr("Restoring note."));
4857 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
4858 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
4861 for (int i=0; i<n.getResourcesSize(); i++) {
4862 n.getResources().get(i).setActive(true);
4863 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
4865 listManager.addNote(n);
4866 conn.getNoteTable().addNote(n, true);
4867 refreshEvernoteNote(true);
4868 setMessage(tr("Note has been restored."));
4870 @SuppressWarnings("unused")
4871 private void setupSelectiveSync() {
4873 // Get a list of valid notebooks
4874 List<Notebook> notebooks = null;
4875 List<Tag> tags = null;
4877 notebooks = syncRunner.noteStore.listNotebooks(syncRunner.authToken);
4878 tags = syncRunner.noteStore.listTags(syncRunner.authToken);
4879 } catch (EDAMUserException e) {
4880 setMessage("EDAMUserException: " +e.getMessage());
4882 } catch (EDAMSystemException e) {
4883 setMessage("EDAMSystemException: " +e.getMessage());
4885 } catch (TException e) {
4886 setMessage("EDAMTransactionException: " +e.getMessage());
4890 // Split up notebooks into synchronized & non-synchronized
4891 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
4892 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4894 for (int i=notebooks.size()-1; i>=0; i--) {
4895 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
4896 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
4897 ignoredBooks.add(notebooks.get(i));
4898 j=dbIgnoredNotebooks.size();
4903 // split up tags into synchronized & non-synchronized
4904 List<Tag> ignoredTags = new ArrayList<Tag>();
4905 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
4907 for (int i=tags.size()-1; i>=0; i--) {
4908 for (int j=0; j<dbIgnoredTags.size(); j++) {
4909 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
4910 ignoredTags.add(tags.get(i));
4911 j=dbIgnoredTags.size();
4916 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags);
4918 if (!ignore.okClicked())
4923 // Clear out old notebooks & add the new ones
4924 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4925 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
4926 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
4929 List<String> newNotebooks = new ArrayList<String>();
4930 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
4931 String text = ignore.getIgnoredBookList().takeItem(i).text();
4932 for (int j=0; j<notebooks.size(); j++) {
4933 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
4934 Notebook n = notebooks.get(j);
4935 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
4937 newNotebooks.add(n.getGuid());
4942 // Clear out old tags & add new ones
4943 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
4944 for (int i=0; i<oldIgnoreTags.size(); i++) {
4945 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
4948 List<String> newTags = new ArrayList<String>();
4949 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
4950 String text = ignore.getIgnoredTagList().takeItem(i).text();
4951 for (int j=0; j<tags.size(); j++) {
4952 if (tags.get(j).getName().equalsIgnoreCase(text)) {
4953 Tag t = tags.get(j);
4954 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
4955 newTags.add(t.getGuid());
4961 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags);
4967 //**********************************************************
4968 //**********************************************************
4969 //* XML Modifying methods
4970 //**********************************************************
4971 //**********************************************************
4972 // An error has happended fetching a resource. let the user know
4973 private void resourceErrorMessage() {
4976 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4977 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4978 "In a perfect world this wouldn't happen, but it has.\n" +
4979 "It is embarasing when a program like me, designed to save all your\n"+
4980 "precious data, has a problem finding data.\n\n" +
4981 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
4982 "In the mean time, I'm not going to let you make changes to this note.\n" +
4983 "Don't get angry. I'm doing it to prevent you from messing up\n"+
4984 "this note on the Evernote servers. Sorry."+
4985 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4987 browserWindow.setReadOnly(true);
4993 //**********************************************************
4994 //**********************************************************
4996 //**********************************************************
4997 //**********************************************************
4998 // We should now do a sync with Evernote
4999 private void syncTimer() {
5000 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5001 syncRunner.syncNeeded = true;
5002 syncRunner.disableUploads = Global.disableUploads;
5004 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5006 private void syncStart() {
5007 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5009 if (!syncRunning && Global.isConnected) {
5010 syncRunner.setConnected(true);
5011 syncRunner.setKeepRunning(Global.keepRunning);
5012 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5014 if (syncThreadsReady > 0) {
5015 indexRunner.interrupt = true;
5016 saveNoteIndexWidth();
5017 saveNoteColumnPositions();
5018 if (syncRunner.addWork("SYNC")) {
5020 syncRunner.syncNeeded = true;
5025 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5027 @SuppressWarnings("unused")
5028 private void syncThreadComplete(Boolean refreshNeeded) {
5029 setMessage(tr("Finalizing Synchronization"));
5031 syncRunning = false;
5032 syncRunner.syncNeeded = false;
5033 synchronizeAnimationTimer.stop();
5034 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5036 if (currentNote == null) {
5037 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5039 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5040 noteIndexUpdated(false);
5041 noteTableView.selectionModel().blockSignals(true);
5042 scrollToGuid(currentNoteGuid);
5043 noteTableView.selectionModel().blockSignals(false);
5044 refreshEvernoteNote(false);
5045 scrollToGuid(currentNoteGuid);
5047 if (!syncRunner.error)
5048 setMessage(tr("Synchronization Complete"));
5050 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5051 logger.log(logger.MEDIUM, "Sync complete.");
5053 public void saveUploadAmount(long t) {
5054 Global.saveUploadAmount(t);
5056 public void saveUserInformation(User user) {
5057 Global.saveUserInformation(user);
5059 public void saveEvernoteUpdateCount(int i) {
5060 Global.saveEvernoteUpdateCount(i);
5062 public void refreshLists() {
5063 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5065 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5066 tagIndexUpdated(true);
5067 notebookIndexUpdated();
5068 savedSearchIndexUpdated();
5069 listManager.loadNotesIndex();
5071 noteTableView.selectionModel().blockSignals(true);
5072 noteIndexUpdated(true);
5073 noteTableView.selectionModel().blockSignals(false);
5074 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5078 @SuppressWarnings("unused")
5079 private void authTimer() {
5080 Calendar cal = Calendar.getInstance();
5082 // If we are not connected let's get out of here
5083 if (!Global.isConnected)
5086 // If this is the first time through, then we need to set this
5087 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5088 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5090 // long now = new Date().getTime();
5091 // if (now > Global.authRefreshTime && Global.isConnected) {
5092 syncRunner.authRefreshNeeded = true;
5096 @SuppressWarnings("unused")
5097 private void authRefreshComplete(boolean goodSync) {
5098 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5099 Global.isConnected = syncRunner.isConnected;
5101 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5102 authTimer.start(1000*60*15);
5103 logger.log(logger.LOW, "Authentication token has been renewed");
5104 // setMessage("Authentication token has been renewed.");
5106 authTimer.start(1000*60*5);
5107 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5108 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5110 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5114 @SuppressWarnings("unused")
5115 private synchronized void indexTimer() {
5116 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5119 if (!indexDisabled && indexRunner.idle) {
5120 indexRunner.addWork("SCAN");
5122 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5125 @SuppressWarnings("unused")
5126 private void indexStarted() {
5127 setMessage(tr("Indexing notes"));
5129 @SuppressWarnings("unused")
5130 private void indexComplete() {
5131 setMessage(tr("Index complete"));
5133 @SuppressWarnings("unused")
5134 private synchronized void toggleNoteIndexing() {
5135 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5136 indexDisabled = !indexDisabled;
5138 setMessage(tr("Indexing is now enabled."));
5140 setMessage(tr("Indexing is now disabled."));
5141 menuBar.disableIndexing.setChecked(indexDisabled);
5142 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5145 @SuppressWarnings("unused")
5146 private void threadMonitorCheck() {
5151 alive = listManager.threadCheck(Global.tagCounterThreadId);
5154 if (tagDeadCount > MAX)
5155 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5156 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5160 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5162 notebookThreadDeadCount++;
5163 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5164 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5166 notebookThreadDeadCount=0;
5168 alive = listManager.threadCheck(Global.trashCounterThreadId);
5171 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5172 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5176 alive = listManager.threadCheck(Global.saveThreadId);
5178 saveThreadDeadCount++;
5179 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5180 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5182 saveThreadDeadCount=0;
5184 if (!syncThread.isAlive()) {
5185 syncThreadDeadCount++;
5186 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5187 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5189 syncThreadDeadCount=0;
5191 if (!indexThread.isAlive()) {
5192 indexThreadDeadCount++;
5193 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5194 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5196 indexThreadDeadCount=0;
5201 private void thumbnailTimer() {
5202 if (Global.enableThumbnails() && conn.getNoteTable().getThumbnailNeededCount() > 1) {
5203 thumbnailTimer.setInterval(10*1000);
5204 thumbnailRunner.addWork("SCAN");
5206 thumbnailTimer.setInterval(60*1000);
5210 //**************************************************
5211 //* Backup & Restore
5212 //**************************************************
5213 @SuppressWarnings("unused")
5214 private void databaseBackup() {
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("Backing up database"));
5230 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5232 ExportData noteWriter = new ExportData(conn, true);
5233 String fileName = fd.selectedFiles().get(0);
5235 if (!fileName.endsWith(".nnex"))
5236 fileName = fileName +".nnex";
5237 noteWriter.exportData(fileName);
5238 setMessage(tr("Database backup completed."));
5243 @SuppressWarnings("unused")
5244 private void databaseRestore() {
5245 if (QMessageBox.question(this, tr("Confirmation"),
5246 tr("This is used to restore a database from backups.\n" +
5247 "It is HIGHLY recommened that this only be used to populate\n" +
5248 "an empty database. Restoring into a database that\n already has data" +
5249 " can cause problems.\n\nAre you sure you want to continue?"),
5250 QMessageBox.StandardButton.Yes,
5251 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5256 QFileDialog fd = new QFileDialog(this);
5257 fd.setFileMode(FileMode.ExistingFile);
5258 fd.setConfirmOverwrite(true);
5259 fd.setWindowTitle(tr("Restore Database"));
5260 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5261 fd.setAcceptMode(AcceptMode.AcceptOpen);
5262 fd.setDirectory(System.getProperty("user.home"));
5263 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5269 setMessage(tr("Restoring database"));
5270 ImportData noteReader = new ImportData(conn, true);
5271 noteReader.importData(fd.selectedFiles().get(0));
5273 if (noteReader.lastError != 0) {
5274 setMessage(noteReader.getErrorMessage());
5275 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5280 listManager.loadNoteTitleColors();
5282 refreshEvernoteNote(true);
5283 setMessage(tr("Database has been restored."));
5286 @SuppressWarnings("unused")
5287 private void exportNotes() {
5288 QFileDialog fd = new QFileDialog(this);
5289 fd.setFileMode(FileMode.AnyFile);
5290 fd.setConfirmOverwrite(true);
5291 fd.setWindowTitle(tr("Backup Database"));
5292 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5293 fd.setAcceptMode(AcceptMode.AcceptSave);
5294 fd.setDirectory(System.getProperty("user.home"));
5295 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5301 setMessage(tr("Exporting Notes"));
5304 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5305 selectedNoteGUIDs.add(currentNoteGuid);
5307 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5308 String fileName = fd.selectedFiles().get(0);
5310 if (!fileName.endsWith(".nnex"))
5311 fileName = fileName +".nnex";
5312 noteWriter.exportData(fileName);
5313 setMessage(tr("Export completed."));
5319 @SuppressWarnings("unused")
5320 private void importNotes() {
5321 QFileDialog fd = new QFileDialog(this);
5322 fd.setFileMode(FileMode.ExistingFile);
5323 fd.setConfirmOverwrite(true);
5324 fd.setWindowTitle(tr("Import Notes"));
5325 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5326 fd.setAcceptMode(AcceptMode.AcceptOpen);
5327 fd.setDirectory(System.getProperty("user.home"));
5328 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5334 setMessage("Importing Notes");
5337 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5338 selectedNoteGUIDs.add(currentNoteGuid);
5340 ImportData noteReader = new ImportData(conn, false);
5341 String fileName = fd.selectedFiles().get(0);
5343 if (!fileName.endsWith(".nnex"))
5344 fileName = fileName +".nnex";
5345 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5346 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5348 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5350 noteReader.importData(fileName);
5352 if (noteReader.lastError != 0) {
5353 setMessage(noteReader.getErrorMessage());
5354 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5359 listManager.loadNoteTitleColors();
5361 refreshEvernoteNote(false);
5362 setMessage(tr("Notes have been imported."));
5365 setMessage("Import completed.");
5372 //**************************************************
5373 //* Duplicate a note
5374 //**************************************************
5375 @SuppressWarnings("unused")
5376 private void duplicateNote() {
5378 duplicateNote(currentNoteGuid);
5383 //**************************************************
5385 //**************************************************
5386 public void setupFolderImports() {
5387 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5389 if (importKeepWatcher == null)
5390 importKeepWatcher = new QFileSystemWatcher();
5391 if (importDeleteWatcher == null) {
5392 importDeleteWatcher = new QFileSystemWatcher();
5393 for (int i=0; i<records.size(); i++) {
5394 if (!records.get(i).keep)
5395 folderImportDelete(records.get(i).folder);
5401 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5402 for (int i=0; i<records.size(); i++) {
5403 if (records.get(i).keep)
5404 importKeepWatcher.addPath(records.get(i).folder);
5406 importDeleteWatcher.addPath(records.get(i).folder);
5409 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5410 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5412 // Look at the files already there so we don't import them again if a new file is created
5413 if (importedFiles == null) {
5414 importedFiles = new ArrayList<String>();
5415 for (int j=0; j<records.size(); j++) {
5416 QDir dir = new QDir(records.get(j).folder);
5417 List<QFileInfo> list = dir.entryInfoList();
5418 for (int k=0; k<list.size(); k++) {
5419 if (list.get(k).isFile())
5420 importedFiles.add(list.get(k).absoluteFilePath());
5425 public void folderImport() {
5426 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5427 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5429 if (!dialog.okClicked())
5432 // We have some sort of update.
5433 if (importKeepWatcher.directories().size() > 0)
5434 importKeepWatcher.removePaths(importKeepWatcher.directories());
5435 if (importDeleteWatcher.directories().size() > 0)
5436 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5438 conn.getWatchFolderTable().expungeAll();
5439 // Start building from the table
5440 for (int i=0; i<dialog.table.rowCount(); i++) {
5441 QTableWidgetItem item = dialog.table.item(i, 0);
5442 String dir = item.text();
5443 item = dialog.table.item(i, 1);
5444 String notebook = item.text();
5445 item = dialog.table.item(i, 2);
5447 if (item.text().equalsIgnoreCase("Keep"))
5452 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5453 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5455 setupFolderImports();
5458 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5460 String whichOS = System.getProperty("os.name");
5461 if (whichOS.contains("Windows"))
5462 dirName = dirName.replace('/','\\');
5464 FileImporter importer = new FileImporter(logger, conn);
5466 QDir dir = new QDir(dirName);
5467 List<QFileInfo> list = dir.entryInfoList();
5468 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5470 for (int i=0; i<list.size(); i++){
5472 boolean redundant = false;
5473 // Check if we've already imported this one or if it existed before
5474 for (int j=0; j<importedFiles.size(); j++) {
5475 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5480 importer.setFileInfo(list.get(i));
5481 importer.setFileName(list.get(i).absoluteFilePath());
5484 if (list.get(i).isFile() && importer.isValidType()) {
5486 if (!importer.importFile()) {
5487 // If we can't get to the file, it is probably locked. We'll try again later.
5488 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5489 importFilesKeep.add(list.get(i).absoluteFilePath());
5493 Note newNote = importer.getNote();
5494 newNote.setNotebookGuid(notebook);
5495 newNote.setTitle(dir.at(i));
5496 listManager.addNote(newNote);
5497 conn.getNoteTable().addNote(newNote, true);
5498 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5499 noteTableView.insertRow(newNote, true, -1);
5500 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5501 listManager.countNotebookResults(listManager.getNoteIndex());
5502 importedFiles.add(list.get(i).absoluteFilePath());
5510 public void folderImportDelete(String dirName) {
5512 String whichOS = System.getProperty("os.name");
5513 if (whichOS.contains("Windows"))
5514 dirName = dirName.replace('/','\\');
5516 FileImporter importer = new FileImporter(logger, conn);
5517 QDir dir = new QDir(dirName);
5518 List<QFileInfo> list = dir.entryInfoList();
5519 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5521 for (int i=0; i<list.size(); i++){
5522 importer.setFileInfo(list.get(i));
5523 importer.setFileName(list.get(i).absoluteFilePath());
5525 if (list.get(i).isFile() && importer.isValidType()) {
5527 if (!importer.importFile()) {
5528 // If we can't get to the file, it is probably locked. We'll try again later.
5529 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5530 importFilesKeep.add(list.get(i).absoluteFilePath());
5534 Note newNote = importer.getNote();
5535 newNote.setNotebookGuid(notebook);
5536 newNote.setTitle(dir.at(i));
5537 listManager.addNote(newNote);
5538 conn.getNoteTable().addNote(newNote, true);
5539 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5540 noteTableView.insertRow(newNote, true, -1);
5541 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5542 listManager.countNotebookResults(listManager.getNoteIndex());
5543 dir.remove(dir.at(i));
5549 //**************************************************
5551 //**************************************************
5552 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5553 logger.log(logger.HIGH, "Entering exernalFileEdited");
5555 // Strip URL prefix and base dir path
5556 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5557 String name = fileName.replace(dPath, "");
5558 int pos = name.lastIndexOf('.');
5561 guid = guid.substring(0,pos);
5563 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5565 guid = name.substring(0, pos);
5568 QFile file = new QFile(fileName);
5569 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5570 // If we can't get to the file, it is probably locked. We'll try again later.
5571 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5572 externalFiles.add(fileName);
5575 QByteArray binData = file.readAll();
5577 if (binData.size() == 0) {
5578 // If we can't get to the file, it is probably locked. We'll try again later.
5579 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5580 externalFiles.add(fileName);
5584 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5586 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5587 if (r == null || r.getData() == null || r.getData().getBody() == null)
5589 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5590 MessageDigest md = MessageDigest.getInstance("MD5");
5591 md.update(binData.toByteArray());
5592 byte[] hash = md.digest();
5593 String newHash = Global.byteArrayToHexString(hash);
5594 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5595 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5597 if (externalWindows.containsKey(r.getNoteGuid())) {
5598 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5599 r.getGuid(), oldHash, newHash);
5601 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5602 Data data = r.getData();
5603 data.setBody(binData.toByteArray());
5604 data.setBodyHash(hash);
5605 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5607 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5609 if (r.getNoteGuid().equals(currentNoteGuid)) {
5610 QWebSettings.setMaximumPagesInCache(0);
5611 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5612 refreshEvernoteNote(true);
5613 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5616 if (externalWindows.containsKey(r.getNoteGuid())) {
5617 QWebSettings.setMaximumPagesInCache(0);
5618 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5619 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5623 logger.log(logger.HIGH, "Exiting externalFielEdited");
5625 // This is a timer event that tries to save any external files that were edited. This
5626 // is only needed if we couldn't save a file earlier.
5627 public void externalFileEditedSaver() {
5628 for (int i=externalFiles.size()-1; i>=0; i--) {
5630 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5631 externalFileEdited(externalFiles.get(i));
5632 externalFiles.remove(i);
5633 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5635 for (int i=0; i<importFilesKeep.size(); i++) {
5637 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5638 folderImportKeep(importFilesKeep.get(i));
5639 importFilesKeep.remove(i);
5640 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5642 for (int i=0; i<importFilesDelete.size(); i++) {
5643 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5644 folderImportDelete(importFilesDelete.get(i));
5645 importFilesDelete.remove(i);
5652 // If an attachment on the current note was edited, we need to update the current notes's hash
5653 // Update a note content's hash. This happens if a resource is edited outside of NN
5654 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5655 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5657 for (;position>-1;) {
5658 endPos = browser.getContent().indexOf(">", position+1);
5659 String oldSegment = browser.getContent().substring(position,endPos);
5660 int hashPos = oldSegment.indexOf("hash=\"");
5661 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5662 String hash = oldSegment.substring(hashPos+6, hashEnd);
5663 if (hash.equalsIgnoreCase(oldHash)) {
5664 String newSegment = oldSegment.replace(oldHash, newHash);
5665 String content = browser.getContent().substring(0,position) +
5667 browser.getContent().substring(endPos);
5668 browser.getBrowser().setContent(new QByteArray(content));;
5671 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5676 //*************************************************
5677 //* Minimize to tray
5678 //*************************************************
5680 public void changeEvent(QEvent e) {
5681 if (e.type() == QEvent.Type.WindowStateChange) {
5682 if (isMinimized() && Global.showTrayIcon()) {
5684 QTimer.singleShot(10, this, "hide()");
5688 windowMaximized = true;
5690 windowMaximized = false;
5694 //*************************************************
5695 //* Check database userid & passwords
5696 //*************************************************
5697 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5698 Connection connection;
5701 Class.forName("org.h2.Driver");
5702 } catch (ClassNotFoundException e1) {
5703 e1.printStackTrace();
5708 String passwordString = null;
5709 if (cypherPassword==null || cypherPassword.trim().equals(""))
5710 passwordString = userPassword;
5712 passwordString = cypherPassword+" "+userPassword;
5713 connection = DriverManager.getConnection(url,userid,passwordString);
5714 } catch (SQLException e) {
5719 } catch (SQLException e) {
5720 e.printStackTrace();