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.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
26 import java.sql.Connection;
27 import java.sql.DriverManager;
28 import java.sql.SQLException;
29 import java.sql.Statement;
30 import java.text.SimpleDateFormat;
31 import java.util.ArrayList;
32 import java.util.Calendar;
33 import java.util.Collections;
34 import java.util.Comparator;
35 import java.util.Date;
36 import java.util.GregorianCalendar;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.SortedMap;
40 import java.util.Vector;
42 import org.apache.thrift.TException;
43 import org.h2.tools.ChangeFileEncryption;
45 import com.evernote.edam.error.EDAMNotFoundException;
46 import com.evernote.edam.error.EDAMSystemException;
47 import com.evernote.edam.error.EDAMUserException;
48 import com.evernote.edam.notestore.NoteFilter;
49 import com.evernote.edam.notestore.NoteVersionId;
50 import com.evernote.edam.type.Data;
51 import com.evernote.edam.type.Note;
52 import com.evernote.edam.type.NoteAttributes;
53 import com.evernote.edam.type.Notebook;
54 import com.evernote.edam.type.QueryFormat;
55 import com.evernote.edam.type.Resource;
56 import com.evernote.edam.type.SavedSearch;
57 import com.evernote.edam.type.Tag;
58 import com.evernote.edam.type.User;
59 import com.trolltech.qt.QThread;
60 import com.trolltech.qt.core.QByteArray;
61 import com.trolltech.qt.core.QDataStream;
62 import com.trolltech.qt.core.QDateTime;
63 import com.trolltech.qt.core.QDir;
64 import com.trolltech.qt.core.QEvent;
65 import com.trolltech.qt.core.QFile;
66 import com.trolltech.qt.core.QFileInfo;
67 import com.trolltech.qt.core.QFileSystemWatcher;
68 import com.trolltech.qt.core.QIODevice;
69 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
70 import com.trolltech.qt.core.QLocale;
71 import com.trolltech.qt.core.QModelIndex;
72 import com.trolltech.qt.core.QSize;
73 import com.trolltech.qt.core.QTemporaryFile;
74 import com.trolltech.qt.core.QTextCodec;
75 import com.trolltech.qt.core.QThreadPool;
76 import com.trolltech.qt.core.QTimer;
77 import com.trolltech.qt.core.QTranslator;
78 import com.trolltech.qt.core.QUrl;
79 import com.trolltech.qt.core.Qt;
80 import com.trolltech.qt.core.Qt.ItemDataRole;
81 import com.trolltech.qt.core.Qt.SortOrder;
82 import com.trolltech.qt.core.Qt.WidgetAttribute;
83 import com.trolltech.qt.gui.QAbstractItemView;
84 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
85 import com.trolltech.qt.gui.QAction;
86 import com.trolltech.qt.gui.QApplication;
87 import com.trolltech.qt.gui.QCloseEvent;
88 import com.trolltech.qt.gui.QColor;
89 import com.trolltech.qt.gui.QComboBox;
90 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
91 import com.trolltech.qt.gui.QDesktopServices;
92 import com.trolltech.qt.gui.QDialog;
93 import com.trolltech.qt.gui.QFileDialog;
94 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
95 import com.trolltech.qt.gui.QFileDialog.FileMode;
96 import com.trolltech.qt.gui.QGridLayout;
97 import com.trolltech.qt.gui.QHBoxLayout;
98 import com.trolltech.qt.gui.QIcon;
99 import com.trolltech.qt.gui.QImage;
100 import com.trolltech.qt.gui.QLabel;
101 import com.trolltech.qt.gui.QListWidget;
102 import com.trolltech.qt.gui.QMainWindow;
103 import com.trolltech.qt.gui.QMenu;
104 import com.trolltech.qt.gui.QMessageBox;
105 import com.trolltech.qt.gui.QMessageBox.StandardButton;
106 import com.trolltech.qt.gui.QPixmap;
107 import com.trolltech.qt.gui.QPrintDialog;
108 import com.trolltech.qt.gui.QPrinter;
109 import com.trolltech.qt.gui.QProgressBar;
110 import com.trolltech.qt.gui.QSizePolicy;
111 import com.trolltech.qt.gui.QSizePolicy.Policy;
112 import com.trolltech.qt.gui.QSpinBox;
113 import com.trolltech.qt.gui.QSplashScreen;
114 import com.trolltech.qt.gui.QSplitter;
115 import com.trolltech.qt.gui.QStatusBar;
116 import com.trolltech.qt.gui.QSystemTrayIcon;
117 import com.trolltech.qt.gui.QTableWidgetItem;
118 import com.trolltech.qt.gui.QTextEdit;
119 import com.trolltech.qt.gui.QToolBar;
120 import com.trolltech.qt.gui.QTreeWidgetItem;
121 import com.trolltech.qt.webkit.QWebPage.WebAction;
122 import com.trolltech.qt.webkit.QWebSettings;
123 import com.trolltech.qt.xml.QDomAttr;
124 import com.trolltech.qt.xml.QDomDocument;
125 import com.trolltech.qt.xml.QDomElement;
126 import com.trolltech.qt.xml.QDomNodeList;
128 import cx.fbn.nevernote.config.FileManager;
129 import cx.fbn.nevernote.config.InitializationException;
130 import cx.fbn.nevernote.config.StartupConfig;
131 import cx.fbn.nevernote.dialog.AccountDialog;
132 import cx.fbn.nevernote.dialog.ConfigDialog;
133 import cx.fbn.nevernote.dialog.DBEncryptDialog;
134 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
135 import cx.fbn.nevernote.dialog.DatabaseStatus;
136 import cx.fbn.nevernote.dialog.FindDialog;
137 import cx.fbn.nevernote.dialog.LoginDialog;
138 import cx.fbn.nevernote.dialog.NotebookArchive;
139 import cx.fbn.nevernote.dialog.NotebookEdit;
140 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
141 import cx.fbn.nevernote.dialog.SavedSearchEdit;
142 import cx.fbn.nevernote.dialog.TagEdit;
143 import cx.fbn.nevernote.dialog.ThumbnailViewer;
144 import cx.fbn.nevernote.dialog.WatchFolder;
145 import cx.fbn.nevernote.filters.EnSearch;
146 import cx.fbn.nevernote.gui.AttributeTreeWidget;
147 import cx.fbn.nevernote.gui.BrowserWindow;
148 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
149 import cx.fbn.nevernote.gui.MainMenuBar;
150 import cx.fbn.nevernote.gui.NotebookTreeWidget;
151 import cx.fbn.nevernote.gui.PDFPreview;
152 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
153 import cx.fbn.nevernote.gui.TableView;
154 import cx.fbn.nevernote.gui.TagTreeWidget;
155 import cx.fbn.nevernote.gui.Thumbnailer;
156 import cx.fbn.nevernote.gui.TrashTreeWidget;
157 import cx.fbn.nevernote.sql.DatabaseConnection;
158 import cx.fbn.nevernote.sql.WatchFolderRecord;
159 import cx.fbn.nevernote.threads.IndexRunner;
160 import cx.fbn.nevernote.threads.SyncRunner;
161 import cx.fbn.nevernote.utilities.AESEncrypter;
162 import cx.fbn.nevernote.utilities.ApplicationLogger;
163 import cx.fbn.nevernote.utilities.FileImporter;
164 import cx.fbn.nevernote.utilities.FileUtils;
165 import cx.fbn.nevernote.utilities.ListManager;
166 import cx.fbn.nevernote.utilities.SyncTimes;
167 import cx.fbn.nevernote.xml.ExportData;
168 import cx.fbn.nevernote.xml.ImportData;
169 import cx.fbn.nevernote.xml.XMLInsertHilight;
172 public class NeverNote extends QMainWindow{
174 QStatusBar statusBar; // Application status bar
176 DatabaseConnection conn;
178 MainMenuBar menuBar; // Main menu bar
179 FindDialog find; // Text search in note dialog
180 List<String> emitLog; // Messages displayed in the status bar;
181 QSystemTrayIcon trayIcon; // little tray icon
182 QMenu trayMenu; // System tray menu
183 QAction trayExitAction; // Exit the application
184 QAction trayShowAction; // toggle the show/hide action
185 QAction trayAddNoteAction; // Add a note from the system tray
187 NotebookTreeWidget notebookTree; // List of notebooks
188 AttributeTreeWidget attributeTree; // List of note attributes
189 TagTreeWidget tagTree; // list of user created tags
190 SavedSearchTreeWidget savedSearchTree; // list of saved searches
191 TrashTreeWidget trashTree; // Trashcan
192 TableView noteTableView; // List of notes (the widget).
194 public BrowserWindow browserWindow; // Window containing browser & labels
195 public QToolBar toolBar; // The tool bar under the menu
196 // QLineEdit searchField; // The search filter bar on the toolbar
197 QComboBox searchField; // search filter bar on the toolbar;
198 boolean searchPerformed = false; // Search was done?
199 QProgressBar quotaBar; // The current quota usage
201 ApplicationLogger logger;
202 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
203 List<String> selectedTagGUIDs; // List of selected tag GUIDs
204 List<String> selectedNoteGUIDs; // List of selected notes
205 String selectedSavedSearchGUID; // Currently selected saved searches
207 NoteFilter filter; // Note filter
208 String currentNoteGuid; // GUID of the current note
209 Note currentNote; // The currently viewed note
210 boolean noteDirty; // Has the note been changed?
211 boolean inkNote; // if this is an ink note, it is read only
213 ListManager listManager; // DB runnable task
215 List<QTemporaryFile> tempFiles; // Array of temporary files;
217 QTimer indexTimer; // timer to start the index thread
218 IndexRunner indexRunner; // thread to index notes
221 QTimer syncTimer; // Sync on an interval
222 QTimer syncDelayTimer; // Sync delay to free up database
223 SyncRunner syncRunner; // thread to do a sync.
225 QTimer saveTimer; // Timer to save note contents
227 QTimer authTimer; // Refresh authentication
228 QTimer externalFileSaveTimer; // Save files altered externally
229 List<String> externalFiles; // External files to save later
230 List<String> importFilesKeep; // Auto-import files to save later
231 List<String> importFilesDelete; // Auto-import files to save later
233 int indexTime; // how often to try and index
234 boolean indexRunning; // Is indexing running?
235 boolean indexDisabled; // Is indexing disabled?
237 int syncThreadsReady; // number of sync threads that are free
238 int syncTime; // Sync interval
239 boolean syncRunning; // Is sync running?
240 boolean automaticSync; // do sync automatically?
241 QTreeWidgetItem attributeTreeSelected;
243 QAction prevButton; // Go to the previous item viewed
244 QAction nextButton; // Go to the next item in the history
245 QAction downButton; // Go to the next item in the list
246 QAction upButton; // Go to the prev. item in the list;
247 QAction synchronizeButton; // Synchronize with Evernote
248 List<QIcon> synchronizeAnimation; // Synchronize movie
249 QTimer synchronizeAnimationTimer; // Timer to change animation button
250 int synchronizeFrame; // Current frame being viewed
251 QAction printButton; // Print Button
252 QAction tagButton; // Tag edit button
253 QAction attributeButton; // Attribute information button
254 QAction emailButton; // Email button
255 QAction deleteButton; // Delete button
256 QAction newButton; // new Note Button;
257 QSpinBox zoomSpinner; // Zoom zoom
258 QAction searchClearButton; // Clear the search field
260 QSplitter mainLeftRightSplitter; // main splitter for left/right side
261 QSplitter leftSplitter1; // first left hand splitter
262 QSplitter browserIndexSplitter; // splitter between note index & note text
264 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
265 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
266 List<String> importedFiles; // History of imported files (so we don't import twice)
268 OnlineNoteHistory historyWindow; // online history window
269 List<NoteVersionId> versions; // history versions
271 QTimer threadMonitorTimer; // Timer to watch threads.
272 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
273 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
274 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
275 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
276 int tagDeadCount=0; // number of consecutive dead times for the tag thread
277 int trashDeadCount=0; // number of consecutive dead times for the trash thread
278 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
280 HashMap<String, String> noteCache; // Cash of note content
281 List<String> historyGuids; // GUIDs of previously viewed items
282 int historyPosition; // Position within the viewed items
283 boolean fromHistory; // Is this from the history queue?
284 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
285 Thumbnailer preview; // generate preview image
286 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
287 boolean encryptOnShutdown; // should I encrypt when I close?
288 boolean decryptOnShutdown; // should I decrypt on shutdown;
289 String encryptCipher; // What cipher should I use?
290 Signal0 minimizeToTray;
291 boolean windowMaximized = false; // Keep track of the window state for restores
293 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
296 //***************************************************************
297 //***************************************************************
298 //** Constructor & main entry point
299 //***************************************************************
300 //***************************************************************
301 // Application Constructor
302 public NeverNote(DatabaseConnection dbConn) {
305 thread().setPriority(Thread.MAX_PRIORITY);
307 logger = new ApplicationLogger("nevernote.log");
308 logger.log(logger.HIGH, "Starting Application");
310 decryptOnShutdown = false;
311 encryptOnShutdown = false;
312 conn.checkDatabaseVersion();
316 // Start building the invalid XML tables
317 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
318 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
320 for (int i=0; i<elements.size(); i++) {
321 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
324 logger.log(logger.EXTREME, "Starting GUI build");
326 QTranslator qtTranslator = new QTranslator();
327 qtTranslator.load("classpath:/translations/qt_" + QLocale.system().name() + ".qm");
328 QApplication.instance().installTranslator(qtTranslator);
330 QTranslator nevernoteTranslator = new QTranslator();
331 nevernoteTranslator.load("classpath:/translations/nevernote_"+QLocale.system().name()+ ".qm");
332 QApplication.instance().installTranslator(nevernoteTranslator);
334 Global.originalPalette = QApplication.palette();
335 QApplication.setStyle(Global.getStyle());
336 if (Global.useStandardPalette())
337 QApplication.setPalette(QApplication.style().standardPalette());
338 setWindowTitle("NeverNote");
340 mainLeftRightSplitter = new QSplitter();
341 setCentralWidget(mainLeftRightSplitter);
342 leftSplitter1 = new QSplitter();
343 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
345 browserIndexSplitter = new QSplitter();
346 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
348 //* Setup threads & thread timers
349 int indexRunnerCount = Global.getIndexThreads();
350 indexRunnerCount = 1;
351 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
353 logger.log(logger.EXTREME, "Building list manager");
354 listManager = new ListManager(conn, logger);
356 logger.log(logger.EXTREME, "Building index runners & timers");
357 indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
358 indexThread = new QThread(indexRunner, "Index Thread");
361 synchronizeAnimationTimer = new QTimer();
362 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
364 indexTimer = new QTimer();
365 indexTime = 1000*Global.getIndexThreadSleepInterval();
366 indexTimer.start(indexTime); // Start indexing timer
367 indexTimer.timeout.connect(this, "indexTimer()");
368 indexDisabled = false;
369 indexRunning = false;
371 logger.log(logger.EXTREME, "Setting sync thread & timers");
373 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
374 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
375 syncTimer = new QTimer();
376 syncTimer.timeout.connect(this, "syncTimer()");
377 syncRunner.status.message.connect(this, "setMessage(String)");
378 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
379 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
382 automaticSync = true;
383 syncTimer.start(syncTime*60*1000);
385 automaticSync = false;
388 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
389 syncThread = new QThread(syncRunner, "Synchronization Thread");
393 logger.log(logger.EXTREME, "Starting authentication timer");
394 authTimer = new QTimer();
395 authTimer.timeout.connect(this, "authTimer()");
396 authTimer.start(1000*60*15);
397 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
399 logger.log(logger.EXTREME, "Setting save note timer");
400 saveTimer = new QTimer();
401 saveTimer.timeout.connect(this, "saveNote()");
402 if (Global.getAutoSaveInterval() > 0) {
403 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
404 // saveTimer.setInterval(1000*10); // auto save every 20 seconds;
407 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
409 logger.log(logger.EXTREME, "Starting external file monitor timer");
410 externalFileSaveTimer = new QTimer();
411 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
412 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
413 externalFiles = new ArrayList<String>();
414 importFilesDelete = new ArrayList<String>();
415 importFilesKeep = new ArrayList<String>();
416 externalFileSaveTimer.start();
418 notebookTree = new NotebookTreeWidget();
419 attributeTree = new AttributeTreeWidget();
420 tagTree = new TagTreeWidget(conn);
421 savedSearchTree = new SavedSearchTreeWidget();
422 trashTree = new TrashTreeWidget();
423 noteTableView = new TableView(logger, listManager);
425 QGridLayout leftGrid = new QGridLayout();
426 leftSplitter1.setLayout(leftGrid);
427 leftGrid.addWidget(notebookTree, 1, 1);
428 leftGrid.addWidget(tagTree,2,1);
429 leftGrid.addWidget(attributeTree,3,1);
430 leftGrid.addWidget(savedSearchTree,4,1);
431 leftGrid.addWidget(trashTree, 5, 1);
433 // Setup the browser window
434 noteCache = new HashMap<String,String>();
435 browserWindow = new BrowserWindow(conn);
437 browserIndexSplitter.addWidget(noteTableView);
438 browserIndexSplitter.addWidget(browserWindow);
440 mainLeftRightSplitter.addWidget(leftSplitter1);
441 mainLeftRightSplitter.addWidget(browserIndexSplitter);
443 searchField = new QComboBox();
444 searchField.setEditable(true);
445 searchField.activatedIndex.connect(this, "searchFieldChanged()");
446 searchField.setDuplicatesEnabled(false);
447 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
449 quotaBar = new QProgressBar();
451 // Setup the thumbnail viewer
452 thumbnailViewer = new ThumbnailViewer();
453 thumbnailViewer.upArrow.connect(this, "upAction()");
454 thumbnailViewer.downArrow.connect(this, "downAction()");
455 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
456 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
458 listManager.loadNotesIndex();
459 initializeNotebookTree();
461 initializeSavedSearchTree();
462 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
463 attributeTreeSelected = null;
464 initializeNoteTable();
466 selectedNoteGUIDs = new ArrayList<String>();
467 statusBar = new QStatusBar();
468 setStatusBar(statusBar);
469 menuBar = new MainMenuBar(this);
470 emitLog = new ArrayList<String>();
472 tagTree.setDeleteAction(menuBar.tagDeleteAction);
473 tagTree.setEditAction(menuBar.tagEditAction);
474 tagTree.setAddAction(menuBar.tagAddAction);
475 tagTree.setVisible(Global.isWindowVisible("tagTree"));
476 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
477 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
478 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
480 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
481 notebookTree.setEditAction(menuBar.notebookEditAction);
482 notebookTree.setAddAction(menuBar.notebookAddAction);
483 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
484 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
485 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
487 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
488 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
489 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
490 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
491 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
492 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
494 noteTableView.setAddAction(menuBar.noteAdd);
495 noteTableView.setDeleteAction(menuBar.noteDelete);
496 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
497 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
498 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
499 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
500 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
501 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
502 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
503 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
504 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
506 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
507 trashTree.setEmptyAction(menuBar.emptyTrashAction);
508 trashTree.setVisible(Global.isWindowVisible("trashTree"));
509 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
510 trashTree.updateCounts(listManager.getTrashCount());
512 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
513 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
515 noteTableView.setVisible(Global.isWindowVisible("noteList"));
516 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
518 if (!Global.isWindowVisible("editorButtonBar"))
519 toggleEditorButtonBar();
520 if (!Global.isWindowVisible("leftPanel"))
521 menuBar.hideLeftSide.setChecked(true);
525 find = new FindDialog();
526 find.getOkButton().clicked.connect(this, "doFindText()");
528 // Setup the tray icon menu bar
529 trayShowAction = new QAction("Show/Hide", this);
530 trayExitAction = new QAction("Exit", this);
531 trayAddNoteAction = new QAction("Add Note", this);
533 trayExitAction.triggered.connect(this, "close()");
534 trayAddNoteAction.triggered.connect(this, "addNote()");
535 trayShowAction.triggered.connect(this, "trayToggleVisible()");
537 trayMenu = new QMenu(this);
538 trayMenu.addAction(trayAddNoteAction);
539 trayMenu.addAction(trayShowAction);
540 trayMenu.addAction(trayExitAction);
543 trayIcon = new QSystemTrayIcon(this);
544 trayIcon.setToolTip("NeverNote");
545 trayIcon.setContextMenu(trayMenu);
546 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
549 currentNoteGuid = Global.getLastViewedNoteGuid();
550 historyGuids = new ArrayList<String>();
554 if (!currentNoteGuid.trim().equals("")) {
555 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
558 noteIndexUpdated(true);
560 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
561 if (menuBar.showEditorBar.isChecked())
563 tagIndexUpdated(true);
564 savedSearchIndexUpdated();
565 notebookIndexUpdated();
567 setupSyncSignalListeners();
568 setupBrowserSignalListeners();
569 setupIndexListeners();
572 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
573 tagTree.showAllTags(true);
575 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
576 setWindowIcon(appIcon);
577 trayIcon.setIcon(appIcon);
578 if (Global.showTrayIcon())
583 scrollToGuid(currentNoteGuid);
584 if (Global.automaticLogin()) {
586 if (Global.isConnected)
589 setupFolderImports();
592 restoreWindowState();
594 if (Global.mimicEvernoteInterface) {
595 notebookTree.selectGuid("");
598 threadMonitorTimer = new QTimer();
599 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
600 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
602 historyGuids.add(currentNoteGuid);
605 int sortCol = Global.getSortColumn();
606 int sortOrder = Global.getSortOrder();
607 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
612 public static void main(String[] args) {
613 QApplication.initialize(args);
614 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
615 QSplashScreen splash = new QSplashScreen(pixmap);
618 DatabaseConnection dbConn;
621 initializeGlobalSettings(args);
623 showSplash = Global.isWindowVisible("SplashScreen");
627 dbConn = setupDatabaseConnection();
629 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
630 Global.getFileManager().purgeResDirectory();
632 } catch (InitializationException e) {
635 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
639 NeverNote application = new NeverNote(dbConn);
641 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
642 if (Global.wasWindowMaximized())
643 application.showMaximized();
647 splash.finish(application);
649 System.out.println("Goodbye.");
654 * Open the internal database, or create if not present
656 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
658 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
659 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
661 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
662 boolean dbExists = f.exists();
664 Global.setDatabaseUrl("");
666 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
667 boolean goodCheck = false;
669 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
671 if (!dialog.okPressed())
673 Global.cipherPassword = dialog.getPassword();
674 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
675 Global.getDatabaseUserPassword(), Global.cipherPassword);
678 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
682 // Encrypt the database upon shutdown
683 private void encryptOnShutdown() {
684 String dbPath= Global.getFileManager().getDbDirPath("");
685 String dbName = "NeverNote";
687 Statement st = conn.getConnection().createStatement();
688 st.execute("shutdown");
689 if (QMessageBox.question(this, "Are you sure",
690 "Are you sure you wish to encrypt the database?",
691 QMessageBox.StandardButton.Yes,
692 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
693 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
694 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
695 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
697 } catch (SQLException e) {
702 // Decrypt the database upon shutdown
703 private void decryptOnShutdown() {
704 String dbPath= Global.getFileManager().getDbDirPath("");
705 String dbName = "NeverNote";
707 Statement st = conn.getConnection().createStatement();
708 st.execute("shutdown");
709 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
710 encryptCipher = "AES";
712 encryptCipher = "XTEA";
713 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
714 "Are you sure you wish to decrypt the database?"),
715 QMessageBox.StandardButton.Yes,
716 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
718 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
719 Global.setDatabaseUrl("");
720 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
722 } catch (SQLException e) {
727 * Encrypt/Decrypt the local database
729 public void doDatabaseEncrypt() {
730 // The database is not currently encrypted
731 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
732 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
733 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
734 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
735 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
736 "Do you wish to proceed?"),
737 QMessageBox.StandardButton.Yes,
738 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
741 DBEncryptDialog dialog = new DBEncryptDialog();
743 if (dialog.okPressed()) {
744 Global.cipherPassword = dialog.getPassword();
745 encryptOnShutdown = true;
746 encryptCipher = dialog.getEncryptionMethod();
749 DBEncryptDialog dialog = new DBEncryptDialog();
750 dialog.setWindowTitle("Database Decryption");
751 dialog.hideEncryption();
753 if (dialog.okPressed()) {
754 if (!dialog.getPassword().equals(Global.cipherPassword)) {
755 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
758 decryptOnShutdown = true;
765 private static void initializeGlobalSettings(String[] args) throws InitializationException {
766 StartupConfig startupConfig = new StartupConfig();
768 for (String arg : args) {
769 String lower = arg.toLowerCase();
770 if (lower.startsWith("--name="))
771 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
772 if (lower.startsWith("--home="))
773 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
774 if (lower.startsWith("--disable-viewing"))
775 startupConfig.setDisableViewing(true);
777 Global.setup(startupConfig);
782 public void closeEvent(QCloseEvent event) {
783 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
786 if (currentNote!= null & browserWindow!=null) {
787 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
788 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
791 setMessage(tr("Beginning shutdown."));
793 externalFileEditedSaver();
794 if (Global.isConnected && Global.synchronizeOnClose()) {
795 setMessage(tr("Performing synchronization before closing."));
796 syncRunner.addWork("SYNC");
798 setMessage("Closing Program.");
799 threadMonitorTimer.stop();
801 syncRunner.addWork("STOP");
802 indexRunner.addWork("STOP");
807 if (tempFiles != null)
810 browserWindow.noteSignal.tagsChanged.disconnect();
811 browserWindow.noteSignal.titleChanged.disconnect();
812 browserWindow.noteSignal.noteChanged.disconnect();
813 browserWindow.noteSignal.notebookChanged.disconnect();
814 browserWindow.noteSignal.createdDateChanged.disconnect();
815 browserWindow.noteSignal.alteredDateChanged.disconnect();
816 syncRunner.searchSignal.listChanged.disconnect();
817 syncRunner.tagSignal.listChanged.disconnect();
818 syncRunner.notebookSignal.listChanged.disconnect();
819 syncRunner.noteIndexSignal.listChanged.disconnect();
822 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
823 Global.setColumnPosition("noteTableCreationPosition", position);
824 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
825 Global.setColumnPosition("noteTableTagPosition", position);
826 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
827 Global.setColumnPosition("noteTableNotebookPosition", position);
828 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
829 Global.setColumnPosition("noteTableChangedPosition", position);
830 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
831 Global.setColumnPosition("noteTableAuthorPosition", position);
832 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
833 Global.setColumnPosition("noteTableSourceUrlPosition", position);
834 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
835 Global.setColumnPosition("noteTableSubjectDatePosition", position);
836 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
837 Global.setColumnPosition("noteTableTitlePosition", position);
838 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
839 Global.setColumnPosition("noteTableSynchronizedPosition", position);
842 Global.saveWindowVisible("toolBar", toolBar.isVisible());
843 saveNoteIndexWidth();
845 int width = notebookTree.columnWidth(0);
846 Global.setColumnWidth("notebookTreeName", width);
847 width = tagTree.columnWidth(0);
848 Global.setColumnWidth("tagTreeName", width);
850 Global.saveWindowMaximized(isMaximized());
851 Global.saveCurrentNoteGuid(currentNoteGuid);
853 int sortCol = noteTableView.proxyModel.sortColumn();
854 int sortOrder = noteTableView.proxyModel.sortOrder().value();
855 Global.setSortColumn(sortCol);
856 Global.setSortOrder(sortOrder);
860 Global.keepRunning = false;
862 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
863 indexRunner.thread().join(50);
864 logger.log(logger.MEDIUM, "Index thread has stopped");
865 } catch (InterruptedException e1) {
866 e1.printStackTrace();
868 if (!syncRunner.isIdle()) {
870 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
872 logger.log(logger.MEDIUM, "Sync thread has stopped");
873 } catch (InterruptedException e1) {
874 e1.printStackTrace();
878 if (encryptOnShutdown) {
881 if (decryptOnShutdown) {
884 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
887 public void setMessage(String s) {
888 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
889 logger.log(logger.HIGH, "Message: " +s);
890 statusBar.showMessage(s);
892 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
895 private void waitCursor(boolean wait) {
897 // QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
899 // QApplication.restoreOverrideCursor();
902 private void setupIndexListeners() {
903 indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
904 indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
905 // indexRunner.threadSignal.indexNeeded.connect(listManager, "setIndexNeeded(String, String, Boolean)");
907 private void setupSyncSignalListeners() {
908 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
909 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
910 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
911 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
912 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
914 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
915 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
916 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
918 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
919 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
920 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
921 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
923 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
926 private void setupBrowserSignalListeners() {
928 browserWindow.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
929 browserWindow.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
930 browserWindow.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
931 //browserWindow.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
932 browserWindow.noteSignal.noteChanged.connect(this, "setNoteDirty()");
933 browserWindow.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
934 browserWindow.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
935 browserWindow.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
936 browserWindow.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
937 browserWindow.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
938 browserWindow.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
939 browserWindow.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
940 browserWindow.noteSignal.geoChanged.connect(this, "setNoteDirty()");
941 browserWindow.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
942 browserWindow.focusLost.connect(this, "saveNote()");
943 browserWindow.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
948 //***************************************************************
949 //***************************************************************
950 //* Settings and look & feel
951 //***************************************************************
952 //***************************************************************
953 @SuppressWarnings("unused")
954 private void settings() {
955 logger.log(logger.HIGH, "Entering NeverNote.settings");
956 ConfigDialog settings = new ConfigDialog(this);
957 String dateFormat = Global.getDateFormat();
958 String timeFormat = Global.getTimeFormat();
960 indexTime = 1000*Global.getIndexThreadSleepInterval();
961 indexTimer.start(indexTime); // reset indexing timer
964 if (Global.showTrayIcon())
969 if (menuBar.showEditorBar.isChecked())
972 // Reset the save timer
973 if (Global.getAutoSaveInterval() > 0)
974 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
978 // This is a hack to force a reload of the index in case the date or time changed.
979 // if (!dateFormat.equals(Global.getDateFormat()) ||
980 // !timeFormat.equals(Global.getTimeFormat())) {
982 noteIndexUpdated(true);
985 logger.log(logger.HIGH, "Leaving NeverNote.settings");
987 // Restore things to the way they were
988 private void restoreWindowState() {
989 // We need to name things or this doesn't work.
990 setObjectName("NeverNote");
991 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
992 browserIndexSplitter.setObjectName("browserIndexSplitter");
993 leftSplitter1.setObjectName("leftSplitter1");
995 // Restore the actual positions.
996 restoreGeometry(Global.restoreGeometry(objectName()));
997 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
998 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
999 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1002 // Save window positions for the next start
1003 private void saveWindowState() {
1004 Global.saveGeometry(objectName(), saveGeometry());
1005 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1006 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1007 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1009 // Load the style sheet
1010 private void loadStyleSheet() {
1011 String fileName = Global.getFileManager().getQssDirPath("default.qss");
1012 QFile file = new QFile(fileName);
1013 file.open(OpenModeFlag.ReadOnly);
1014 String styleSheet = file.readAll().toString();
1016 setStyleSheet(styleSheet);
1018 // Save column widths for the next time
1019 private void saveNoteIndexWidth() {
1021 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1022 Global.setColumnWidth("noteTableCreationPosition", width);
1023 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1024 Global.setColumnWidth("noteTableChangedPosition", width);
1025 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1026 Global.setColumnWidth("noteTableGuidPosition", width);
1027 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1028 Global.setColumnWidth("noteTableNotebookPosition", width);
1029 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1030 Global.setColumnWidth("noteTableTagPosition", width);
1031 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1032 Global.setColumnWidth("noteTableTitlePosition", width);
1033 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1034 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1035 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1036 Global.setColumnWidth("noteTableAuthorPosition", width);
1037 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1038 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1039 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1040 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1044 //***************************************************************
1045 //***************************************************************
1046 //** These functions deal with Notebook menu items
1047 //***************************************************************
1048 //***************************************************************
1049 // Setup the tree containing the user's notebooks.
1050 private void initializeNotebookTree() {
1051 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1052 notebookTree.itemSelectionChanged.connect(this, "notebookTreeSelection()");
1053 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1054 // notebookTree.resize(Global.getSize("notebookTree"));
1055 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1057 // Listener when a notebook is selected
1058 private void notebookTreeSelection() {
1059 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1062 clearAttributeFilter();
1063 clearSavedSearchFilter();
1064 if (Global.mimicEvernoteInterface) {
1066 searchField.clear();
1068 menuBar.noteRestoreAction.setVisible(false);
1069 menuBar.notebookEditAction.setEnabled(true);
1070 menuBar.notebookDeleteAction.setEnabled(true);
1071 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1072 QTreeWidgetItem currentSelection;
1073 selectedNotebookGUIDs.clear();
1074 if (!Global.mimicEvernoteInterface) {
1075 for (int i=0; i<selections.size(); i++) {
1076 currentSelection = selections.get(i);
1077 selectedNotebookGUIDs.add(currentSelection.text(2));
1081 // There is the potential for no notebooks to be selected if this
1082 // happens then we make it look like all notebooks were selecetd.
1083 // If that happens, just select the "all notebooks"
1084 selections = notebookTree.selectedItems();
1085 if (selections.size()==0) {
1086 selectedNotebookGUIDs.clear();
1087 menuBar.notebookEditAction.setEnabled(false);
1088 menuBar.notebookDeleteAction.setEnabled(false);
1092 if (selections.size() > 0)
1093 guid = (selections.get(0).text(2));
1094 if (!guid.equals(""))
1095 selectedNotebookGUIDs.add(guid);
1097 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1098 listManager.loadNotesIndex();
1099 noteIndexUpdated(false);
1100 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1103 private void clearNotebookFilter() {
1104 notebookTree.blockSignals(true);
1105 notebookTree.clearSelection();
1106 menuBar.noteRestoreAction.setVisible(false);
1107 menuBar.notebookEditAction.setEnabled(false);
1108 menuBar.notebookDeleteAction.setEnabled(false);
1109 selectedNotebookGUIDs.clear();
1110 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1111 notebookTree.blockSignals(false);
1113 // Triggered when the notebook DB has been updated
1114 private void notebookIndexUpdated() {
1115 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1116 if (selectedNotebookGUIDs == null)
1117 selectedNotebookGUIDs = new ArrayList<String>();
1118 List<Notebook> books = conn.getNotebookTable().getAll();
1119 for (int i=books.size()-1; i>=0; i--) {
1120 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1121 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1123 j=listManager.getArchiveNotebookIndex().size();
1129 listManager.countNotebookResults(listManager.getNoteIndex());
1130 notebookTree.blockSignals(true);
1131 notebookTree.load(books, listManager.getLocalNotebooks());
1132 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1133 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1135 selectedNotebookGUIDs.remove(i);
1137 notebookTree.blockSignals(false);
1139 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1141 // Show/Hide note information
1142 private void toggleNotebookWindow() {
1143 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1144 if (notebookTree.isVisible())
1145 notebookTree.hide();
1147 notebookTree.show();
1148 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1149 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1150 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1152 // Add a new notebook
1153 @SuppressWarnings("unused")
1154 private void addNotebook() {
1155 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1156 NotebookEdit edit = new NotebookEdit();
1157 edit.setNotebooks(listManager.getNotebookIndex());
1160 if (!edit.okPressed())
1163 Calendar currentTime = new GregorianCalendar();
1164 Long l = new Long(currentTime.getTimeInMillis());
1165 String randint = new String(Long.toString(l));
1167 Notebook newBook = new Notebook();
1168 newBook.setUpdateSequenceNum(0);
1169 newBook.setGuid(randint);
1170 newBook.setName(edit.getNotebook());
1171 newBook.setServiceCreated(new Date().getTime());
1172 newBook.setServiceUpdated(new Date().getTime());
1173 newBook.setDefaultNotebook(false);
1174 newBook.setPublished(false);
1176 listManager.getNotebookIndex().add(newBook);
1178 listManager.getLocalNotebooks().add(newBook.getGuid());
1179 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1180 notebookIndexUpdated();
1181 listManager.countNotebookResults(listManager.getNoteIndex());
1182 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1183 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1185 // Edit an existing notebook
1186 @SuppressWarnings("unused")
1187 private void editNotebook() {
1188 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1189 NotebookEdit edit = new NotebookEdit();
1190 edit.setTitle(tr("Edit Notebook"));
1191 edit.setLocalCheckboxEnabled(false);
1192 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1193 QTreeWidgetItem currentSelection;
1194 currentSelection = selections.get(0);
1195 edit.setNotebook(currentSelection.text(0));
1196 edit.setNotebooks(listManager.getNotebookIndex());
1199 if (!edit.okPressed())
1202 String guid = currentSelection.text(2);
1203 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1204 currentSelection.setText(0, edit.getNotebook());
1206 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1207 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1208 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1209 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1210 i=listManager.getNotebookIndex().size();
1214 // Build a list of non-closed notebooks
1215 List<Notebook> nbooks = new ArrayList<Notebook>();
1216 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1217 boolean found=false;
1218 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1219 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1223 nbooks.add(listManager.getNotebookIndex().get(i));
1226 browserWindow.setNotebookList(nbooks);
1227 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1229 // Delete an existing notebook
1230 @SuppressWarnings("unused")
1231 private void deleteNotebook() {
1232 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1233 boolean assigned = false;
1234 // Check if any notes have this notebook
1235 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1236 for (int i=0; i<selections.size(); i++) {
1237 QTreeWidgetItem currentSelection;
1238 currentSelection = selections.get(i);
1239 String guid = currentSelection.text(2);
1240 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1241 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1242 if (noteGuid.equals(guid)) {
1244 j=listManager.getNoteIndex().size();
1245 i=selections.size();
1250 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1251 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1255 if (conn.getNotebookTable().getAll().size() == 1) {
1256 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1260 // If all notebooks are clear, verify the delete
1261 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected notebooks?"),
1262 QMessageBox.StandardButton.Yes,
1263 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1267 // If confirmed, delete the notebook
1268 for (int i=selections.size()-1; i>=0; i--) {
1269 QTreeWidgetItem currentSelection;
1270 currentSelection = selections.get(i);
1271 String guid = currentSelection.text(2);
1272 conn.getNotebookTable().expungeNotebook(guid, true);
1273 listManager.deleteNotebook(guid);
1275 // for (int i=<dbRunner.getLocalNotebooks().size()-1; i>=0; i--) {
1276 // if (dbRunner.getLocalNotebooks().get(i).equals(arg0))
1278 notebookTreeSelection();
1279 notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1280 listManager.countNotebookResults(listManager.getNoteIndex());
1281 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1282 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1284 // A note's notebook has been updated
1285 @SuppressWarnings("unused")
1286 private void updateNoteNotebook(String guid, String notebookGuid) {
1288 // Update the list manager
1289 listManager.updateNoteNotebook(guid, notebookGuid);
1290 listManager.countNotebookResults(listManager.getNoteIndex());
1291 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1293 // Find the name of the notebook
1294 String notebookName = null;
1295 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1296 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1297 notebookName = listManager.getNotebookIndex().get(i).getName();
1302 // If we found the name, update the browser window
1303 if (notebookName != null) {
1304 updateListNoteNotebook(guid, notebookName);
1305 if (guid.equals(currentNoteGuid)) {
1306 int pos = browserWindow.notebookBox.findText(notebookName);
1308 browserWindow.notebookBox.setCurrentIndex(pos);
1312 // If we're dealing with the current note, then we need to be sure and update the notebook there
1313 if (guid.equals(currentNoteGuid)) {
1314 if (currentNote != null) {
1315 currentNote.setNotebookGuid(notebookGuid);
1319 // Open/close notebooks
1320 @SuppressWarnings("unused")
1321 private void closeNotebooks() {
1322 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1324 if (!na.okClicked())
1328 listManager.getArchiveNotebookIndex().clear();
1330 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1331 String text = na.getClosedBookList().takeItem(i).text();
1332 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1333 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1334 Notebook n = listManager.getNotebookIndex().get(j);
1335 conn.getNotebookTable().setArchived(n.getGuid(),true);
1336 listManager.getArchiveNotebookIndex().add(n);
1337 j=listManager.getNotebookIndex().size();
1342 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1343 String text = na.getOpenBookList().takeItem(i).text();
1344 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1345 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1346 Notebook n = listManager.getNotebookIndex().get(j);
1347 conn.getNotebookTable().setArchived(n.getGuid(),false);
1348 j=listManager.getNotebookIndex().size();
1352 notebookTreeSelection();
1353 listManager.loadNotesIndex();
1354 notebookIndexUpdated();
1355 noteIndexUpdated(false);
1356 // noteIndexUpdated(false);
1358 // Build a list of non-closed notebooks
1359 List<Notebook> nbooks = new ArrayList<Notebook>();
1360 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1361 boolean found=false;
1362 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1363 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1367 nbooks.add(listManager.getNotebookIndex().get(i));
1370 browserWindow.setNotebookList(nbooks);
1377 //***************************************************************
1378 //***************************************************************
1379 //** These functions deal with Tag menu items
1380 //***************************************************************
1381 //***************************************************************
1382 // Add a new notebook
1383 @SuppressWarnings("unused")
1384 private void addTag() {
1385 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1386 TagEdit edit = new TagEdit();
1387 edit.setTagList(listManager.getTagIndex());
1390 if (!edit.okPressed())
1393 Calendar currentTime = new GregorianCalendar();
1394 Long l = new Long(currentTime.getTimeInMillis());
1395 String randint = new String(Long.toString(l));
1397 Tag newTag = new Tag();
1398 newTag.setUpdateSequenceNum(0);
1399 newTag.setGuid(randint);
1400 newTag.setName(edit.getTag());
1401 conn.getTagTable().addTag(newTag, true);
1402 listManager.getTagIndex().add(newTag);
1405 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1407 private void reloadTagTree() {
1408 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1409 tagIndexUpdated(false);
1410 boolean filter = false;
1411 listManager.countTagResults(listManager.getNoteIndex());
1412 if (notebookTree.selectedItems().size() > 0
1413 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1415 if (tagTree.selectedItems().size() > 0)
1417 tagTree.showAllTags(!filter);
1418 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1420 // Edit an existing tag
1421 @SuppressWarnings("unused")
1422 private void editTag() {
1423 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1424 TagEdit edit = new TagEdit();
1425 edit.setTitle("Edit Tag");
1426 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1427 QTreeWidgetItem currentSelection;
1428 currentSelection = selections.get(0);
1429 edit.setTag(currentSelection.text(0));
1430 edit.setTagList(listManager.getTagIndex());
1433 if (!edit.okPressed())
1436 String guid = currentSelection.text(2);
1437 currentSelection.setText(0,edit.getTag());
1439 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1440 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1441 listManager.getTagIndex().get(i).setName(edit.getTag());
1442 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1443 updateListTagName(guid);
1444 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1445 browserWindow.setTag(getTagNamesForNote(currentNote));
1446 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1450 browserWindow.setTag(getTagNamesForNote(currentNote));
1451 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1453 // Delete an existing tag
1454 @SuppressWarnings("unused")
1455 private void deleteTag() {
1456 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1458 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1459 QMessageBox.StandardButton.Yes,
1460 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1464 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1465 for (int i=selections.size()-1; i>=0; i--) {
1466 QTreeWidgetItem currentSelection;
1467 currentSelection = selections.get(i);
1468 removeTagItem(currentSelection.text(2));
1470 tagIndexUpdated(true);
1472 listManager.countTagResults(listManager.getNoteIndex());
1473 // tagTree.updateCounts(listManager.getTagCounter());
1474 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1476 // Remove a tag tree item. Go recursively down & remove the children too
1477 private void removeTagItem(String guid) {
1478 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1479 String parent = listManager.getTagIndex().get(j).getParentGuid();
1480 if (parent != null && parent.equals(guid)) {
1481 //Remove this tag's children
1482 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1485 //Now, remove this tag
1486 removeListTagName(guid);
1487 conn.getTagTable().expungeTag(guid, true);
1488 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1489 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1490 listManager.getTagIndex().remove(a);
1495 // Setup the tree containing the user's tags
1496 private void initializeTagTree() {
1497 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1498 tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1499 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1500 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1502 // Listener when a tag is selected
1503 private void tagTreeSelection() {
1504 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1507 clearAttributeFilter();
1508 clearSavedSearchFilter();
1510 menuBar.noteRestoreAction.setVisible(false);
1512 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1513 QTreeWidgetItem currentSelection;
1514 selectedTagGUIDs.clear();
1515 for (int i=0; i<selections.size(); i++) {
1516 currentSelection = selections.get(i);
1517 selectedTagGUIDs.add(currentSelection.text(2));
1519 if (selections.size() > 0) {
1520 menuBar.tagEditAction.setEnabled(true);
1521 menuBar.tagDeleteAction.setEnabled(true);
1524 menuBar.tagEditAction.setEnabled(false);
1525 menuBar.tagDeleteAction.setEnabled(false);
1527 listManager.setSelectedTags(selectedTagGUIDs);
1528 listManager.loadNotesIndex();
1529 noteIndexUpdated(false);
1530 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1532 // trigger the tag index to be refreshed
1533 @SuppressWarnings("unused")
1534 private void tagIndexUpdated() {
1535 tagIndexUpdated(true);
1537 private void tagIndexUpdated(boolean reload) {
1538 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1539 if (selectedTagGUIDs == null)
1540 selectedTagGUIDs = new ArrayList<String>();
1541 // selectedTagGUIDs.clear(); // clear out old entries
1543 tagTree.blockSignals(true);
1545 tagTree.load(listManager.getTagIndex());
1546 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1547 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1549 selectedTagGUIDs.remove(i);
1551 tagTree.blockSignals(false);
1553 browserWindow.setTag(getTagNamesForNote(currentNote));
1554 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1556 // Show/Hide note information
1557 private void toggleTagWindow() {
1558 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1559 if (tagTree.isVisible())
1563 menuBar.hideTags.setChecked(tagTree.isVisible());
1564 Global.saveWindowVisible("tagTree", tagTree.isVisible());
1565 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1567 // A note's tags have been updated
1568 @SuppressWarnings("unused")
1569 private void updateNoteTags(String guid, List<String> tags) {
1570 // Save any new tags. We'll need them later.
1571 List<String> newTags = new ArrayList<String>();
1572 for (int i=0; i<tags.size(); i++) {
1573 if (conn.getTagTable().findTagByName(tags.get(i))==null)
1574 newTags.add(tags.get(i));
1577 listManager.saveNoteTags(guid, tags);
1578 listManager.countTagResults(listManager.getNoteIndex());
1579 StringBuffer names = new StringBuffer("");
1580 for (int i=0; i<tags.size(); i++) {
1581 names = names.append(tags.get(i));
1582 if (i<tags.size()-1) {
1583 names.append(Global.tagDelimeter + " ");
1586 browserWindow.setTag(names.toString());
1589 // Now, we need to add any new tags to the tag tree
1590 for (int i=0; i<newTags.size(); i++)
1591 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
1593 // Get a string containing all tag names for a note
1594 private String getTagNamesForNote(Note n) {
1595 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
1596 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
1598 StringBuffer buffer = new StringBuffer(100);
1599 Vector<String> v = new Vector<String>();
1600 List<String> guids = n.getTagGuids();
1605 for (int i=0; i<guids.size(); i++) {
1606 v.add(listManager.getTagNameByGuid(guids.get(i)));
1608 Comparator<String> comparator = Collections.reverseOrder();
1609 Collections.sort(v,comparator);
1610 Collections.reverse(v);
1612 for (int i = 0; i<v.size(); i++) {
1614 buffer.append(", ");
1615 buffer.append(v.get(i));
1618 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
1619 return buffer.toString();
1621 // Tags were added via dropping notes from the note list
1622 @SuppressWarnings("unused")
1623 private void tagsAdded(String noteGuid, String tagGuid) {
1624 String tagName = null;
1625 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1626 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
1627 tagName = listManager.getTagIndex().get(i).getName();
1628 i=listManager.getTagIndex().size();
1631 if (tagName == null)
1634 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
1635 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
1636 List<String> tagNames = new ArrayList<String>();
1637 tagNames.add(new String(tagName));
1638 Note n = listManager.getMasterNoteIndex().get(i);
1639 for (int j=0; j<n.getTagNames().size(); j++) {
1640 tagNames.add(new String(n.getTagNames().get(j)));
1642 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
1643 if (n.getGuid().equals(currentNoteGuid)) {
1644 Collections.sort(tagNames);
1645 String display = "";
1646 for (int j=0; j<tagNames.size(); j++) {
1647 display = display+tagNames.get(j);
1648 if (j+2<tagNames.size())
1649 display = display+Global.tagDelimeter+" ";
1651 browserWindow.setTag(display);
1653 i=listManager.getMasterNoteIndex().size();
1658 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
1660 private void clearTagFilter() {
1661 tagTree.blockSignals(true);
1662 tagTree.clearSelection();
1663 menuBar.noteRestoreAction.setVisible(false);
1664 menuBar.tagEditAction.setEnabled(false);
1665 menuBar.tagDeleteAction.setEnabled(false);
1666 selectedTagGUIDs.clear();
1667 listManager.setSelectedTags(selectedTagGUIDs);
1668 tagTree.blockSignals(false);
1672 //***************************************************************
1673 //***************************************************************
1674 //** These functions deal with Saved Search menu items
1675 //***************************************************************
1676 //***************************************************************
1677 // Add a new notebook
1678 @SuppressWarnings("unused")
1679 private void addSavedSearch() {
1680 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
1681 SavedSearchEdit edit = new SavedSearchEdit();
1682 edit.setSearchList(listManager.getSavedSearchIndex());
1685 if (!edit.okPressed())
1688 Calendar currentTime = new GregorianCalendar();
1689 Long l = new Long(currentTime.getTimeInMillis());
1690 String randint = new String(Long.toString(l));
1692 SavedSearch search = new SavedSearch();
1693 search.setUpdateSequenceNum(0);
1694 search.setGuid(randint);
1695 search.setName(edit.getName());
1696 search.setQuery(edit.getQuery());
1697 search.setFormat(QueryFormat.USER);
1698 listManager.getSavedSearchIndex().add(search);
1699 conn.getSavedSearchTable().addSavedSearch(search, true);
1700 savedSearchIndexUpdated();
1701 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
1703 // Edit an existing tag
1704 @SuppressWarnings("unused")
1705 private void editSavedSearch() {
1706 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
1707 SavedSearchEdit edit = new SavedSearchEdit();
1708 edit.setTitle(tr("Edit Search"));
1709 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1710 QTreeWidgetItem currentSelection;
1711 currentSelection = selections.get(0);
1712 String guid = currentSelection.text(1);
1713 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
1714 edit.setName(currentSelection.text(0));
1715 edit.setQuery(s.getQuery());
1716 edit.setSearchList(listManager.getSavedSearchIndex());
1719 if (!edit.okPressed())
1722 List<SavedSearch> list = listManager.getSavedSearchIndex();
1723 SavedSearch search = null;
1724 boolean found = false;
1725 for (int i=0; i<list.size(); i++) {
1726 search = list.get(i);
1727 if (search.getGuid().equals(guid)) {
1734 search.setName(edit.getName());
1735 search.setQuery(edit.getQuery());
1736 conn.getSavedSearchTable().updateSavedSearch(search, true);
1737 savedSearchIndexUpdated();
1738 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
1740 // Delete an existing tag
1741 @SuppressWarnings("unused")
1742 private void deleteSavedSearch() {
1743 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
1745 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
1746 QMessageBox.StandardButton.Yes,
1747 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1751 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1752 for (int i=selections.size()-1; i>=0; i--) {
1753 QTreeWidgetItem currentSelection;
1754 currentSelection = selections.get(i);
1755 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
1756 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
1757 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
1758 listManager.getSavedSearchIndex().remove(j);
1759 j=listManager.getSavedSearchIndex().size()+1;
1762 selections.remove(i);
1764 savedSearchIndexUpdated();
1765 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
1767 // Setup the tree containing the user's tags
1768 private void initializeSavedSearchTree() {
1769 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
1770 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
1771 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
1773 // Listener when a tag is selected
1774 @SuppressWarnings("unused")
1775 private void savedSearchTreeSelection() {
1776 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
1778 clearNotebookFilter();
1781 clearAttributeFilter();
1783 String currentGuid = selectedSavedSearchGUID;
1784 menuBar.savedSearchEditAction.setEnabled(true);
1785 menuBar.savedSearchDeleteAction.setEnabled(true);
1786 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1787 QTreeWidgetItem currentSelection;
1788 selectedSavedSearchGUID = "";
1789 for (int i=0; i<selections.size(); i++) {
1790 currentSelection = selections.get(i);
1791 if (currentSelection.text(1).equals(currentGuid)) {
1792 currentSelection.setSelected(false);
1794 selectedSavedSearchGUID = currentSelection.text(1);
1796 // i = selections.size() +1;
1799 // There is the potential for no notebooks to be selected if this
1800 // happens then we make it look like all notebooks were selecetd.
1801 // If that happens, just select the "all notebooks"
1802 if (selections.size()==0) {
1803 clearSavedSearchFilter();
1805 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1807 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
1809 private void clearSavedSearchFilter() {
1810 menuBar.savedSearchEditAction.setEnabled(false);
1811 menuBar.savedSearchDeleteAction.setEnabled(false);
1812 savedSearchTree.blockSignals(true);
1813 savedSearchTree.clearSelection();
1814 savedSearchTree.blockSignals(false);
1815 selectedSavedSearchGUID = "";
1816 searchField.setEditText("");
1817 searchPerformed = false;
1818 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1820 // trigger the tag index to be refreshed
1821 private void savedSearchIndexUpdated() {
1822 if (selectedSavedSearchGUID == null)
1823 selectedSavedSearchGUID = new String();
1824 savedSearchTree.blockSignals(true);
1825 savedSearchTree.load(listManager.getSavedSearchIndex());
1826 savedSearchTree.selectGuid(selectedSavedSearchGUID);
1827 savedSearchTree.blockSignals(false);
1829 // trigger when the saved search selection changes
1830 @SuppressWarnings("unused")
1831 private void updateSavedSearchSelection() {
1832 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
1834 menuBar.savedSearchEditAction.setEnabled(true);
1835 menuBar.savedSearchDeleteAction.setEnabled(true);
1836 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1838 if (selections.size() > 0) {
1839 menuBar.savedSearchEditAction.setEnabled(true);
1840 menuBar.savedSearchDeleteAction.setEnabled(true);
1841 selectedSavedSearchGUID = selections.get(0).text(1);
1842 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
1843 searchField.setEditText(s.getQuery());
1845 menuBar.savedSearchEditAction.setEnabled(false);
1846 menuBar.savedSearchDeleteAction.setEnabled(false);
1847 selectedSavedSearchGUID = "";
1848 searchField.setEditText("");
1850 searchFieldChanged();
1852 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
1856 // Show/Hide note information
1857 private void toggleSavedSearchWindow() {
1858 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
1859 if (savedSearchTree.isVisible())
1860 savedSearchTree.hide();
1862 savedSearchTree.show();
1863 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
1865 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
1866 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
1872 //***************************************************************
1873 //***************************************************************
1874 //** These functions deal with Help menu & tool menu items
1875 //***************************************************************
1876 //***************************************************************
1877 // Show database status
1878 @SuppressWarnings("unused")
1879 private void databaseStatus() {
1881 int dirty = conn.getNoteTable().getDirtyCount();
1882 int unindexed = conn.getNoteTable().getUnindexedCount();
1883 DatabaseStatus status = new DatabaseStatus();
1884 status.setUnsynchronized(dirty);
1885 status.setUnindexed(unindexed);
1886 status.setNoteCount(conn.getNoteTable().getNoteCount());
1887 status.setNotebookCount(listManager.getNotebookIndex().size());
1888 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
1889 status.setTagCount(listManager.getTagIndex().size());
1890 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
1891 status.setWordCount(conn.getWordsTable().getWordCount());
1895 // Compact the database
1896 @SuppressWarnings("unused")
1897 private void compactDatabase() {
1898 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
1899 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
1900 "but please be aware that depending upon the size of your database this can be time consuming " +
1901 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
1902 QMessageBox.StandardButton.Yes,
1903 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
1906 setMessage("Compacting database.");
1908 listManager.compactDatabase();
1910 setMessage("Database compact is complete.");
1911 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
1913 @SuppressWarnings("unused")
1914 private void accountInformation() {
1915 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
1916 AccountDialog dialog = new AccountDialog();
1918 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
1920 @SuppressWarnings("unused")
1921 private void releaseNotes() {
1922 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
1923 QDialog dialog = new QDialog(this);
1924 QHBoxLayout layout = new QHBoxLayout();
1925 QTextEdit textBox = new QTextEdit();
1926 layout.addWidget(textBox);
1927 textBox.setReadOnly(true);
1928 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
1929 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
1930 QIODevice.OpenModeFlag.Text)))
1932 textBox.setText(file.readAll().toString());
1934 dialog.setWindowTitle(tr("Release Notes"));
1935 dialog.setLayout(layout);
1937 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
1939 // Called when user picks Log from the help menu
1940 @SuppressWarnings("unused")
1941 private void logger() {
1942 logger.log(logger.HIGH, "Entering NeverNote.logger");
1943 QDialog dialog = new QDialog(this);
1944 QHBoxLayout layout = new QHBoxLayout();
1945 QListWidget textBox = new QListWidget();
1946 layout.addWidget(textBox);
1947 textBox.addItems(emitLog);
1949 dialog.setLayout(layout);
1950 dialog.setWindowTitle(tr("Mesasge Log"));
1952 logger.log(logger.HIGH, "Leaving NeverNote.logger");
1954 // Menu option "help/about" was selected
1955 @SuppressWarnings("unused")
1956 private void about() {
1957 logger.log(logger.HIGH, "Entering NeverNote.about");
1958 QMessageBox.about(this,
1959 tr("About NeverNote"),
1960 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
1962 +tr("<hr></center>Evernote"
1963 +"An Open Source Evernote Client.<br><br>"
1964 +"Licensed under GPL v2. <br><hr><br>"
1965 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
1966 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
1967 +"PDFRenderer is licened under the LGPL<br>"
1968 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
1969 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
1970 +"Jazzy is licened under the LGPL<br>"
1971 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
1972 logger.log(logger.HIGH, "Leaving NeverNote.about");
1974 // Hide the entire left hand side
1975 @SuppressWarnings("unused")
1976 private void toggleLeftSide() {
1979 hidden = !menuBar.hideLeftSide.isChecked();
1980 menuBar.hideLeftSide.setChecked(!hidden);
1982 if (notebookTree.isVisible() != hidden)
1983 toggleNotebookWindow();
1984 if (savedSearchTree.isVisible() != hidden)
1985 toggleSavedSearchWindow();
1986 if (tagTree.isVisible() != hidden)
1988 if (attributeTree.isVisible() != hidden)
1989 toggleAttributesWindow();
1990 if (trashTree.isVisible() != hidden)
1991 toggleTrashWindow();
1993 Global.saveWindowVisible("leftPanel", hidden);
1998 //***************************************************************
1999 //***************************************************************
2000 //** These functions deal with the Toolbar
2001 //***************************************************************
2002 //***************************************************************
2003 // Text in the search bar has been cleared
2004 private void searchFieldCleared() {
2005 searchField.setEditText("");
2006 saveNoteIndexWidth();
2008 // text in the search bar changed. We only use this to tell if it was cleared,
2009 // otherwise we trigger off searchFieldChanged.
2010 @SuppressWarnings("unused")
2011 private void searchFieldTextChanged(String text) {
2012 if (text.trim().equals("")) {
2013 searchFieldCleared();
2014 if (searchPerformed) {
2016 listManager.setEnSearch("");
2017 ///// listManager.clearNoteIndexSearch();
2018 //noteIndexUpdated(true);
2019 listManager.loadNotesIndex();
2020 refreshEvernoteNote(true);
2021 noteIndexUpdated(false);
2023 searchPerformed = false;
2026 // Text in the toolbar has changed
2027 private void searchFieldChanged() {
2028 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2030 saveNoteIndexWidth();
2031 String text = searchField.currentText();
2032 listManager.setEnSearch(text.trim());
2033 listManager.loadNotesIndex();
2034 //--->>> noteIndexUpdated(true);
2035 noteIndexUpdated(false);
2036 refreshEvernoteNote(true);
2037 searchPerformed = true;
2038 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2041 // Build the window tool bar
2042 private void setupToolBar() {
2043 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2044 toolBar = addToolBar(tr("Tool Bar"));
2045 menuBar.setupToolBarVisible();
2046 if (!Global.isWindowVisible("toolBar"))
2047 toolBar.setVisible(false);
2049 toolBar.setVisible(true);
2051 prevButton = toolBar.addAction("Previous");
2052 QIcon prevIcon = new QIcon(iconPath+"back.png");
2053 prevButton.setIcon(prevIcon);
2054 prevButton.triggered.connect(this, "previousViewedAction()");
2056 nextButton = toolBar.addAction("Next");
2057 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2058 nextButton.setIcon(nextIcon);
2059 nextButton.triggered.connect(this, "nextViewedAction()");
2061 upButton = toolBar.addAction("Up");
2062 QIcon upIcon = new QIcon(iconPath+"up.png");
2063 upButton.setIcon(upIcon);
2064 upButton.triggered.connect(this, "upAction()");
2066 downButton = toolBar.addAction("Down");
2067 QIcon downIcon = new QIcon(iconPath+"down.png");
2068 downButton.setIcon(downIcon);
2069 downButton.triggered.connect(this, "downAction()");
2071 synchronizeButton = toolBar.addAction("Synchronize");
2072 synchronizeAnimation = new ArrayList<QIcon>();
2073 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-0.png"));
2074 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-1.png"));
2075 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-2.png"));
2076 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-3.png"));
2077 synchronizeButton.setIcon(synchronizeAnimation.get(0));
2078 synchronizeFrame = 0;
2079 synchronizeButton.triggered.connect(this, "evernoteSync()");
2081 printButton = toolBar.addAction("Print");
2082 QIcon printIcon = new QIcon(iconPath+"print.png");
2083 printButton.setIcon(printIcon);
2084 printButton.triggered.connect(this, "printNote()");
2086 tagButton = toolBar.addAction("Tag");
2087 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2088 tagButton.setIcon(tagIcon);
2089 tagButton.triggered.connect(browserWindow, "modifyTags()");
2091 attributeButton = toolBar.addAction("Attributes");
2092 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2093 attributeButton.setIcon(attributeIcon);
2094 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2096 emailButton = toolBar.addAction("Email");
2097 QIcon emailIcon = new QIcon(iconPath+"email.png");
2098 emailButton.setIcon(emailIcon);
2099 emailButton.triggered.connect(this, "emailNote()");
2101 deleteButton = toolBar.addAction("Delete");
2102 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2103 deleteButton.setIcon(deleteIcon);
2104 deleteButton.triggered.connect(this, "deleteNote()");
2106 newButton = toolBar.addAction("New");
2107 QIcon newIcon = new QIcon(iconPath+"new.png");
2108 newButton.triggered.connect(this, "addNote()");
2109 newButton.setIcon(newIcon);
2110 toolBar.addSeparator();
2111 toolBar.addWidget(new QLabel(tr("Quota:")));
2112 toolBar.addWidget(quotaBar);
2113 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2117 zoomSpinner = new QSpinBox();
2118 zoomSpinner.setMinimum(10);
2119 zoomSpinner.setMaximum(1000);
2120 zoomSpinner.setAccelerated(true);
2121 zoomSpinner.setSingleStep(10);
2122 zoomSpinner.setValue(100);
2123 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2124 toolBar.addWidget(new QLabel(tr("Zoom")));
2125 toolBar.addWidget(zoomSpinner);
2127 //toolBar.addWidget(new QLabel(" "));
2128 toolBar.addSeparator();
2129 toolBar.addWidget(new QLabel(tr(" Search:")));
2130 toolBar.addWidget(searchField);
2131 QSizePolicy sizePolicy = new QSizePolicy();
2132 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2133 searchField.setSizePolicy(sizePolicy);
2134 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2136 searchClearButton = toolBar.addAction("Search Clear");
2137 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2138 searchClearButton.setIcon(searchClearIcon);
2139 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2141 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2143 // Update the sychronize button picture
2144 @SuppressWarnings("unused")
2145 private void updateSyncButton() {
2147 if (synchronizeFrame == 4)
2148 synchronizeFrame = 0;
2149 synchronizeButton.setIcon(synchronizeAnimation.get(synchronizeFrame));
2151 // Synchronize with Evernote
2152 @SuppressWarnings("unused")
2153 private void evernoteSync() {
2154 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2155 if (!Global.isConnected)
2157 if (Global.isConnected)
2158 synchronizeAnimationTimer.start(200);
2160 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2162 private void updateQuotaBar() {
2163 long limit = Global.getUploadLimit();
2164 long amount = Global.getUploadAmount();
2165 if (amount>0 && limit>0) {
2166 int percent =(int)(amount*100/limit);
2167 quotaBar.setValue(percent);
2169 quotaBar.setValue(0);
2172 @SuppressWarnings("unused")
2173 private void zoomChanged() {
2174 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2177 //****************************************************************
2178 //****************************************************************
2179 //* System Tray functions
2180 //****************************************************************
2181 //****************************************************************
2182 private void trayToggleVisible() {
2187 if (windowMaximized)
2194 @SuppressWarnings("unused")
2195 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2196 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2197 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2198 trayToggleVisible();
2203 //***************************************************************
2204 //***************************************************************
2205 //** These functions deal with the trash tree
2206 //***************************************************************
2207 //***************************************************************
2208 // Setup the tree containing the trash.
2209 @SuppressWarnings("unused")
2210 private void trashTreeSelection() {
2211 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2213 clearNotebookFilter();
2215 clearAttributeFilter();
2216 clearSavedSearchFilter();
2218 String tempGuid = currentNoteGuid;
2220 // currentNoteGuid = "";
2221 currentNote = new Note();
2222 selectedNoteGUIDs.clear();
2223 listManager.getSelectedNotebooks().clear();
2224 listManager.getSelectedTags().clear();
2225 listManager.setSelectedSavedSearch("");
2226 browserWindow.clear();
2228 // toggle the add buttons
2229 newButton.setEnabled(!newButton.isEnabled());
2230 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2231 menuBar.noteAdd.setVisible(true);
2233 List<QTreeWidgetItem> selections = trashTree.selectedItems();
2234 if (selections.size() == 0) {
2235 currentNoteGuid = trashNoteGuid;
2236 trashNoteGuid = tempGuid;
2237 Global.showDeleted = false;
2238 menuBar.noteRestoreAction.setEnabled(false);
2239 menuBar.noteRestoreAction.setVisible(false);
2242 currentNoteGuid = trashNoteGuid;
2243 trashNoteGuid = tempGuid;
2244 menuBar.noteRestoreAction.setEnabled(true);
2245 menuBar.noteRestoreAction.setVisible(true);
2246 Global.showDeleted = true;
2248 listManager.loadNotesIndex();
2249 noteIndexUpdated(false);
2250 //// browserWindow.setEnabled(newButton.isEnabled());
2251 browserWindow.setReadOnly(!newButton.isEnabled());
2252 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2254 // Empty the trash file
2255 @SuppressWarnings("unused")
2256 private void emptyTrash() {
2257 // browserWindow.clear();
2258 listManager.emptyTrash();
2259 if (trashTree.selectedItems().size() > 0) {
2260 listManager.getSelectedNotebooks().clear();
2261 listManager.getSelectedTags().clear();
2262 listManager.setSelectedSavedSearch("");
2263 newButton.setEnabled(!newButton.isEnabled());
2264 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2265 menuBar.noteAdd.setVisible(true);
2266 browserWindow.clear();
2269 clearNotebookFilter();
2270 clearSavedSearchFilter();
2271 clearAttributeFilter();
2273 Global.showDeleted = false;
2274 menuBar.noteRestoreAction.setEnabled(false);
2275 menuBar.noteRestoreAction.setVisible(false);
2277 listManager.loadNotesIndex();
2278 //--->>> noteIndexUpdated(true);
2279 noteIndexUpdated(false);
2282 // Show/Hide trash window
2283 private void toggleTrashWindow() {
2284 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2285 if (trashTree.isVisible())
2289 menuBar.hideTrash.setChecked(trashTree.isVisible());
2291 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2292 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2294 private void clearTrashFilter() {
2295 Global.showDeleted = false;
2296 newButton.setEnabled(true);
2297 menuBar.noteAdd.setEnabled(true);
2298 menuBar.noteAdd.setVisible(true);
2299 trashTree.blockSignals(true);
2300 trashTree.clearSelection();
2301 trashTree.blockSignals(false);
2306 //***************************************************************
2307 //***************************************************************
2308 //** These functions deal with connection settings
2309 //***************************************************************
2310 //***************************************************************
2311 // SyncRunner had a problem and things are disconnected
2312 @SuppressWarnings("unused")
2313 private void remoteErrorDisconnect() {
2314 menuBar.connectAction.setText(tr("Connect"));
2315 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2316 menuBar.synchronizeAction.setEnabled(false);
2317 synchronizeAnimationTimer.stop();
2320 // Do a manual connect/disconnect
2321 private void remoteConnect() {
2322 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2324 if (Global.isConnected) {
2325 Global.isConnected = false;
2326 syncRunner.enDisconnect();
2327 setupConnectMenuOptions();
2332 AESEncrypter aes = new AESEncrypter();
2334 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
2335 } catch (FileNotFoundException e) {
2336 // File not found, so we'll just get empty strings anyway.
2338 String userid = aes.getUserid();
2339 String password = aes.getPassword();
2340 if (!userid.equals("") && !password.equals("")) {
2341 Global.username = userid;
2342 Global.password = password;
2345 // Show the login dialog box
2346 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
2347 LoginDialog login = new LoginDialog();
2350 if (!login.okPressed()) {
2354 Global.username = login.getUserid();
2355 Global.password = login.getPassword();
2357 syncRunner.username = Global.username;
2358 syncRunner.password = Global.password;
2359 syncRunner.userStoreUrl = Global.userStoreUrl;
2360 syncRunner.noteStoreUrl = Global.noteStoreUrl;
2361 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
2362 syncRunner.enConnect();
2363 Global.isConnected = syncRunner.isConnected;
2365 setupConnectMenuOptions();
2366 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
2368 private void setupConnectMenuOptions() {
2369 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
2370 if (!Global.isConnected) {
2371 menuBar.connectAction.setText(tr("Connect"));
2372 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2373 menuBar.synchronizeAction.setEnabled(false);
2375 menuBar.connectAction.setText(tr("Disconnect"));
2376 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
2377 menuBar.synchronizeAction.setEnabled(true);
2379 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
2384 //***************************************************************
2385 //***************************************************************
2386 //** These functions deal with the GUI Attribute tree
2387 //***************************************************************
2388 //***************************************************************
2389 @SuppressWarnings("unused")
2390 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
2393 clearNotebookFilter();
2395 clearSavedSearchFilter();
2397 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
2398 if (item.childCount() > 0) {
2399 item.setSelected(false);
2401 Global.createdBeforeFilter.reset();
2402 Global.createdSinceFilter.reset();
2403 Global.changedBeforeFilter.reset();
2404 Global.changedSinceFilter.reset();
2405 Global.containsFilter.reset();
2406 attributeTreeSelected = item;
2407 DateAttributeFilterTable f = null;
2408 f = findDateAttributeFilterTable(item.parent());
2410 f.select(item.parent().indexOfChild(item));
2412 Global.containsFilter.select(item.parent().indexOfChild(item));
2415 listManager.loadNotesIndex();
2416 noteIndexUpdated(false);
2419 attributeTreeSelected = null;
2420 item.setSelected(false);
2421 Global.createdBeforeFilter.reset();
2422 Global.createdSinceFilter.reset();
2423 Global.changedBeforeFilter.reset();
2424 Global.changedSinceFilter.reset();
2425 Global.containsFilter.reset();
2426 listManager.loadNotesIndex();
2427 noteIndexUpdated(false);
2429 // This determines what attribute filter we need, depending upon the selection
2430 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
2431 if (w.parent() != null && w.childCount() > 0) {
2432 QTreeWidgetItem parent = w.parent();
2433 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
2434 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2435 return Global.createdSinceFilter;
2436 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
2437 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2438 return Global.createdBeforeFilter;
2439 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
2440 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2441 return Global.changedSinceFilter;
2442 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
2443 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2444 return Global.changedBeforeFilter;
2449 // Show/Hide attribute search window
2450 private void toggleAttributesWindow() {
2451 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
2452 if (attributeTree.isVisible())
2453 attributeTree.hide();
2455 attributeTree.show();
2456 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
2458 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
2459 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
2461 private void clearAttributeFilter() {
2462 Global.createdBeforeFilter.reset();
2463 Global.createdSinceFilter.reset();
2464 Global.changedBeforeFilter.reset();
2465 Global.changedSinceFilter.reset();
2466 Global.containsFilter.reset();
2467 attributeTreeSelected = null;
2468 attributeTree.blockSignals(true);
2469 attributeTree.clearSelection();
2470 attributeTree.blockSignals(false);
2474 //***************************************************************
2475 //***************************************************************
2476 //** These functions deal with the GUI Note index table
2477 //***************************************************************
2478 //***************************************************************
2479 // Initialize the note list table
2480 private void initializeNoteTable() {
2481 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
2482 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
2483 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
2484 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
2486 // Show/Hide trash window
2487 @SuppressWarnings("unused")
2488 private void toggleNoteListWindow() {
2489 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
2490 if (noteTableView.isVisible())
2491 noteTableView.hide();
2493 noteTableView.show();
2494 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
2496 Global.saveWindowVisible("noteList", noteTableView.isVisible());
2497 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
2499 // Handle the event that a user selects a note from the table
2500 @SuppressWarnings("unused")
2501 private void noteTableSelection() {
2502 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
2504 if (historyGuids.size() == 0) {
2505 historyGuids.add(currentNoteGuid);
2506 historyPosition = 1;
2508 noteTableView.showColumn(Global.noteTableGuidPosition);
2510 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2511 noteTableView.hideColumn(Global.noteTableGuidPosition);
2513 if (selections.size() > 0) {
2515 menuBar.noteDuplicateAction.setEnabled(true);
2516 menuBar.noteOnlineHistoryAction.setEnabled(true);
2517 menuBar.noteMergeAction.setEnabled(true);
2518 selectedNoteGUIDs.clear();
2519 if (selections.size() != 1 || Global.showDeleted) {
2520 menuBar.noteDuplicateAction.setEnabled(false);
2522 if (selections.size() != 1 || !Global.isConnected) {
2523 menuBar.noteOnlineHistoryAction.setEnabled(false);
2525 if (selections.size() == 1) {
2526 menuBar.noteMergeAction.setEnabled(false);
2528 for (int i=0; i<selections.size(); i++) {
2529 int row = selections.get(i).row();
2531 upButton.setEnabled(false);
2533 upButton.setEnabled(true);
2534 if (row < listManager.getNoteTableModel().rowCount()-1)
2535 downButton.setEnabled(true);
2537 downButton.setEnabled(false);
2538 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
2539 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
2540 currentNoteGuid = (String)ix.values().toArray()[0];
2541 selectedNoteGUIDs.add(currentNoteGuid);
2545 nextButton.setEnabled(true);
2546 prevButton.setEnabled(true);
2548 int endPosition = historyGuids.size()-1;
2549 for (int j=historyPosition; j<=endPosition; j++) {
2550 historyGuids.remove(historyGuids.size()-1);
2552 historyGuids.add(currentNoteGuid);
2553 historyPosition = historyGuids.size();
2555 if (historyPosition <= 1)
2556 prevButton.setEnabled(false);
2557 if (historyPosition == historyGuids.size())
2558 nextButton.setEnabled(false);
2560 fromHistory = false;
2561 scrollToGuid(currentNoteGuid);
2562 refreshEvernoteNote(true);
2563 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
2565 // Trigger a refresh when the note db has been updated
2566 private void noteIndexUpdated(boolean reload) {
2567 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
2569 refreshEvernoteNoteList();
2570 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
2571 noteTableView.load(reload);
2572 scrollToGuid(currentNoteGuid);
2573 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
2575 // Called when the list of notes is updated
2576 private void refreshEvernoteNoteList() {
2577 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
2578 browserWindow.setDisabled(false);
2579 if (selectedNoteGUIDs == null)
2580 selectedNoteGUIDs = new ArrayList<String>();
2581 selectedNoteGUIDs.clear(); // clear out old entries
2583 String saveCurrentNoteGuid = new String();
2584 String tempNoteGuid = new String();
2586 historyGuids.clear();
2587 historyPosition = 0;
2588 prevButton.setEnabled(false);
2589 nextButton.setEnabled(false);
2591 if (currentNoteGuid == null)
2592 currentNoteGuid = new String();
2594 for (Note note : listManager.getNoteIndex()) {
2595 tempNoteGuid = note.getGuid();
2596 if (currentNoteGuid.equals(tempNoteGuid)) {
2597 saveCurrentNoteGuid = new String(tempNoteGuid);
2601 if (listManager.getNoteIndex().size() == 0) {
2602 currentNoteGuid = "";
2604 browserWindow.clear();
2605 browserWindow.setDisabled(true);
2608 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() >0) {
2609 currentNoteGuid = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1).getGuid();
2610 currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
2611 refreshEvernoteNote(true);
2613 refreshEvernoteNote(false);
2617 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
2619 // Called when the previous arrow button is clicked
2620 @SuppressWarnings("unused")
2621 private void previousViewedAction() {
2622 if (!prevButton.isEnabled())
2624 if (historyPosition == 0)
2627 if (historyPosition <= 0)
2629 String historyGuid = historyGuids.get(historyPosition-1);
2631 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2632 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
2633 if (modelIndex != null) {
2634 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2635 String tableGuid = (String)ix.values().toArray()[0];
2636 if (tableGuid.equals(historyGuid)) {
2637 noteTableView.selectRow(i);
2643 @SuppressWarnings("unused")
2644 private void nextViewedAction() {
2645 if (!nextButton.isEnabled())
2647 String historyGuid = historyGuids.get(historyPosition);
2650 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2651 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
2652 if (modelIndex != null) {
2653 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2654 String tableGuid = (String)ix.values().toArray()[0];
2655 if (tableGuid.equals(historyGuid)) {
2656 noteTableView.selectRow(i);
2662 // Called when the up arrow is clicked
2663 @SuppressWarnings("unused")
2664 private void upAction() {
2665 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2666 int row = selections.get(0).row();
2668 noteTableView.selectRow(row-1);
2671 // Called when the down arrow is clicked
2672 @SuppressWarnings("unused")
2673 private void downAction() {
2674 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2675 int row = selections.get(0).row();
2676 int max = listManager.getNoteTableModel().rowCount();
2678 noteTableView.selectRow(row+1);
2681 // Update a tag string for a specific note in the list
2682 @SuppressWarnings("unused")
2683 private void updateListTags(String guid, List<String> tags) {
2684 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
2685 StringBuffer tagBuffer = new StringBuffer();
2686 for (int i=0; i<tags.size(); i++) {
2687 tagBuffer.append(tags.get(i));
2688 if (i<tags.size()-1)
2689 tagBuffer.append(", ");
2692 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2693 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2694 if (modelIndex != null) {
2695 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2696 String tableGuid = (String)ix.values().toArray()[0];
2697 if (tableGuid.equals(guid)) {
2698 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
2699 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2704 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
2706 // Update a title for a specific note in the list
2707 @SuppressWarnings("unused")
2708 private void updateListAuthor(String guid, String author) {
2709 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2711 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2712 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2713 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2714 if (modelIndex != null) {
2715 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2716 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2717 String tableGuid = (String)ix.values().toArray()[0];
2718 if (tableGuid.equals(guid)) {
2719 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
2720 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2725 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2727 private void updateListNoteNotebook(String guid, String notebook) {
2728 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
2729 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
2730 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
2732 // Update a title for a specific note in the list
2733 @SuppressWarnings("unused")
2734 private void updateListSourceUrl(String guid, String url) {
2735 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2737 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2738 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2739 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2740 if (modelIndex != null) {
2741 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2742 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2743 String tableGuid = (String)ix.values().toArray()[0];
2744 if (tableGuid.equals(guid)) {
2745 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2746 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
2751 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2753 private void updateListGuid(String oldGuid, String newGuid) {
2754 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2756 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2757 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2758 if (modelIndex != null) {
2759 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2760 String tableGuid = (String)ix.values().toArray()[0];
2761 if (tableGuid.equals(oldGuid)) {
2762 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
2763 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2768 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2770 private void updateListTagName(String guid) {
2771 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2773 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2774 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2775 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2777 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2778 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2779 if (modelIndex != null) {
2780 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2781 String noteGuid = (String)ix.values().toArray()[0];
2782 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2783 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2784 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2785 i=listManager.getNoteTableModel().rowCount();
2791 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2793 private void removeListTagName(String guid) {
2794 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2796 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2797 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2798 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
2799 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
2800 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
2803 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2804 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2805 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2806 if (modelIndex != null) {
2807 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2808 String noteGuid = (String)ix.values().toArray()[0];
2809 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2810 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2811 // listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2812 i=listManager.getNoteTableModel().rowCount();
2818 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2820 private void updateListNotebookName(String oldName, String newName) {
2821 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
2823 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2824 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
2825 if (modelIndex != null) {
2826 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2827 String tableName = (String)ix.values().toArray()[0];
2828 if (tableName.equalsIgnoreCase(oldName)) {
2829 // listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2830 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
2834 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
2836 @SuppressWarnings("unused")
2837 private void updateListDateCreated(String guid, QDateTime date) {
2838 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
2840 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2841 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2842 if (modelIndex != null) {
2843 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2844 String tableGuid = (String)ix.values().toArray()[0];
2845 if (tableGuid.equals(guid)) {
2846 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2851 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2853 @SuppressWarnings("unused")
2854 private void updateListDateSubject(String guid, QDateTime date) {
2855 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
2857 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2858 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2859 if (modelIndex != null) {
2860 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2861 String tableGuid = (String)ix.values().toArray()[0];
2862 if (tableGuid.equals(guid)) {
2863 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2864 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2869 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2871 @SuppressWarnings("unused")
2872 private void updateListDateChanged(String guid, QDateTime date) {
2873 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2875 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2876 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2877 if (modelIndex != null) {
2878 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2879 String tableGuid = (String)ix.values().toArray()[0];
2880 if (tableGuid.equals(guid)) {
2881 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2882 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2887 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2889 private void updateListDateChanged() {
2890 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2891 QDateTime date = new QDateTime(QDateTime.currentDateTime());
2892 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2893 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2894 if (modelIndex != null) {
2895 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2896 String tableGuid = (String)ix.values().toArray()[0];
2897 if (tableGuid.equals(currentNoteGuid)) {
2898 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2899 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2904 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2907 @SuppressWarnings("unused")
2908 private void scrollToCurrentGuid() {
2909 //scrollToGuid(currentNoteGuid);
2910 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2911 if (selections.size() == 0)
2913 QModelIndex index = selections.get(0);
2914 int row = selections.get(0).row();
2915 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
2918 // Scroll to a particular index item
2919 private void scrollToGuid(String guid) {
2920 if (currentNote == null || guid == null)
2922 if (currentNote.isActive() && Global.showDeleted) {
2923 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2924 if (!listManager.getNoteIndex().get(i).isActive()) {
2925 currentNote = listManager.getNoteIndex().get(i);
2926 currentNoteGuid = currentNote.getGuid();
2927 i = listManager.getNoteIndex().size();
2932 if (!currentNote.isActive() && !Global.showDeleted) {
2933 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2934 if (listManager.getNoteIndex().get(i).isActive()) {
2935 currentNote = listManager.getNoteIndex().get(i);
2936 currentNoteGuid = currentNote.getGuid();
2937 i = listManager.getNoteIndex().size();
2943 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2944 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
2945 if (currentNoteGuid.equals(index.data())) {
2946 // noteTableView.setCurrentIndex(index);
2947 noteTableView.selectRow(i);
2948 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
2949 i=listManager.getNoteTableModel().rowCount();
2953 // Show/Hide columns
2954 private void showColumns() {
2955 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
2956 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
2957 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
2958 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
2959 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
2960 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
2961 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
2962 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
2964 // Open a separate window
2965 @SuppressWarnings("unused")
2966 private void listDoubleClick() {
2969 // Title color has changed
2970 @SuppressWarnings("unused")
2971 private void titleColorChanged(Integer color) {
2972 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2974 QColor backgroundColor = new QColor();
2975 QColor foregroundColor = new QColor(QColor.black);
2976 backgroundColor.setRgb(color);
2978 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
2979 foregroundColor.setRgb(QColor.white.rgb());
2981 if (selectedNoteGUIDs.size() == 0)
2982 selectedNoteGUIDs.add(currentNoteGuid);
2984 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
2985 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2986 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2987 if (modelIndex != null) {
2988 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2989 String tableGuid = (String)ix.values().toArray()[0];
2990 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
2991 for (int k=0; k<Global.noteTableColumnCount; k++) {
2992 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
2993 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
2994 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
2996 i=listManager.getNoteTableModel().rowCount();
3001 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3005 //***************************************************************
3006 //***************************************************************
3007 //** These functions deal with Note specific things
3008 //***************************************************************
3009 //***************************************************************
3010 @SuppressWarnings("unused")
3011 private void setNoteDirty() {
3012 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
3014 // If the note is dirty, then it is unsynchronized by default.
3018 // Set the note as dirty and check if its status is synchronized in the display table
3020 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
3021 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
3025 // If this wasn't already marked as unsynchronized, then we need to update the table
3026 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
3027 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
3028 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3029 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3030 if (modelIndex != null) {
3031 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3032 String tableGuid = (String)ix.values().toArray()[0];
3033 if (tableGuid.equals(currentNoteGuid)) {
3034 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3040 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
3042 private void saveNote() {
3043 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
3045 logger.log(logger.EXTREME, "Note is dirty.");
3048 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
3049 preview.finished.connect(this, "saveThumbnail(String)");
3050 preview.setContent(browserWindow.getContent());
3052 logger.log(logger.EXTREME, "Saving to cache");
3053 QTextCodec codec = QTextCodec.codecForLocale();
3054 // QTextDecoder decoder = codec.makeDecoder();
3055 codec = QTextCodec.codecForName("UTF-8");
3056 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
3057 noteCache.put(currentNoteGuid, unicode.toString());
3059 logger.log(logger.EXTREME, "updating list manager");
3060 listManager.updateNoteContent(currentNoteGuid, browserWindow.getContent());
3061 // noteCache.put(currentNoteGuid, browserWindow.getContent());
3062 logger.log(logger.EXTREME, "Updating title");
3063 listManager.updateNoteTitle(currentNoteGuid, browserWindow.getTitle());
3064 updateListDateChanged();
3066 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
3067 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3068 if (listManager.getNoteIndex().get(i).getGuid().equals(currentNoteGuid)) {
3069 currentNote = listManager.getNoteIndex().get(i);
3070 i = listManager.getNoteIndex().size();
3077 // Get a note from Evernote (and put it in the browser)
3078 private void refreshEvernoteNote(boolean reload) {
3079 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
3080 if (Global.disableViewing) {
3081 browserWindow.setEnabled(false);
3085 if (!Global.showDeleted)
3086 browserWindow.setReadOnly(false);
3087 Global.cryptCounter =0;
3088 if (currentNoteGuid.equals("")) {
3089 browserWindow.setReadOnly(true);
3096 browserWindow.loadingData(true);
3098 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
3099 if (currentNote == null)
3102 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3103 QByteArray js = new QByteArray();
3104 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
3105 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
3106 js.append("<style type=\"text/css\">en-crypt-temp { border-style:solid; border-color:blue; padding:0.5mm 0.5mm 0.5mm 0.5mm; }</style>");
3107 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
3108 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
3109 js.append("</head>");
3110 js.append(rebuildNoteHTML(currentNoteGuid, currentNote.getContent()));
3111 js.append("</HTML>");
3112 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
3113 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
3114 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
3115 browserWindow.getBrowser().setContent(js);
3116 noteCache.put(currentNoteGuid, js.toString());
3117 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3118 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
3119 preview.finished.connect(this, "saveThumbnail(String)");
3120 preview.setContent(js.toString());
3123 logger.log(logger.HIGH, "Note content is being pulled from the cache");
3124 String cachedContent = modifyCachedTodoTags(noteCache.get(currentNoteGuid));
3125 browserWindow.getBrowser().setContent(new QByteArray(cachedContent));
3128 browserWindow.getBrowser().page().setContentEditable(!inkNote); // We don't allow editing of ink notes
3129 browserWindow.setNote(currentNote);
3131 // Build a list of non-closed notebooks
3132 List<Notebook> nbooks = new ArrayList<Notebook>();
3133 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3134 boolean found=false;
3135 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3136 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
3140 nbooks.add(listManager.getNotebookIndex().get(i));
3143 browserWindow.setNotebookList(nbooks);
3144 browserWindow.setTitle(currentNote.getTitle());
3145 browserWindow.setTag(getTagNamesForNote(currentNote));
3146 browserWindow.setAuthor(currentNote.getAttributes().getAuthor());
3148 browserWindow.setAltered(currentNote.getUpdated());
3149 browserWindow.setCreation(currentNote.getCreated());
3150 if (currentNote.getAttributes().getSubjectDate() > 0)
3151 browserWindow.setSubjectDate(currentNote.getAttributes().getSubjectDate());
3153 browserWindow.setSubjectDate(currentNote.getCreated());
3154 browserWindow.setUrl(currentNote.getAttributes().getSourceURL());
3155 browserWindow.setAllTags(listManager.getTagIndex());
3156 browserWindow.setCurrentTags(currentNote.getTagNames());
3158 scrollToGuid(currentNoteGuid);
3160 browserWindow.loadingData(false);
3161 if (thumbnailViewer.isActiveWindow())
3164 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
3166 // Save a generated thumbnail
3167 @SuppressWarnings("unused")
3168 private void saveThumbnail(String guid) {
3169 QFile tFile = new QFile(Global.getFileManager().getResDirPath("thumbnail-" + guid + ".png"));
3170 tFile.open(OpenModeFlag.ReadOnly);
3171 QByteArray imgBytes = tFile.readAll();
3173 conn.getNoteTable().setThumbnail(guid, imgBytes);
3174 conn.getNoteTable().setThumbnailNeeded(guid, false);
3175 thumbnailViewer.setThumbnail(QImage.fromData(imgBytes));
3176 if (thumbnailViewer.isVisible())
3177 thumbnailViewer.showFullScreen();
3180 QByteArray img2 = new QByteArray(conn.getNoteTable().getThumbnail(guid));
3181 QFile file = new QFile(Global.currentDir+"res/aaaa.png");
3182 file.open(OpenModeFlag.WriteOnly);
3187 // Show/Hide note information
3188 @SuppressWarnings("unused")
3189 private void toggleNoteInformation() {
3190 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
3191 browserWindow.toggleInformation();
3192 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
3193 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
3195 // Listener triggered when a print button is pressed
3196 @SuppressWarnings("unused")
3197 private void printNote() {
3198 logger.log(logger.HIGH, "Entering NeverNote.printNote");
3200 QPrintDialog dialog = new QPrintDialog();
3201 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
3202 QPrinter printer = dialog.printer();
3203 browserWindow.getBrowser().print(printer);
3205 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
3208 // Listener triggered when the email button is pressed
3209 @SuppressWarnings("unused")
3210 private void emailNote() {
3211 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
3213 if (Desktop.isDesktopSupported()) {
3214 Desktop desktop = Desktop.getDesktop();
3216 String text2 = browserWindow.getContentsToEmail();
3217 QUrl url = new QUrl("mailto:");
3218 url.addQueryItem("subject", currentNote.getTitle());
3219 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
3220 url.addQueryItem("body", text2);
3221 QDesktopServices.openUrl(url);
3225 if (desktop.isSupported(Desktop.Action.MAIL)) {
3226 URI uriMailTo = null;
3228 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
3229 String text = browserWindow.getContentsToEmail();
3230 //text = "<b>" +text +"</b>";
3231 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3232 +"&BODY=" +text, null);
3233 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3234 +"&ATTACHMENT=d:/test.pdf", null);
3235 desktop.mail(uriMailTo);
3236 } catch (URISyntaxException e) {
3237 e.printStackTrace();
3238 } catch (IOException e) {
3239 e.printStackTrace();
3246 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
3248 // Reindex all notes
3249 @SuppressWarnings("unused")
3250 private void fullReindex() {
3251 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
3252 // If we are deleting non-trash notes
3253 if (currentNote.getDeleted() == 0) {
3254 if (QMessageBox.question(this, tr("Confirmation"), tr("This will cause all notes & attachments to be reindexed, "+
3255 "but please be aware that depending upon the size of your database updating all these records " +
3256 "can be time consuming and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
3257 QMessageBox.StandardButton.Yes,
3258 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3263 setMessage(tr("Marking notes for reindex."));
3264 conn.getNoteTable().reindexAllNotes();
3265 conn.getNoteTable().noteResourceTable.reindexAll();
3266 setMessage(tr("Database will be reindexed."));
3268 logger.log(logger.HIGH, "Leaving NeverNote.fullRefresh");
3270 // Listener when a user wants to reindex a specific note
3271 @SuppressWarnings("unused")
3272 private void reindexNote() {
3273 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
3274 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3275 conn.getNoteTable().setIndexNeeded(selectedNoteGUIDs.get(i), true);
3277 if (selectedNotebookGUIDs.size() > 1)
3278 setMessage(tr("Notes will be reindexed."));
3280 setMessage(tr("Note will be reindexed."));
3281 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
3284 @SuppressWarnings("unused")
3285 private void deleteNote() {
3286 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
3287 if (currentNote == null)
3289 if (currentNoteGuid.equals(""))
3292 // If we are deleting non-trash notes
3293 if (currentNote.isActive()) {
3294 if (Global.verifyDelete()) {
3295 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
3296 QMessageBox.StandardButton.Yes,
3297 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3301 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3302 selectedNoteGUIDs.add(currentNoteGuid);
3303 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3304 listManager.deleteNote(selectedNoteGUIDs.get(i));
3307 // If we are deleting from the trash.
3308 if (Global.verifyDelete()) {
3309 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
3310 QMessageBox.StandardButton.Yes,
3311 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
3315 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3316 selectedNoteGUIDs.add(currentNoteGuid);
3317 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
3318 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
3319 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
3320 if (modelIndex != null) {
3321 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3322 String tableGuid = (String)ix.values().toArray()[0];
3323 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
3324 listManager.getNoteTableModel().removeRow(j);
3329 listManager.expungeNote(selectedNoteGUIDs.get(i));
3332 currentNoteGuid = "";
3333 listManager.loadNotesIndex();
3334 noteIndexUpdated(false);
3335 refreshEvernoteNote(true);
3336 scrollToGuid(currentNoteGuid);
3337 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
3340 @SuppressWarnings("unused")
3341 private void addNote() {
3342 logger.log(logger.HIGH, "Inside NeverNote.addNote");
3343 // browserWindow.setEnabled(true);
3344 browserWindow.setReadOnly(false);
3346 Calendar currentTime = new GregorianCalendar();
3347 String noteString = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
3348 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
3349 "<en-note>\n<br clear=\"none\" /></en-note>");
3351 Long l = new Long(currentTime.getTimeInMillis());
3352 String randint = new String(Long.toString(l));
3354 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
3356 // for the first non-archived notebook. Finally, if nothing else we
3357 // pick the first notebook in the list.
3358 String notebook = null;
3359 listManager.getNotebookIndex().get(0).getGuid();
3360 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
3361 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
3362 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
3363 notebook = currentSelectedNotebook.text(2);
3365 boolean found = false;
3366 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
3367 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3368 boolean match = false;
3369 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3370 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
3372 j = listManager.getArchiveNotebookIndex().size();
3376 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
3378 // Now we have a list of good notebooks, so we can look for the default
3380 for (int i=0; i<goodNotebooks.size(); i++) {
3381 if (goodNotebooks.get(i).isDefaultNotebook()) {
3382 notebook = goodNotebooks.get(i).getGuid();
3384 i = goodNotebooks.size();
3388 if (goodNotebooks.size() > 0 && !found)
3389 notebook = goodNotebooks.get(0).getGuid();
3392 notebook = listManager.getNotebookIndex().get(0).getGuid();
3395 Note newNote = new Note();
3396 newNote.setUpdateSequenceNum(0);
3397 newNote.setGuid(randint);
3398 newNote.setNotebookGuid(notebook);
3399 newNote.setTitle("");
3400 newNote.setContent(noteString);
3401 newNote.setDeleted(0);
3402 newNote.setCreated(System.currentTimeMillis());
3403 newNote.setUpdated(System.currentTimeMillis());
3404 newNote.setActive(true);
3405 NoteAttributes na = new NoteAttributes();
3406 na.setLatitude(0.0);
3407 na.setLongitude(0.0);
3408 na.setAltitude(0.0);
3409 newNote.setAttributes(new NoteAttributes());
3410 newNote.setTagGuids(new ArrayList<String>());
3411 newNote.setTagNames(new ArrayList<String>());
3413 // If new notes are to be created based upon the selected tags, then we need to assign the tags
3414 if (Global.newNoteWithSelectedTags()) {
3415 List<QTreeWidgetItem> selections = tagTree.selectedItems();
3416 QTreeWidgetItem currentSelection;
3417 for (int i=0; i<selections.size(); i++) {
3418 currentSelection = selections.get(i);
3419 newNote.getTagGuids().add(currentSelection.text(2));
3420 newNote.getTagNames().add(currentSelection.text(0));
3424 conn.getNoteTable().addNote(newNote, true);
3425 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3426 listManager.addNote(newNote);
3427 // noteTableView.insertRow(newNote, true, -1);
3429 currentNote = newNote;
3430 currentNoteGuid = currentNote.getGuid();
3431 refreshEvernoteNote(true);
3432 listManager.countNotebookResults(listManager.getNoteIndex());
3433 browserWindow.titleLabel.setFocus();
3434 browserWindow.titleLabel.selectAll();
3435 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
3436 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
3438 // Restore a note from the trash;
3439 @SuppressWarnings("unused")
3440 private void restoreNote() {
3442 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3443 selectedNoteGUIDs.add(currentNoteGuid);
3444 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3445 listManager.restoreNote(selectedNoteGUIDs.get(i));
3447 currentNoteGuid = "";
3448 listManager.loadNotesIndex();
3449 noteIndexUpdated(false);
3452 // Search a note for specific txt
3453 @SuppressWarnings("unused")
3454 private void findText() {
3456 find.setFocusOnTextField();
3458 @SuppressWarnings("unused")
3459 private void doFindText() {
3460 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
3463 // Signal received that note content has changed. Normally we just need the guid to remove
3464 // it from the cache.
3465 @SuppressWarnings("unused")
3466 private void invalidateNoteCache(String guid, String content) {
3467 String v = noteCache.remove(guid);
3468 if (content != null) {
3469 //noteCache.put(guid, content);
3472 // Signal received that a note guid has changed
3473 @SuppressWarnings("unused")
3474 private void noteGuidChanged(String oldGuid, String newGuid) {
3475 if (noteCache.containsKey(oldGuid)) {
3476 String cache = noteCache.get(oldGuid);
3477 noteCache.put(newGuid, cache);
3478 noteCache.remove(oldGuid);
3480 listManager.updateNoteGuid(oldGuid, newGuid, false);
3481 if (currentNoteGuid.equals(oldGuid)) {
3482 if (currentNote != null)
3483 currentNote.setGuid(newGuid);
3484 currentNoteGuid = newGuid;
3486 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3487 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
3488 noteTableView.proxyModel.addGuid(newGuid);
3489 i=listManager.getNoteIndex().size();
3492 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
3493 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
3494 listManager.getNoteTableModel().titleColors.put(newGuid, color);
3495 listManager.getNoteTableModel().titleColors.remove(oldGuid);
3499 // Toggle the note editor button bar
3500 private void toggleEditorButtonBar() {
3501 if (browserWindow.buttonsVisible) {
3502 browserWindow.hideButtons();
3503 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
3504 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3506 browserWindow.buttonsVisible = true;
3507 showEditorButtons();
3509 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3511 // Show editor buttons
3512 private void showEditorButtons() {
3513 browserWindow.buttonLayout.setVisible(true);
3514 browserWindow.undoAction.setVisible(false);
3516 browserWindow.undoButton.setVisible(false);
3518 browserWindow.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
3519 browserWindow.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
3520 browserWindow.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
3521 browserWindow.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
3522 browserWindow.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
3523 browserWindow.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
3524 browserWindow.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
3525 browserWindow.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
3526 browserWindow.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
3527 browserWindow.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
3528 browserWindow.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
3529 browserWindow.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
3530 browserWindow.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
3531 browserWindow.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
3532 browserWindow.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
3533 browserWindow.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
3534 browserWindow.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
3535 browserWindow.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
3536 browserWindow.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
3537 browserWindow.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
3538 browserWindow.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
3540 private void duplicateNote(String guid) {
3542 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
3543 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
3544 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
3545 oldNote.setResources(resList);
3546 duplicateNote(oldNote);
3548 private void duplicateNote(Note oldNote) {
3550 // Now that we have a good notebook guid, we need to move the conflicting note
3551 // to the local notebook
3552 Calendar currentTime = new GregorianCalendar();
3553 Long l = new Long(currentTime.getTimeInMillis());
3554 String newGuid = new String(Long.toString(l));
3556 Note newNote = oldNote.deepCopy();
3557 newNote.setUpdateSequenceNum(0);
3558 newNote.setGuid(newGuid);
3559 newNote.setDeleted(0);
3560 newNote.setActive(true);
3561 List<Resource> resList = oldNote.getResources();
3562 if (resList == null)
3563 resList = new ArrayList<Resource>();
3565 for (int i=0; i<resList.size(); i++) {
3567 while (l == prevGuid) {
3568 currentTime = new GregorianCalendar();
3569 l = new Long(currentTime.getTimeInMillis());
3572 String newResGuid = new String(Long.toString(l));
3573 resList.get(i).setNoteGuid(newGuid);
3574 resList.get(i).setGuid(newResGuid);
3575 resList.get(i).setUpdateSequenceNum(0);
3576 resList.get(i).setActive(true);
3577 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
3579 newNote.setResources(resList);
3580 listManager.addNote(newNote);
3581 conn.getNoteTable().addNote(newNote, true);
3582 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3583 noteTableView.insertRow(newNote, true, -1);
3584 listManager.countNotebookResults(listManager.getNoteIndex());
3588 @SuppressWarnings("unused")
3589 private void mergeNotes() {
3590 logger.log(logger.HIGH, "Merging notes");
3593 String masterGuid = null;
3594 List<String> sources = new ArrayList<String>();
3596 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
3597 int r = noteTableView.selectionModel().selectedRows().get(i).row();
3598 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
3599 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3601 masterGuid = (String)ix.values().toArray()[0];
3603 sources.add((String)ix.values().toArray()[0]);
3606 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
3607 logger.log(logger.EXTREME, "Children count: "+sources.size());
3608 mergeNoteContents(masterGuid, sources);
3609 currentNoteGuid = masterGuid;
3610 noteIndexUpdated(false);
3611 refreshEvernoteNote(true);
3614 private void mergeNoteContents(String targetGuid, List<String> sources) {
3615 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
3616 String newContent = target.getContent();
3617 newContent = newContent.replace("</en-note>", "<br></br>");
3619 for (int i=0; i<sources.size(); i++) {
3620 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
3621 if (source.isSetTitle()) {
3622 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
3624 String sourceContent = source.getContent();
3625 logger.log(logger.EXTREME, "Merging contents into note");
3626 logger.log(logger.EXTREME, sourceContent);
3627 logger.log(logger.EXTREME, "End of content");
3628 int startOfNote = sourceContent.indexOf("<en-note>");
3629 sourceContent = sourceContent.substring(startOfNote+9);
3630 int endOfNote = sourceContent.indexOf("</en-note>");
3631 sourceContent = sourceContent.substring(0,endOfNote);
3632 newContent = newContent + sourceContent;
3633 logger.log(logger.EXTREME, "New note content");
3634 logger.log(logger.EXTREME, newContent);
3635 logger.log(logger.EXTREME, "End of content");
3636 for (int j=0; j<source.getResourcesSize(); j++) {
3637 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
3638 Resource r = source.getResources().get(j);
3639 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3641 Calendar currentTime = new GregorianCalendar();
3642 Long l = new Long(currentTime.getTimeInMillis());
3646 while (l == prevGuid) {
3647 currentTime = new GregorianCalendar();
3648 l = new Long(currentTime.getTimeInMillis());
3650 String newResGuid = new String(Long.toString(l));
3651 newRes.setNoteGuid(targetGuid);
3652 newRes.setGuid(newResGuid);
3653 newRes.setUpdateSequenceNum(0);
3654 newRes.setActive(true);
3655 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
3658 logger.log(logger.EXTREME, "Updating note");
3659 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
3660 for (int i=0; i<sources.size(); i++) {
3661 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
3662 listManager.deleteNote(sources.get(i));
3664 logger.log(logger.EXTREME, "Exiting merge note");
3666 // A resource within a note has had a guid change
3667 @SuppressWarnings("unused")
3668 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
3669 if (!oldGuid.equals(newGuid))
3670 Global.resourceMap.put(oldGuid, newGuid);
3672 // View a thumbnail of the note
3673 public void thumbnailView() {
3675 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
3676 QFile thumbnail = new QFile(thumbnailName);
3677 if (!thumbnail.exists()) {
3679 QImage img = new QImage();
3680 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
3681 thumbnailViewer.setThumbnail(img);
3683 thumbnailViewer.setThumbnail(thumbnailName);
3684 if (!thumbnailViewer.isVisible())
3685 thumbnailViewer.showFullScreen();
3687 // An error happened while saving a note. Inform the user
3688 @SuppressWarnings("unused")
3689 private void saveRunnerError(String guid, String msg) {
3691 String title = "*Unknown*";
3692 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
3693 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
3694 title = listManager.getMasterNoteIndex().get(i).getTitle();
3695 i=listManager.getMasterNoteIndex().size();
3698 msg = "An error has happened saving the note \"" +title+
3699 "\". \nThis is probably due to a document that is too complex for Nevernote to process. "+
3700 "As a result, changes to the note may not be saved.\n\nPlease review the note for any potential problems.";
3702 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
3706 //**********************************************************
3707 //**********************************************************
3708 //* Online user actions
3709 //**********************************************************
3710 //**********************************************************
3711 private void setupOnlineMenu() {
3712 if (!Global.isConnected) {
3713 menuBar.noteOnlineHistoryAction.setEnabled(false);
3716 menuBar.noteOnlineHistoryAction.setEnabled(true);
3719 @SuppressWarnings("unused")
3720 private void viewNoteHistory() {
3721 if (currentNoteGuid == null || currentNoteGuid.equals(""))
3723 if (currentNote.getUpdateSequenceNum() == 0) {
3724 setMessage(tr("Note has never been synchronized."));
3725 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
3729 setMessage(tr("Getting Note History"));
3731 Note currentOnlineNote = null;
3734 if (Global.isPremium())
3735 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
3737 versions = new ArrayList<NoteVersionId>();
3738 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
3739 } catch (EDAMUserException e) {
3740 setMessage("EDAMUserException: " +e.getMessage());
3742 } catch (EDAMSystemException e) {
3743 setMessage("EDAMSystemException: " +e.getMessage());
3745 } catch (EDAMNotFoundException e) {
3746 setMessage(tr("Note not found on server."));
3747 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
3749 } catch (TException e) {
3750 setMessage("EDAMTransactionException: " +e.getMessage());
3754 // If we've gotten this far, we have a good note.
3755 if (historyWindow == null) {
3756 historyWindow = new OnlineNoteHistory(conn);
3757 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
3758 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
3759 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
3761 historyWindow.historyCombo.clear();
3763 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
3764 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
3766 historyWindow.setCurrent(isDirty);
3768 loadHistoryWindowContent(currentOnlineNote);
3769 historyWindow.load(versions);
3770 setMessage(tr("History retrieved"));
3772 historyWindow.exec();
3774 private Note reloadHistoryWindow(String selection) {
3776 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
3777 String dateTimeFormat = new String(fmt);
3778 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
3782 for (int i=0; i<versions.size(); i++) {
3783 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getServiceUpdated()));
3784 if (versionDate.toString().equals(selection))
3788 if (index > -1 || selection.indexOf("Current") > -1) {
3789 Note historyNote = null;
3792 usn = versions.get(index).getUpdateSequenceNum();
3793 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
3795 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
3796 } catch (EDAMUserException e) {
3797 setMessage("EDAMUserException: " +e.getMessage());
3800 } catch (EDAMSystemException e) {
3801 setMessage("EDAMSystemException: " +e.getMessage());
3804 } catch (EDAMNotFoundException e) {
3805 setMessage("EDAMNotFoundException: " +e.getMessage());
3808 } catch (TException e) {
3809 setMessage("EDAMTransactionException: " +e.getMessage());
3815 if (historyNote != null)
3816 historyWindow.setContent(historyNote);
3822 private void loadHistoryWindowContent(Note note) {
3823 note.setUpdateSequenceNum(0);
3824 historyWindow.setContent(note);
3826 @SuppressWarnings("unused")
3827 private void restoreHistoryNoteAsNew() {
3828 setMessage(tr("Restoring as new note."));
3829 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
3830 setMessage(tr("Note has been restored as a new note."));
3832 @SuppressWarnings("unused")
3833 private void restoreHistoryNote() {
3834 setMessage(tr("Restoring note."));
3835 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
3836 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
3839 for (int i=0; i<n.getResourcesSize(); i++) {
3840 n.getResources().get(i).setActive(true);
3841 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
3843 listManager.addNote(n);
3844 conn.getNoteTable().addNote(n, true);
3845 refreshEvernoteNote(true);
3846 setMessage(tr("Note has been restored."));
3851 //**********************************************************
3852 //**********************************************************
3853 //* XML Modifying methods
3854 //**********************************************************
3855 //**********************************************************
3856 // find the appropriate icon for an attachment
3857 private String findIcon(String appl) {
3858 logger.log(logger.HIGH, "Entering NeverNote.findIcon");
3859 appl = appl.toLowerCase();
3860 String relativePath = appl + ".png";
3861 File f = Global.getFileManager().getImageDirFile(relativePath);
3863 return relativePath;
3867 logger.log(logger.HIGH, "Leaving NeverNote.findIcon");
3868 return "attachment.png";
3870 // Modify the en-media tag into an attachment
3871 private void modifyApplicationTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {
3872 logger.log(logger.HIGH, "Entering NeverNote.modifyApplicationTags");
3873 if (appl.equalsIgnoreCase("vnd.evernote.ink"))
3875 String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());
3876 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);
3877 if (r == null || r.getData() == null)
3878 resourceErrorMessage();
3880 if (r.getData()!=null) {
3881 // Did we get a generic applicaiton? Then look at the file name to
3882 // try and find a good application type for the icon
3883 if (appl.equalsIgnoreCase("octet-stream")) {
3884 if (r.getAttributes() != null && r.getAttributes().getFileName() != null) {
3885 String fn = r.getAttributes().getFileName();
3886 int pos = fn.lastIndexOf(".");
3888 appl = fn.substring(pos+1);
3893 String fileDetails = null;
3894 if (r.getAttributes() != null && r.getAttributes().getFileName() != null && !r.getAttributes().getFileName().equals(""))
3895 fileDetails = r.getAttributes().getFileName();
3896 String contextFileName;
3897 FileManager fileManager = Global.getFileManager();
3898 if (fileDetails != null && !fileDetails.equals("")) {
3899 enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +fileDetails);
3900 contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + fileDetails);
3902 enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +appl);
3903 contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + appl);
3905 contextFileName = contextFileName.replace("\\", "/");
3906 enmedia.setAttribute("onContextMenu", "window.jambi.resourceContextMenu('" +contextFileName +"');");
3907 if (fileDetails == null || fileDetails.equals(""))
3909 enmedia.setAttribute("en-tag", "en-media");
3910 enmedia.setAttribute("guid", r.getGuid());
3911 enmedia.setTagName("a");
3912 QDomElement newText = doc.createElement("img");
3913 boolean goodPreview = false;
3914 String filePath = "";
3915 if (appl.equalsIgnoreCase("pdf") && Global.pdfPreview()) {
3917 Resource res = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3918 if (res.getAttributes() != null &&
3919 res.getAttributes().getFileName() != null &&
3920 !res.getAttributes().getFileName().trim().equals(""))
3921 fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();
3923 fileName = res.getGuid()+".pdf";
3924 QFile file = new QFile(fileManager.getResDirPath(fileName));
3925 QFile.OpenMode mode = new QFile.OpenMode();
3926 mode.set(QFile.OpenModeFlag.WriteOnly);
3928 QDataStream out = new QDataStream(file);
3929 Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);
3930 QByteArray binData = new QByteArray(resBinary.getData().getBody());
3932 out.writeBytes(binData.toByteArray());
3934 PDFPreview pdfPreview = new PDFPreview();
3935 goodPreview = pdfPreview.setupPreview(file.fileName(), appl,0);
3937 QDomElement span = doc.createElement("span");
3938 QDomElement table = doc.createElement("table");
3939 span.setAttribute("pdfNavigationTable", "true");
3940 QDomElement tr = doc.createElement("tr");
3941 QDomElement td = doc.createElement("td");
3942 QDomElement left = doc.createElement("img");
3943 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3944 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3945 left.setAttribute("onMouseOver", "style.cursor='hand'");
3946 QDomElement right = doc.createElement("img");
3947 right.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3948 left.setAttribute("onMouseDown", "window.jambi.previousPage('" +file.fileName() +"')");
3949 // NFC TODO: should these be file:// URLs?
3950 left.setAttribute("src", Global.getFileManager().getImageDirPath("small_left.png"));
3951 right.setAttribute("src", Global.getFileManager().getImageDirPath("small_right.png"));
3952 right.setAttribute("onMouseOver", "style.cursor='hand'");
3954 table.appendChild(tr);
3956 td.appendChild(left);
3957 td.appendChild(right);
3958 span.appendChild(table);
3959 enmedia.parentNode().insertBefore(span, enmedia);
3961 filePath = fileName+".png";
3963 String icon = findIcon(appl);
3964 if (icon.equals("attachment.png"))
3965 icon = findIcon(fileDetails.substring(fileDetails.indexOf(".")+1));
3966 // NFC TODO: should this be a 'file://' URL?
3967 newText.setAttribute("src", Global.getFileManager().getImageDirPath(icon));
3969 // NFC TODO: should this be a 'file://' URL?
3970 newText.setAttribute("src", fileManager.getResDirPath(filePath));
3971 newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");
3973 newText.setAttribute("title", fileDetails);
3974 enmedia.removeChild(enmedia.firstChild());
3976 enmedia.appendChild(newText);
3979 logger.log(logger.HIGH, "Leaving NeverNote.modifyApplicationTags");
3981 // Modify the en-to tag into an input field
3982 private void modifyTodoTags(QDomElement todo) {
3983 logger.log(logger.HIGH, "Entering NeverNote.modifyTodoTags");
3984 todo.setAttribute("type", "checkbox");
3985 String checked = todo.attribute("checked");
3986 todo.removeAttribute("checked");
3987 if (checked.equalsIgnoreCase("true"))
3988 todo.setAttribute("checked", "");
3990 todo.setAttribute("unchecked","");
3991 todo.setAttribute("value", checked);
3992 todo.setAttribute("onClick", "value=checked;window.jambi.contentChanged(); ");
3993 todo.setTagName("input");
3994 logger.log(logger.HIGH, "Leaving NeverNote.modifyTodoTags");
3996 // Modify any cached todo tags that may have changed
3997 private String modifyCachedTodoTags(String note) {
3998 logger.log(logger.HIGH, "Entering NeverNote.modifyCachedTodoTags");
3999 StringBuffer html = new StringBuffer(note);
4000 for (int i=html.indexOf("<input", 0); i>-1; i=html.indexOf("<input", i)) {
4001 int endPos =html.indexOf(">",i+1);
4002 String input = html.substring(i,endPos);
4003 if (input.indexOf("value=\"true\"") > 0)
4004 input = input.replace(" unchecked=\"\"", " checked=\"\"");
4006 input = input.replace(" checked=\"\"", " unchecked=\"\"");
4007 html.replace(i, endPos, input);
4010 logger.log(logger.HIGH, "Leaving NeverNote.modifyCachedTodoTags");
4011 return html.toString();
4013 // Modify the en-media tag into an image tag so it can be displayed.
4014 private void modifyImageTags(QDomElement docElem, QDomElement enmedia, QDomAttr hash) {
4015 logger.log(logger.HIGH, "Entering NeverNote.modifyImageTags");
4016 String type = enmedia.attribute("type");
4017 if (type.startsWith("image/"))
4018 type = "."+type.substring(6);
4022 String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNoteGuid, hash.value());
4023 QFile tfile = new QFile(Global.getFileManager().getResDirPath(resGuid + type));
4024 if (!tfile.exists()) {
4026 if (resGuid != null)
4027 r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid,true);
4028 if (r==null || r.getData() == null || r.getData().getBody().length == 0)
4029 resourceErrorMessage();
4030 if (r!= null && r.getData() != null && r.getData().getBody().length > 0) {
4031 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));
4032 QByteArray binData = new QByteArray(r.getData().getBody());
4033 tfile.write(binData);
4035 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
4036 enmedia.setAttribute("en-tag", "en-media");
4037 enmedia.setNodeValue("");
4038 enmedia.setAttribute("guid", r.getGuid());
4039 enmedia.setTagName("img");
4042 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
4043 enmedia.setAttribute("en-tag", "en-media");
4044 enmedia.setAttribute("onContextMenu", "window.jambi.imageContextMenu('" +tfile.fileName() +"');");
4045 enmedia.setNodeValue("");
4046 enmedia.setAttribute("guid", resGuid);
4047 enmedia.setTagName("img");
4049 logger.log(logger.HIGH, "Leaving NeverNote.modifyImageTags");
4051 // Modify tags from Evernote specific things to XHTML tags.
4052 private QDomDocument modifyTags(QDomDocument doc) {
4053 logger.log(logger.HIGH, "Entering NeverNote.modifyTags");
4054 if (tempFiles == null)
4055 tempFiles = new ArrayList<QTemporaryFile>();
4057 QDomElement docElem = doc.documentElement();
4059 // Modify en-media tags
4060 QDomNodeList anchors = docElem.elementsByTagName("en-media");
4061 int enMediaCount = anchors.length();
4062 for (int i=enMediaCount-1; i>=0; i--) {
4063 QDomElement enmedia = anchors.at(i).toElement();
4064 if (enmedia.hasAttribute("type")) {
4065 QDomAttr attr = enmedia.attributeNode("type");
4066 QDomAttr hash = enmedia.attributeNode("hash");
4067 String[] type = attr.nodeValue().split("/");
4068 String appl = type[1];
4070 if (type[0] != null) {
4071 if (type[0].equals("image")) {
4072 modifyImageTags(docElem, enmedia, hash);
4074 if (!type[0].equals("image")) {
4075 modifyApplicationTags(doc, docElem, enmedia, hash, appl);
4082 anchors = docElem.elementsByTagName("en-todo");
4083 int enTodoCount = anchors.length();
4084 for (int i=enTodoCount-1; i>=0; i--) {
4085 QDomElement enmedia = anchors.at(i).toElement();
4086 modifyTodoTags(enmedia);
4089 // Modify en-crypt tags
4090 anchors = docElem.elementsByTagName("en-crypt");
4091 int enCryptLen = anchors.length();
4092 for (int i=enCryptLen-1; i>=0; i--) {
4093 QDomElement enmedia = anchors.at(i).toElement();
4094 enmedia.setAttribute("contentEditable","false");
4095 enmedia.setAttribute("src", Global.getFileManager().getImageDirPath("encrypt.png"));
4096 enmedia.setAttribute("en-tag","en-crypt");
4097 enmedia.setAttribute("alt", enmedia.text());
4098 Global.cryptCounter++;
4099 enmedia.setAttribute("id", "crypt"+Global.cryptCounter.toString());
4100 String encryptedText = enmedia.text();
4102 // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
4103 if (encryptedText.endsWith("\n"))
4104 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
4105 if (encryptedText.endsWith("\r"))
4106 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
4109 String hint = enmedia.attribute("hint");
4110 hint = hint.replace("'","'");
4111 enmedia.setAttribute("onClick", "window.jambi.decryptText('crypt"+Global.cryptCounter.toString()+"', '"+encryptedText+"', '"+hint+"');");
4112 enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
4113 enmedia.setTagName("img");
4114 enmedia.removeChild(enmedia.firstChild()); // Remove the actual encrypted text
4119 anchors = docElem.elementsByTagName("a");
4120 enCryptLen = anchors.length();
4121 for (int i=0; i<anchors.length(); i++) {
4122 QDomElement element = anchors.at(i).toElement();
4123 element.setAttribute("title", element.attribute("href"));
4126 logger.log(logger.HIGH, "Leaving NeverNote.modifyTags");
4129 // Rebuild the note HTML to something usable
4130 private String rebuildNoteHTML(String noteGuid, String note) {
4131 logger.log(logger.HIGH, "Entering NeverNote.rebuildNoteHTML");
4132 logger.log(logger.EXTREME, "Note guid: " +noteGuid);
4133 logger.log(logger.EXTREME, "Note Text:" +note);
4134 QDomDocument doc = new QDomDocument();
4135 QDomDocument.Result result = doc.setContent(note);
4136 if (!result.success) {
4137 logger.log(logger.MEDIUM, "Parse error when rebuilding HTML");
4138 logger.log(logger.MEDIUM, "Note guid: " +noteGuid);
4139 logger.log(logger.EXTREME, "Start of unmodified note HTML");
4140 logger.log(logger.EXTREME, note);
4141 logger.log(logger.EXTREME, "End of unmodified note HTML");
4145 if (tempFiles == null)
4146 tempFiles = new ArrayList<QTemporaryFile>();
4149 doc = modifyTags(doc);
4150 doc = addHilight(doc);
4151 QDomElement docElem = doc.documentElement();
4152 docElem.setTagName("Body");
4153 // docElem.setAttribute("bgcolor", "green");
4154 logger.log(logger.EXTREME, "Rebuilt HTML:");
4155 logger.log(logger.EXTREME, doc.toString());
4156 logger.log(logger.HIGH, "Leaving NeverNote.rebuildNoteHTML");
4157 // Fix the stupid problem where inserting an <img> tag after an <a> tag (which is done
4158 // to get the <en-media> application tag to work properly) causes spaces to be inserted
4159 // between the <a> & <img>. This messes things up later. This is an ugly hack.
4160 StringBuffer html = new StringBuffer(doc.toString());
4161 for (int i=html.indexOf("<a en-tag=\"en-media\" ", 0); i>-1; i=html.indexOf("<a en-tag=\"en-media\" ", i)) {
4162 i=html.indexOf(">\n",i+1);
4163 int z = html.indexOf("<img",i);
4164 for (int j=z-1; j>i; j--)
4165 html.deleteCharAt(j);
4166 i=html.indexOf("/>", z+1);
4167 z = html.indexOf("</a>",i);
4168 for (int j=z-1; j>i+1; j--)
4169 html.deleteCharAt(j);
4171 return html.toString();
4173 // Scan and do hilighting of words
4174 private QDomDocument addHilight(QDomDocument doc) {
4175 EnSearch e = listManager.getEnSearch();
4176 if (e.hilightWords == null || e.hilightWords.size() == 0)
4178 XMLInsertHilight hilight = new XMLInsertHilight(doc, listManager.getEnSearch().hilightWords);
4179 return hilight.getDoc();
4182 // An error has happended fetching a resource. let the user know
4183 private void resourceErrorMessage() {
4186 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4187 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4188 "In a perfect world this wouldn't happen, but it has.\n" +
4189 "It is embarasing when a program like me, designed to save all your\n"+
4190 "precious data, has a problem finding data.\n\n" +
4191 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
4192 "In the mean time, I'm not going to let you make changes to this note.\n" +
4193 "Don't get angry. I'm doing it to prevent you from messing up\n"+
4194 "this note on the Evernote servers. Sorry."+
4195 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4197 //// browserWindow.setEnabled(false);
4198 browserWindow.setReadOnly(true);
4204 //**********************************************************
4205 //**********************************************************
4207 //**********************************************************
4208 //**********************************************************
4209 // We should now do a sync with Evernote
4210 private void syncTimer() {
4211 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
4212 syncRunner.syncNeeded = true;
4213 syncRunner.disableUploads = Global.disableUploads;
4215 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
4217 private void syncStart() {
4218 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
4220 if (!syncRunning && Global.isConnected) {
4221 syncRunner.setConnected(true);
4222 syncRunner.setKeepRunning(Global.keepRunning);
4223 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
4225 if (syncThreadsReady > 0) {
4226 saveNoteIndexWidth();
4227 if (syncRunner.addWork("SYNC")) {
4229 syncRunner.syncNeeded = true;
4234 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
4236 @SuppressWarnings("unused")
4237 private void syncThreadComplete(Boolean refreshNeeded) {
4238 setMessage(tr("Finalizing Synchronization"));
4240 syncRunning = false;
4241 syncRunner.syncNeeded = false;
4242 synchronizeAnimationTimer.stop();
4243 synchronizeButton.setIcon(synchronizeAnimation.get(0));
4245 if (currentNote == null) {
4246 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
4248 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
4249 noteIndexUpdated(false);
4250 noteTableView.selectionModel().blockSignals(true);
4251 scrollToGuid(currentNoteGuid);
4252 noteTableView.selectionModel().blockSignals(false);
4253 refreshEvernoteNote(false);
4254 scrollToGuid(currentNoteGuid);
4256 if (!syncRunner.error)
4257 setMessage(tr("Synchronization Complete"));
4259 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
4260 logger.log(logger.MEDIUM, "Sync complete.");
4262 public void saveUploadAmount(long t) {
4263 Global.saveUploadAmount(t);
4265 public void saveUserInformation(User user) {
4266 Global.saveUserInformation(user);
4268 public void saveEvernoteUpdateCount(int i) {
4269 Global.saveEvernoteUpdateCount(i);
4271 public void refreshLists() {
4272 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
4274 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
4275 tagIndexUpdated(true);
4276 notebookIndexUpdated();
4277 savedSearchIndexUpdated();
4278 listManager.loadNotesIndex();
4280 noteTableView.selectionModel().blockSignals(true);
4281 noteIndexUpdated(true);
4282 noteTableView.selectionModel().blockSignals(false);
4283 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
4287 @SuppressWarnings("unused")
4288 private void authTimer() {
4289 Calendar cal = Calendar.getInstance();
4291 // If we are not connected let's get out of here
4292 if (!Global.isConnected)
4295 // If this is the first time through, then we need to set this
4296 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
4297 // syncRunner.authRefreshTime = cal.getTimeInMillis();
4299 // long now = new Date().getTime();
4300 // if (now > Global.authRefreshTime && Global.isConnected) {
4301 syncRunner.authRefreshNeeded = true;
4305 @SuppressWarnings("unused")
4306 private void authRefreshComplete(boolean goodSync) {
4307 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
4308 Global.isConnected = syncRunner.isConnected;
4310 // authTimer.start((int)syncRunner.authTimeRemaining/4);
4311 authTimer.start(1000*60*15);
4312 logger.log(logger.LOW, "Authentication token has been renewed");
4313 // setMessage("Authentication token has been renewed.");
4315 authTimer.start(1000*60*5);
4316 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
4317 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
4319 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
4323 @SuppressWarnings("unused")
4324 private synchronized void indexTimer() {
4325 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
4328 // Look for any unindexed notes. We only refresh occasionally
4329 // and do one at a time to keep overhead down.
4330 if (!indexDisabled && indexRunner.getWorkQueueSize() == 0) {
4331 List<String> notes = conn.getNoteTable().getNextUnindexed(1);
4332 String unindexedNote = null;
4333 if (notes.size() > 0)
4334 unindexedNote = notes.get(0);
4335 if (unindexedNote != null && Global.keepRunning) {
4336 indexNoteContent(unindexedNote);
4338 if (notes.size()>0) {
4339 indexTimer.setInterval(100);
4342 List<String> unindexedResources = conn.getNoteTable().noteResourceTable.getNextUnindexed(1);
4343 if (unindexedResources.size() > 0 && indexRunner.getWorkQueueSize() == 0) {
4344 String unindexedResource = unindexedResources.get(0);
4345 if (unindexedResource != null && Global.keepRunning) {
4346 indexNoteResource(unindexedResource);
4349 if (unindexedResources.size() > 0) {
4350 indexTimer.setInterval(100);
4353 indexTimer.setInterval(indexTime);
4356 setMessage(tr("Index completed."));
4357 logger.log(logger.LOW, "Indexing has completed.");
4358 indexRunning = false;
4359 indexTimer.setInterval(indexTime);
4362 logger.log(logger.EXTREME, "Leaving neverNote index timer");
4364 private synchronized void indexNoteContent(String unindexedNote) {
4365 logger.log(logger.EXTREME, "Entering NeverNote.indexNoteContent()");
4366 logger.log(logger.MEDIUM, "Unindexed Note found: "+unindexedNote);
4367 indexRunner.setIndexType(indexRunner.CONTENT);
4368 indexRunner.addWork("CONTENT "+unindexedNote);
4369 if (!indexRunning) {
4370 setMessage(tr("Indexing notes."));
4371 logger.log(logger.LOW, "Beginning to index note contents.");
4372 indexRunning = true;
4374 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteContent()");
4376 private synchronized void indexNoteResource(String unindexedResource) {
4377 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4378 indexRunner.addWork(new String("RESOURCE "+unindexedResource));
4379 if (!indexRunning) {
4380 setMessage(tr("Indexing notes."));
4381 indexRunning = true;
4383 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4385 @SuppressWarnings("unused")
4386 private void indexThreadComplete(String guid) {
4387 logger.log(logger.MEDIUM, "Index complete for "+guid);
4389 @SuppressWarnings("unused")
4390 private synchronized void toggleNoteIndexing() {
4391 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
4392 indexDisabled = !indexDisabled;
4394 setMessage(tr("Indexing is now enabled."));
4396 setMessage(tr("Indexing is now disabled."));
4397 menuBar.disableIndexing.setChecked(indexDisabled);
4398 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
4401 @SuppressWarnings("unused")
4402 private void threadMonitorCheck() {
4407 alive = listManager.threadCheck(Global.tagCounterThreadId);
4410 if (tagDeadCount > MAX)
4411 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
4412 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4416 alive = listManager.threadCheck(Global.notebookCounterThreadId);
4418 notebookThreadDeadCount++;
4419 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
4420 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4422 notebookThreadDeadCount=0;
4424 alive = listManager.threadCheck(Global.trashCounterThreadId);
4427 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
4428 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4432 alive = listManager.threadCheck(Global.saveThreadId);
4434 saveThreadDeadCount++;
4435 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
4436 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4438 saveThreadDeadCount=0;
4440 if (!syncThread.isAlive()) {
4441 syncThreadDeadCount++;
4442 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
4443 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4445 syncThreadDeadCount=0;
4447 if (!indexThread.isAlive()) {
4448 indexThreadDeadCount++;
4449 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
4450 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4452 indexThreadDeadCount=0;
4459 //**************************************************
4460 //* Backup & Restore
4461 //**************************************************
4462 @SuppressWarnings("unused")
4463 private void databaseBackup() {
4464 QFileDialog fd = new QFileDialog(this);
4465 fd.setFileMode(FileMode.AnyFile);
4466 fd.setConfirmOverwrite(true);
4467 fd.setWindowTitle(tr("Backup Database"));
4468 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4469 fd.setAcceptMode(AcceptMode.AcceptSave);
4470 fd.setDirectory(System.getProperty("user.home"));
4471 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4477 setMessage(tr("Backing up database"));
4479 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
4481 ExportData noteWriter = new ExportData(conn, true);
4482 String fileName = fd.selectedFiles().get(0);
4484 if (!fileName.endsWith(".nnex"))
4485 fileName = fileName +".nnex";
4486 noteWriter.exportData(fileName);
4487 setMessage(tr("Database backup completed."));
4492 @SuppressWarnings("unused")
4493 private void databaseRestore() {
4494 if (QMessageBox.question(this, tr("Confirmation"),
4495 tr("This is used to restore a database from backups.\n" +
4496 "It is HIGHLY recommened that this only be used to populate\n" +
4497 "an empty database. Restoring into a database that\n already has data" +
4498 " can cause problems.\n\nAre you sure you want to continue?"),
4499 QMessageBox.StandardButton.Yes,
4500 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4505 QFileDialog fd = new QFileDialog(this);
4506 fd.setFileMode(FileMode.ExistingFile);
4507 fd.setConfirmOverwrite(true);
4508 fd.setWindowTitle(tr("Restore Database"));
4509 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4510 fd.setAcceptMode(AcceptMode.AcceptOpen);
4511 fd.setDirectory(System.getProperty("user.home"));
4512 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4518 setMessage(tr("Restoring database"));
4519 ImportData noteReader = new ImportData(conn, true);
4520 noteReader.importData(fd.selectedFiles().get(0));
4522 if (noteReader.lastError != 0) {
4523 setMessage(noteReader.getErrorMessage());
4524 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
4529 listManager.loadNoteTitleColors();
4531 refreshEvernoteNote(true);
4532 setMessage(tr("Database has been restored."));
4535 @SuppressWarnings("unused")
4536 private void exportNotes() {
4537 QFileDialog fd = new QFileDialog(this);
4538 fd.setFileMode(FileMode.AnyFile);
4539 fd.setConfirmOverwrite(true);
4540 fd.setWindowTitle(tr("Backup Database"));
4541 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4542 fd.setAcceptMode(AcceptMode.AcceptSave);
4543 fd.setDirectory(System.getProperty("user.home"));
4544 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4550 setMessage(tr("Exporting Notes"));
4553 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4554 selectedNoteGUIDs.add(currentNoteGuid);
4556 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
4557 String fileName = fd.selectedFiles().get(0);
4559 if (!fileName.endsWith(".nnex"))
4560 fileName = fileName +".nnex";
4561 noteWriter.exportData(fileName);
4562 setMessage(tr("Export completed."));
4568 @SuppressWarnings("unused")
4569 private void importNotes() {
4570 QFileDialog fd = new QFileDialog(this);
4571 fd.setFileMode(FileMode.ExistingFile);
4572 fd.setConfirmOverwrite(true);
4573 fd.setWindowTitle(tr("Import Notes"));
4574 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4575 fd.setAcceptMode(AcceptMode.AcceptOpen);
4576 fd.setDirectory(System.getProperty("user.home"));
4577 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4583 setMessage("Importing Notes");
4586 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4587 selectedNoteGUIDs.add(currentNoteGuid);
4589 ImportData noteReader = new ImportData(conn, false);
4590 String fileName = fd.selectedFiles().get(0);
4592 if (!fileName.endsWith(".nnex"))
4593 fileName = fileName +".nnex";
4594 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
4595 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
4597 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
4599 noteReader.importData(fileName);
4601 if (noteReader.lastError != 0) {
4602 setMessage(noteReader.getErrorMessage());
4603 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
4608 listManager.loadNoteTitleColors();
4610 refreshEvernoteNote(false);
4611 setMessage(tr("Notes have been imported."));
4614 setMessage("Import completed.");
4621 //**************************************************
4622 //* Duplicate a note
4623 //**************************************************
4624 @SuppressWarnings("unused")
4625 private void duplicateNote() {
4627 duplicateNote(currentNoteGuid);
4632 //**************************************************
4634 //**************************************************
4635 public void setupFolderImports() {
4636 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
4638 if (importKeepWatcher == null)
4639 importKeepWatcher = new QFileSystemWatcher();
4640 if (importDeleteWatcher == null) {
4641 importDeleteWatcher = new QFileSystemWatcher();
4642 for (int i=0; i<records.size(); i++) {
4643 if (!records.get(i).keep)
4644 folderImportDelete(records.get(i).folder);
4650 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
4651 for (int i=0; i<records.size(); i++) {
4652 if (records.get(i).keep)
4653 importKeepWatcher.addPath(records.get(i).folder);
4655 importDeleteWatcher.addPath(records.get(i).folder);
4658 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
4659 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
4661 // Look at the files already there so we don't import them again if a new file is created
4662 if (importedFiles == null) {
4663 importedFiles = new ArrayList<String>();
4664 for (int j=0; j<records.size(); j++) {
4665 QDir dir = new QDir(records.get(j).folder);
4666 List<QFileInfo> list = dir.entryInfoList();
4667 for (int k=0; k<list.size(); k++) {
4668 if (list.get(k).isFile())
4669 importedFiles.add(list.get(k).absoluteFilePath());
4674 public void folderImport() {
4675 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
4676 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
4678 if (!dialog.okClicked())
4681 // We have some sort of update.
4682 if (importKeepWatcher.directories().size() > 0)
4683 importKeepWatcher.removePaths(importKeepWatcher.directories());
4684 if (importDeleteWatcher.directories().size() > 0)
4685 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
4687 conn.getWatchFolderTable().expungeAll();
4688 // Start building from the table
4689 for (int i=0; i<dialog.table.rowCount(); i++) {
4690 QTableWidgetItem item = dialog.table.item(i, 0);
4691 String dir = item.text();
4692 item = dialog.table.item(i, 1);
4693 String notebook = item.text();
4694 item = dialog.table.item(i, 2);
4696 if (item.text().equalsIgnoreCase("Keep"))
4701 String guid = conn.getNotebookTable().findNotebookByName(notebook);
4702 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
4704 setupFolderImports();
4707 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
4709 String whichOS = System.getProperty("os.name");
4710 if (whichOS.contains("Windows"))
4711 dirName = dirName.replace('/','\\');
4713 FileImporter importer = new FileImporter(logger, conn);
4715 QDir dir = new QDir(dirName);
4716 List<QFileInfo> list = dir.entryInfoList();
4717 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4719 for (int i=0; i<list.size(); i++){
4721 boolean redundant = false;
4722 // Check if we've already imported this one or if it existed before
4723 for (int j=0; j<importedFiles.size(); j++) {
4724 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
4729 importer.setFileInfo(list.get(i));
4730 importer.setFileName(list.get(i).absoluteFilePath());
4733 if (list.get(i).isFile() && importer.isValidType()) {
4735 if (!importer.importFile()) {
4736 // If we can't get to the file, it is probably locked. We'll try again later.
4737 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4738 importFilesKeep.add(list.get(i).absoluteFilePath());
4742 Note newNote = importer.getNote();
4743 newNote.setNotebookGuid(notebook);
4744 newNote.setTitle(dir.at(i));
4745 listManager.addNote(newNote);
4746 conn.getNoteTable().addNote(newNote, true);
4747 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4748 noteTableView.insertRow(newNote, true, -1);
4749 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4750 listManager.countNotebookResults(listManager.getNoteIndex());
4751 importedFiles.add(list.get(i).absoluteFilePath());
4759 public void folderImportDelete(String dirName) {
4761 String whichOS = System.getProperty("os.name");
4762 if (whichOS.contains("Windows"))
4763 dirName = dirName.replace('/','\\');
4765 FileImporter importer = new FileImporter(logger, conn);
4766 QDir dir = new QDir(dirName);
4767 List<QFileInfo> list = dir.entryInfoList();
4768 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4770 for (int i=0; i<list.size(); i++){
4771 importer.setFileInfo(list.get(i));
4772 importer.setFileName(list.get(i).absoluteFilePath());
4774 if (list.get(i).isFile() && importer.isValidType()) {
4776 if (!importer.importFile()) {
4777 // If we can't get to the file, it is probably locked. We'll try again later.
4778 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4779 importFilesKeep.add(list.get(i).absoluteFilePath());
4783 Note newNote = importer.getNote();
4784 newNote.setNotebookGuid(notebook);
4785 newNote.setTitle(dir.at(i));
4786 listManager.addNote(newNote);
4787 conn.getNoteTable().addNote(newNote, true);
4788 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4789 noteTableView.insertRow(newNote, true, -1);
4790 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4791 listManager.countNotebookResults(listManager.getNoteIndex());
4792 dir.remove(dir.at(i));
4798 //**************************************************
4800 //**************************************************
4801 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
4802 logger.log(logger.HIGH, "Entering exernalFileEdited");
4804 // Strip URL prefix and base dir path
4805 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
4806 String name = fileName.replace(dPath, "");
4807 int pos = name.lastIndexOf('.');
4810 guid = guid.substring(0,pos);
4812 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
4814 guid = name.substring(0, pos);
4817 QFile file = new QFile(fileName);
4818 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
4819 // If we can't get to the file, it is probably locked. We'll try again later.
4820 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4821 externalFiles.add(fileName);
4824 QByteArray binData = file.readAll();
4826 if (binData.size() == 0) {
4827 // If we can't get to the file, it is probably locked. We'll try again later.
4828 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4829 externalFiles.add(fileName);
4833 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
4835 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
4836 if (r == null || r.getData() == null || r.getData().getBody() == null)
4838 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
4839 MessageDigest md = MessageDigest.getInstance("MD5");
4840 md.update(binData.toByteArray());
4841 byte[] hash = md.digest();
4842 String newHash = Global.byteArrayToHexString(hash);
4843 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
4844 updateResourceContentHash(r.getGuid(), oldHash, newHash);
4846 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
4847 Data data = r.getData();
4848 data.setBody(binData.toByteArray());
4849 data.setBodyHash(hash);
4850 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
4852 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
4854 if (r.getNoteGuid().equals(currentNoteGuid)) {
4855 QWebSettings.setMaximumPagesInCache(0);
4856 QWebSettings.setObjectCacheCapacities(0, 0, 0);
4857 refreshEvernoteNote(true);
4858 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
4861 logger.log(logger.HIGH, "Exiting externalFielEdited");
4863 // This is a timer event that tries to save any external files that were edited. This
4864 // is only needed if we couldn't save a file earlier.
4865 public void externalFileEditedSaver() {
4866 for (int i=externalFiles.size()-1; i>=0; i--) {
4868 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
4869 externalFileEdited(externalFiles.get(i));
4870 externalFiles.remove(i);
4871 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4873 for (int i=0; i<importFilesKeep.size(); i++) {
4875 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
4876 folderImportKeep(importFilesKeep.get(i));
4877 importFilesKeep.remove(i);
4878 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4880 for (int i=0; i<importFilesDelete.size(); i++) {
4881 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
4882 folderImportDelete(importFilesDelete.get(i));
4883 importFilesDelete.remove(i);
4890 // If an attachment on the current note was edited, we need to update the current notes's hash
4891 // Update a note content's hash. This happens if a resource is edited outside of NN
4892 public void updateResourceContentHash(String guid, String oldHash, String newHash) {
4893 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
4895 for (;position>-1;) {
4896 endPos = browserWindow.getContent().indexOf(">", position+1);
4897 String oldSegment = browserWindow.getContent().substring(position,endPos);
4898 int hashPos = oldSegment.indexOf("hash=\"");
4899 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
4900 String hash = oldSegment.substring(hashPos+6, hashEnd);
4901 if (hash.equalsIgnoreCase(oldHash)) {
4902 String newSegment = oldSegment.replace(oldHash, newHash);
4903 String content = browserWindow.getContent().substring(0,position) +
4905 browserWindow.getContent().substring(endPos);
4906 browserWindow.getBrowser().setContent(new QByteArray(content));;
4909 position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
4914 //*************************************************
4915 //* Minimize to tray
4916 //*************************************************
4918 public void changeEvent(QEvent e) {
4919 if (e.type() == QEvent.Type.WindowStateChange) {
4920 if (isMinimized() && Global.showTrayIcon()) {
4922 QTimer.singleShot(10, this, "hide()");
4926 windowMaximized = true;
4928 windowMaximized = false;
4932 //*************************************************
4933 //* Check database userid & passwords
4934 //*************************************************
4935 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
4936 Connection connection;
4939 Class.forName("org.h2.Driver");
4940 } catch (ClassNotFoundException e1) {
4941 e1.printStackTrace();
4946 String passwordString = null;
4947 if (cypherPassword==null || cypherPassword.trim().equals(""))
4948 passwordString = userPassword;
4950 passwordString = cypherPassword+" "+userPassword;
4951 connection = DriverManager.getConnection(url,userid,passwordString);
4952 } catch (SQLException e) {
4957 } catch (SQLException e) {
4958 e.printStackTrace();