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.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Calendar;
32 import java.util.Collections;
33 import java.util.Comparator;
34 import java.util.Date;
35 import java.util.GregorianCalendar;
36 import java.util.HashMap;
37 import java.util.List;
38 import java.util.SortedMap;
39 import java.util.Vector;
41 import org.apache.thrift.TException;
43 import com.evernote.edam.error.EDAMNotFoundException;
44 import com.evernote.edam.error.EDAMSystemException;
45 import com.evernote.edam.error.EDAMUserException;
46 import com.evernote.edam.notestore.NoteFilter;
47 import com.evernote.edam.notestore.NoteVersionId;
48 import com.evernote.edam.type.Data;
49 import com.evernote.edam.type.Note;
50 import com.evernote.edam.type.NoteAttributes;
51 import com.evernote.edam.type.Notebook;
52 import com.evernote.edam.type.QueryFormat;
53 import com.evernote.edam.type.Resource;
54 import com.evernote.edam.type.SavedSearch;
55 import com.evernote.edam.type.Tag;
56 import com.evernote.edam.type.User;
57 import com.trolltech.qt.QThread;
58 import com.trolltech.qt.core.QByteArray;
59 import com.trolltech.qt.core.QDataStream;
60 import com.trolltech.qt.core.QDateTime;
61 import com.trolltech.qt.core.QDir;
62 import com.trolltech.qt.core.QFile;
63 import com.trolltech.qt.core.QFileInfo;
64 import com.trolltech.qt.core.QFileSystemWatcher;
65 import com.trolltech.qt.core.QIODevice;
66 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
67 import com.trolltech.qt.core.QLocale;
68 import com.trolltech.qt.core.QModelIndex;
69 import com.trolltech.qt.core.QSize;
70 import com.trolltech.qt.core.QTemporaryFile;
71 import com.trolltech.qt.core.QTextCodec;
72 import com.trolltech.qt.core.QThreadPool;
73 import com.trolltech.qt.core.QTimer;
74 import com.trolltech.qt.core.QTranslator;
75 import com.trolltech.qt.core.QUrl;
76 import com.trolltech.qt.core.Qt;
77 import com.trolltech.qt.core.Qt.ItemDataRole;
78 import com.trolltech.qt.core.Qt.SortOrder;
79 import com.trolltech.qt.core.Qt.WidgetAttribute;
80 import com.trolltech.qt.gui.QAbstractItemView;
81 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
82 import com.trolltech.qt.gui.QAction;
83 import com.trolltech.qt.gui.QApplication;
84 import com.trolltech.qt.gui.QCloseEvent;
85 import com.trolltech.qt.gui.QColor;
86 import com.trolltech.qt.gui.QComboBox;
87 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
88 import com.trolltech.qt.gui.QDesktopServices;
89 import com.trolltech.qt.gui.QDialog;
90 import com.trolltech.qt.gui.QFileDialog;
91 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
92 import com.trolltech.qt.gui.QFileDialog.FileMode;
93 import com.trolltech.qt.gui.QGridLayout;
94 import com.trolltech.qt.gui.QHBoxLayout;
95 import com.trolltech.qt.gui.QIcon;
96 import com.trolltech.qt.gui.QImage;
97 import com.trolltech.qt.gui.QLabel;
98 import com.trolltech.qt.gui.QListWidget;
99 import com.trolltech.qt.gui.QMainWindow;
100 import com.trolltech.qt.gui.QMenu;
101 import com.trolltech.qt.gui.QMessageBox;
102 import com.trolltech.qt.gui.QMessageBox.StandardButton;
103 import com.trolltech.qt.gui.QPixmap;
104 import com.trolltech.qt.gui.QPrintDialog;
105 import com.trolltech.qt.gui.QPrinter;
106 import com.trolltech.qt.gui.QProgressBar;
107 import com.trolltech.qt.gui.QSizePolicy;
108 import com.trolltech.qt.gui.QSizePolicy.Policy;
109 import com.trolltech.qt.gui.QSpinBox;
110 import com.trolltech.qt.gui.QSplashScreen;
111 import com.trolltech.qt.gui.QSplitter;
112 import com.trolltech.qt.gui.QStatusBar;
113 import com.trolltech.qt.gui.QSystemTrayIcon;
114 import com.trolltech.qt.gui.QTableWidgetItem;
115 import com.trolltech.qt.gui.QTextEdit;
116 import com.trolltech.qt.gui.QToolBar;
117 import com.trolltech.qt.gui.QTreeWidgetItem;
118 import com.trolltech.qt.webkit.QWebPage.WebAction;
119 import com.trolltech.qt.webkit.QWebSettings;
120 import com.trolltech.qt.xml.QDomAttr;
121 import com.trolltech.qt.xml.QDomDocument;
122 import com.trolltech.qt.xml.QDomElement;
123 import com.trolltech.qt.xml.QDomNodeList;
125 import cx.fbn.nevernote.config.FileManager;
126 import cx.fbn.nevernote.config.InitializationException;
127 import cx.fbn.nevernote.config.StartupConfig;
128 import cx.fbn.nevernote.dialog.AccountDialog;
129 import cx.fbn.nevernote.dialog.ConfigDialog;
130 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
131 import cx.fbn.nevernote.dialog.DatabaseStatus;
132 import cx.fbn.nevernote.dialog.FindDialog;
133 import cx.fbn.nevernote.dialog.LoginDialog;
134 import cx.fbn.nevernote.dialog.NotebookArchive;
135 import cx.fbn.nevernote.dialog.NotebookEdit;
136 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
137 import cx.fbn.nevernote.dialog.SavedSearchEdit;
138 import cx.fbn.nevernote.dialog.TagEdit;
139 import cx.fbn.nevernote.dialog.ThumbnailViewer;
140 import cx.fbn.nevernote.dialog.WatchFolder;
141 import cx.fbn.nevernote.filters.EnSearch;
142 import cx.fbn.nevernote.gui.AttributeTreeWidget;
143 import cx.fbn.nevernote.gui.BrowserWindow;
144 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
145 import cx.fbn.nevernote.gui.MainMenuBar;
146 import cx.fbn.nevernote.gui.NotebookTreeWidget;
147 import cx.fbn.nevernote.gui.PDFPreview;
148 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
149 import cx.fbn.nevernote.gui.TableView;
150 import cx.fbn.nevernote.gui.TagTreeWidget;
151 import cx.fbn.nevernote.gui.Thumbnailer;
152 import cx.fbn.nevernote.gui.TrashTreeWidget;
153 import cx.fbn.nevernote.sql.DatabaseConnection;
154 import cx.fbn.nevernote.sql.WatchFolderRecord;
155 import cx.fbn.nevernote.threads.IndexRunner;
156 import cx.fbn.nevernote.threads.SyncRunner;
157 import cx.fbn.nevernote.utilities.AESEncrypter;
158 import cx.fbn.nevernote.utilities.ApplicationLogger;
159 import cx.fbn.nevernote.utilities.FileImporter;
160 import cx.fbn.nevernote.utilities.FileUtils;
161 import cx.fbn.nevernote.utilities.ListManager;
162 import cx.fbn.nevernote.utilities.SyncTimes;
163 import cx.fbn.nevernote.xml.ExportData;
164 import cx.fbn.nevernote.xml.ImportData;
165 import cx.fbn.nevernote.xml.XMLInsertHilight;
168 public class NeverNote extends QMainWindow{
170 QStatusBar statusBar; // Application status bar
172 DatabaseConnection conn;
174 MainMenuBar menuBar; // Main menu bar
175 FindDialog find; // Text search in note dialog
176 List<String> emitLog; // Messages displayed in the status bar;
177 QSystemTrayIcon trayIcon; // little tray icon
178 QMenu trayMenu; // System tray menu
179 QAction trayExitAction; // Exit the application
180 QAction trayShowAction; // toggle the show/hide action
181 QAction trayAddNoteAction; // Add a note from the system tray
183 NotebookTreeWidget notebookTree; // List of notebooks
184 AttributeTreeWidget attributeTree; // List of note attributes
185 TagTreeWidget tagTree; // list of user created tags
186 SavedSearchTreeWidget savedSearchTree; // list of saved searches
187 TrashTreeWidget trashTree; // Trashcan
188 TableView noteTableView; // List of notes (the widget).
190 public BrowserWindow browserWindow; // Window containing browser & labels
191 public QToolBar toolBar; // The tool bar under the menu
192 // QLineEdit searchField; // The search filter bar on the toolbar
193 QComboBox searchField; // search filter bar on the toolbar;
194 boolean searchPerformed = false; // Search was done?
195 QProgressBar quotaBar; // The current quota usage
197 ApplicationLogger logger;
198 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
199 List<String> selectedTagGUIDs; // List of selected tag GUIDs
200 List<String> selectedNoteGUIDs; // List of selected notes
201 String selectedSavedSearchGUID; // Currently selected saved searches
203 NoteFilter filter; // Note filter
204 String currentNoteGuid; // GUID of the current note
205 Note currentNote; // The currently viewed note
206 boolean noteDirty; // Has the note been changed?
207 boolean inkNote; // if this is an ink note, it is read only
209 ListManager listManager; // DB runnable task
211 List<QTemporaryFile> tempFiles; // Array of temporary files;
213 QTimer indexTimer; // timer to start the index thread
214 IndexRunner indexRunner; // thread to index notes
217 QTimer syncTimer; // Sync on an interval
218 QTimer syncDelayTimer; // Sync delay to free up database
219 SyncRunner syncRunner; // thread to do a sync.
221 QTimer saveTimer; // Timer to save note contents
223 QTimer authTimer; // Refresh authentication
224 QTimer externalFileSaveTimer; // Save files altered externally
225 List<String> externalFiles; // External files to save later
226 List<String> importFilesKeep; // Auto-import files to save later
227 List<String> importFilesDelete; // Auto-import files to save later
229 int indexTime; // how often to try and index
230 boolean indexRunning; // Is indexing running?
231 boolean indexDisabled; // Is indexing disabled?
233 int syncThreadsReady; // number of sync threads that are free
234 int syncTime; // Sync interval
235 boolean syncRunning; // Is sync running?
236 boolean automaticSync; // do sync automatically?
237 QTreeWidgetItem attributeTreeSelected;
239 QAction prevButton; // Go to the previous item viewed
240 QAction nextButton; // Go to the next item in the history
241 QAction downButton; // Go to the next item in the list
242 QAction upButton; // Go to the prev. item in the list;
243 QAction synchronizeButton; // Synchronize with Evernote
244 List<QIcon> synchronizeAnimation; // Synchronize movie
245 QTimer synchronizeAnimationTimer; // Timer to change animation button
246 int synchronizeFrame; // Current frame being viewed
247 QAction printButton; // Print Button
248 QAction tagButton; // Tag edit button
249 QAction attributeButton; // Attribute information button
250 QAction emailButton; // Email button
251 QAction deleteButton; // Delete button
252 QAction newButton; // new Note Button;
253 QSpinBox zoomSpinner; // Zoom zoom
254 QAction searchClearButton; // Clear the search field
256 QSplitter mainLeftRightSplitter; // main splitter for left/right side
257 QSplitter leftSplitter1; // first left hand splitter
258 QSplitter browserIndexSplitter; // splitter between note index & note text
260 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
261 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
262 List<String> importedFiles; // History of imported files (so we don't import twice)
264 OnlineNoteHistory historyWindow; // online history window
265 List<NoteVersionId> versions; // history versions
267 QTimer threadMonitorTimer; // Timer to watch threads.
268 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
269 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
270 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
271 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
272 int tagDeadCount=0; // number of consecutive dead times for the tag thread
273 int trashDeadCount=0; // number of consecutive dead times for the trash thread
274 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
276 HashMap<String, String> noteCache; // Cash of note content
277 List<String> historyGuids; // GUIDs of previously viewed items
278 int historyPosition; // Position within the viewed items
279 boolean fromHistory; // Is this from the history queue?
280 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
281 Thumbnailer preview; // generate preview image
282 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
284 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
287 //***************************************************************
288 //***************************************************************
289 //** Constructor & main entry point
290 //***************************************************************
291 //***************************************************************
292 // Application Constructor
293 public NeverNote(DatabaseConnection dbConn) {
296 thread().setPriority(Thread.MAX_PRIORITY);
298 logger = new ApplicationLogger("nevernote.log");
299 logger.log(logger.HIGH, "Starting Application");
301 conn.checkDatabaseVersion();
303 // Start building the invalid XML tables
304 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
305 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
307 for (int i=0; i<elements.size(); i++) {
308 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
311 logger.log(logger.EXTREME, "Starting GUI build");
313 QTranslator qtTranslator = new QTranslator();
314 qtTranslator.load("classpath:/translations/qt_" + QLocale.system().name() + ".qm");
315 QApplication.instance().installTranslator(qtTranslator);
317 QTranslator nevernoteTranslator = new QTranslator();
318 nevernoteTranslator.load("classpath:/translations/nevernote_"+QLocale.system().name()+ ".qm");
319 QApplication.instance().installTranslator(nevernoteTranslator);
321 Global.originalPalette = QApplication.palette();
322 QApplication.setStyle(Global.getStyle());
323 if (Global.useStandardPalette())
324 QApplication.setPalette(QApplication.style().standardPalette());
325 setWindowTitle("NeverNote");
327 mainLeftRightSplitter = new QSplitter();
328 setCentralWidget(mainLeftRightSplitter);
329 leftSplitter1 = new QSplitter();
330 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
332 browserIndexSplitter = new QSplitter();
333 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
335 //* Setup threads & thread timers
336 int indexRunnerCount = Global.getIndexThreads();
337 indexRunnerCount = 1;
338 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
340 logger.log(logger.EXTREME, "Building list manager");
341 listManager = new ListManager(conn, logger);
343 logger.log(logger.EXTREME, "Building index runners & timers");
344 indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
345 indexThread = new QThread(indexRunner, "Index Thread");
348 synchronizeAnimationTimer = new QTimer();
349 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
351 indexTimer = new QTimer();
352 indexTime = 1000*60*5; // look for unindexed every 5 minutes
353 // indexTime = 1000*5;
354 indexTimer.start(indexTime); // Start indexing timer
355 indexTimer.timeout.connect(this, "indexTimer()");
356 indexDisabled = false;
357 indexRunning = false;
359 logger.log(logger.EXTREME, "Setting sync thread & timers");
361 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
362 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
363 syncTimer = new QTimer();
364 syncTimer.timeout.connect(this, "syncTimer()");
365 syncRunner.status.message.connect(this, "setMessage(String)");
366 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
367 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
370 automaticSync = true;
371 syncTimer.start(syncTime*60*1000);
373 automaticSync = false;
376 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
377 syncThread = new QThread(syncRunner, "Synchronization Thread");
381 logger.log(logger.EXTREME, "Starting authentication timer");
382 authTimer = new QTimer();
383 authTimer.timeout.connect(this, "authTimer()");
384 authTimer.start(1000*60*15);
385 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
387 logger.log(logger.EXTREME, "Setting save note timer");
388 saveTimer = new QTimer();
389 saveTimer.timeout.connect(this, "saveNote()");
390 if (Global.getAutoSaveInterval() > 0) {
391 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
392 // saveTimer.setInterval(1000*10); // auto save every 20 seconds;
395 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
397 logger.log(logger.EXTREME, "Starting external file monitor timer");
398 externalFileSaveTimer = new QTimer();
399 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
400 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
401 externalFiles = new ArrayList<String>();
402 importFilesDelete = new ArrayList<String>();
403 importFilesKeep = new ArrayList<String>();
404 externalFileSaveTimer.start();
406 notebookTree = new NotebookTreeWidget();
407 attributeTree = new AttributeTreeWidget();
408 tagTree = new TagTreeWidget(conn);
409 savedSearchTree = new SavedSearchTreeWidget();
410 trashTree = new TrashTreeWidget();
411 noteTableView = new TableView(logger, listManager);
413 QGridLayout leftGrid = new QGridLayout();
414 leftSplitter1.setLayout(leftGrid);
415 leftGrid.addWidget(notebookTree, 1, 1);
416 leftGrid.addWidget(tagTree,2,1);
417 leftGrid.addWidget(attributeTree,3,1);
418 leftGrid.addWidget(savedSearchTree,4,1);
419 leftGrid.addWidget(trashTree, 5, 1);
421 // Setup the browser window
422 noteCache = new HashMap<String,String>();
423 browserWindow = new BrowserWindow(conn);
425 browserIndexSplitter.addWidget(noteTableView);
426 browserIndexSplitter.addWidget(browserWindow);
428 mainLeftRightSplitter.addWidget(leftSplitter1);
429 mainLeftRightSplitter.addWidget(browserIndexSplitter);
431 searchField = new QComboBox();
432 searchField.setEditable(true);
433 searchField.activatedIndex.connect(this, "searchFieldChanged()");
434 searchField.setDuplicatesEnabled(false);
435 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
437 quotaBar = new QProgressBar();
439 // Setup the thumbnail viewer
440 thumbnailViewer = new ThumbnailViewer();
441 thumbnailViewer.upArrow.connect(this, "upAction()");
442 thumbnailViewer.downArrow.connect(this, "downAction()");
443 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
444 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
446 listManager.loadNotesIndex();
447 initializeNotebookTree();
449 initializeSavedSearchTree();
450 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
451 attributeTreeSelected = null;
452 initializeNoteTable();
454 selectedNoteGUIDs = new ArrayList<String>();
455 statusBar = new QStatusBar();
456 setStatusBar(statusBar);
457 menuBar = new MainMenuBar(this);
458 emitLog = new ArrayList<String>();
460 tagTree.setDeleteAction(menuBar.tagDeleteAction);
461 tagTree.setEditAction(menuBar.tagEditAction);
462 tagTree.setAddAction(menuBar.tagAddAction);
463 tagTree.setVisible(Global.isWindowVisible("tagTree"));
464 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
465 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
466 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
468 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
469 notebookTree.setEditAction(menuBar.notebookEditAction);
470 notebookTree.setAddAction(menuBar.notebookAddAction);
471 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
472 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
473 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
475 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
476 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
477 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
478 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
479 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
480 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
482 noteTableView.setAddAction(menuBar.noteAdd);
483 noteTableView.setDeleteAction(menuBar.noteDelete);
484 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
485 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
486 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
487 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
488 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
489 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
490 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
491 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
492 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
494 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
495 trashTree.setEmptyAction(menuBar.emptyTrashAction);
496 trashTree.setVisible(Global.isWindowVisible("trashTree"));
497 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
498 trashTree.updateCounts(listManager.getTrashCount());
500 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
501 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
503 noteTableView.setVisible(Global.isWindowVisible("noteList"));
504 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
506 if (!Global.isWindowVisible("editorButtonBar"))
507 toggleEditorButtonBar();
508 if (!Global.isWindowVisible("leftPanel"))
509 menuBar.hideLeftSide.setChecked(true);
513 find = new FindDialog();
514 find.getOkButton().clicked.connect(this, "doFindText()");
516 // Setup the tray icon menu bar
517 trayShowAction = new QAction("Show/Hide", this);
518 trayExitAction = new QAction("Exit", this);
519 trayAddNoteAction = new QAction("Add Note", this);
521 trayExitAction.triggered.connect(this, "close()");
522 trayAddNoteAction.triggered.connect(this, "addNote()");
523 trayShowAction.triggered.connect(this, "trayToggleVisible()");
525 trayMenu = new QMenu(this);
526 trayMenu.addAction(trayAddNoteAction);
527 trayMenu.addAction(trayShowAction);
528 trayMenu.addAction(trayExitAction);
531 trayIcon = new QSystemTrayIcon(this);
532 trayIcon.setToolTip("NeverNote");
533 trayIcon.setContextMenu(trayMenu);
534 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
537 currentNoteGuid = Global.getLastViewedNoteGuid();
538 historyGuids = new ArrayList<String>();
542 if (!currentNoteGuid.trim().equals("")) {
543 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
546 noteIndexUpdated(true);
548 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
549 if (menuBar.showEditorBar.isChecked())
551 tagIndexUpdated(true);
552 savedSearchIndexUpdated();
553 notebookIndexUpdated();
555 setupSyncSignalListeners();
556 setupBrowserSignalListeners();
557 setupIndexListeners();
560 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
561 tagTree.showAllTags(true);
563 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
564 setWindowIcon(appIcon);
565 trayIcon.setIcon(appIcon);
566 if (Global.showTrayIcon())
571 scrollToGuid(currentNoteGuid);
572 if (Global.automaticLogin()) {
574 if (Global.isConnected)
577 setupFolderImports();
580 restoreWindowState();
582 if (Global.mimicEvernoteInterface) {
583 notebookTree.selectGuid("");
586 threadMonitorTimer = new QTimer();
587 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
588 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
590 historyGuids.add(currentNoteGuid);
593 int sortCol = Global.getSortColumn();
594 int sortOrder = Global.getSortOrder();
595 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
600 public static void main(String[] args) {
601 QApplication.initialize(args);
602 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
603 QSplashScreen splash = new QSplashScreen(pixmap);
606 DatabaseConnection dbConn;
609 initializeGlobalSettings(args);
611 showSplash = Global.isWindowVisible("SplashScreen");
615 dbConn = setupDatabaseConnection();
617 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
618 Global.getFileManager().purgeResDirectory();
620 } catch (InitializationException e) {
623 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
627 NeverNote application = new NeverNote(dbConn);
629 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
630 if (Global.wasWindowMaximized())
631 application.showMaximized();
635 splash.finish(application);
637 System.out.println("Goodbye.");
642 * Open the internal database, or create if not present
644 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
646 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
647 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
648 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
650 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
651 boolean goodCheck = false;
653 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
655 if (!dialog.okPressed())
657 Global.cipherPassword = dialog.getPassword();
658 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
659 Global.getDatabaseUserPassword(), Global.cipherPassword);
665 private static void initializeGlobalSettings(String[] args) throws InitializationException {
666 StartupConfig startupConfig = new StartupConfig();
668 for (String arg : args) {
669 String lower = arg.toLowerCase();
670 if (lower.startsWith("--name="))
671 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
672 if (lower.startsWith("--home="))
673 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
674 if (lower.startsWith("--disable-viewing"))
675 startupConfig.setDisableViewing(true);
678 Global.setup(startupConfig);
683 public void closeEvent(QCloseEvent event) {
684 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
687 if (currentNote!= null & browserWindow!=null) {
688 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
689 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
692 setMessage(tr("Beginning shutdown."));
694 externalFileEditedSaver();
695 if (Global.isConnected && Global.synchronizeOnClose()) {
696 setMessage(tr("Performing synchronization before closing."));
697 syncRunner.addWork("SYNC");
699 setMessage("Closing Program.");
700 threadMonitorTimer.stop();
702 syncRunner.addWork("STOP");
703 indexRunner.addWork("STOP");
708 if (tempFiles != null)
711 browserWindow.noteSignal.tagsChanged.disconnect();
712 browserWindow.noteSignal.titleChanged.disconnect();
713 browserWindow.noteSignal.noteChanged.disconnect();
714 browserWindow.noteSignal.notebookChanged.disconnect();
715 browserWindow.noteSignal.createdDateChanged.disconnect();
716 browserWindow.noteSignal.alteredDateChanged.disconnect();
717 syncRunner.searchSignal.listChanged.disconnect();
718 syncRunner.tagSignal.listChanged.disconnect();
719 syncRunner.notebookSignal.listChanged.disconnect();
720 syncRunner.noteIndexSignal.listChanged.disconnect();
723 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
724 Global.setColumnPosition("noteTableCreationPosition", position);
725 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
726 Global.setColumnPosition("noteTableTagPosition", position);
727 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
728 Global.setColumnPosition("noteTableNotebookPosition", position);
729 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
730 Global.setColumnPosition("noteTableChangedPosition", position);
731 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
732 Global.setColumnPosition("noteTableAuthorPosition", position);
733 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
734 Global.setColumnPosition("noteTableSourceUrlPosition", position);
735 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
736 Global.setColumnPosition("noteTableSubjectDatePosition", position);
737 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
738 Global.setColumnPosition("noteTableTitlePosition", position);
739 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
740 Global.setColumnPosition("noteTableSynchronizedPosition", position);
742 Global.saveWindowVisible("toolBar", toolBar.isVisible());
743 saveNoteIndexWidth();
745 int width = notebookTree.columnWidth(0);
746 Global.setColumnWidth("notebookTreeName", width);
747 width = tagTree.columnWidth(0);
748 Global.setColumnWidth("tagTreeName", width);
750 Global.saveWindowMaximized(isMaximized());
751 Global.saveCurrentNoteGuid(currentNoteGuid);
753 int sortCol = noteTableView.proxyModel.sortColumn();
754 int sortOrder = noteTableView.proxyModel.sortOrder().value();
755 Global.setSortColumn(sortCol);
756 Global.setSortOrder(sortOrder);
760 Global.keepRunning = false;
762 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
763 indexRunner.thread().join(50);
764 logger.log(logger.MEDIUM, "Index thread has stopped");
765 } catch (InterruptedException e1) {
766 e1.printStackTrace();
768 if (!syncRunner.isIdle()) {
770 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
772 logger.log(logger.MEDIUM, "Sync thread has stopped");
773 } catch (InterruptedException e1) {
774 e1.printStackTrace();
778 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
781 public void setMessage(String s) {
782 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
783 logger.log(logger.HIGH, "Message: " +s);
784 statusBar.showMessage(s);
786 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
789 private void waitCursor(boolean wait) {
791 // QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
793 // QApplication.restoreOverrideCursor();
796 private void setupIndexListeners() {
797 indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
798 indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
799 // indexRunner.threadSignal.indexNeeded.connect(listManager, "setIndexNeeded(String, String, Boolean)");
801 private void setupSyncSignalListeners() {
802 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
803 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
804 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
805 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
806 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
808 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
809 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
810 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
812 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
813 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
814 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
815 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
817 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
820 private void setupBrowserSignalListeners() {
822 browserWindow.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
823 browserWindow.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
824 browserWindow.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
825 //browserWindow.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
826 browserWindow.noteSignal.noteChanged.connect(this, "setNoteDirty()");
827 browserWindow.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
828 browserWindow.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
829 browserWindow.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
830 browserWindow.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
831 browserWindow.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
832 browserWindow.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
833 browserWindow.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
834 browserWindow.noteSignal.geoChanged.connect(this, "setNoteDirty()");
835 browserWindow.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
836 browserWindow.focusLost.connect(this, "saveNote()");
837 browserWindow.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
842 //***************************************************************
843 //***************************************************************
844 //* Settings and look & feel
845 //***************************************************************
846 //***************************************************************
847 @SuppressWarnings("unused")
848 private void settings() {
849 logger.log(logger.HIGH, "Entering NeverNote.settings");
850 ConfigDialog settings = new ConfigDialog(this);
851 String dateFormat = Global.getDateFormat();
852 String timeFormat = Global.getTimeFormat();
855 if (Global.showTrayIcon())
860 if (menuBar.showEditorBar.isChecked())
863 // Reset the save timer
864 if (Global.getAutoSaveInterval() > 0)
865 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
869 // This is a hack to force a reload of the index in case the date or time changed.
870 // if (!dateFormat.equals(Global.getDateFormat()) ||
871 // !timeFormat.equals(Global.getTimeFormat())) {
873 noteIndexUpdated(true);
876 logger.log(logger.HIGH, "Leaving NeverNote.settings");
878 // Restore things to the way they were
879 private void restoreWindowState() {
880 // We need to name things or this doesn't work.
881 setObjectName("NeverNote");
882 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
883 browserIndexSplitter.setObjectName("browserIndexSplitter");
884 leftSplitter1.setObjectName("leftSplitter1");
886 // Restore the actual positions.
887 restoreGeometry(Global.restoreGeometry(objectName()));
888 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
889 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
890 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
893 // Save window positions for the next start
894 private void saveWindowState() {
895 Global.saveGeometry(objectName(), saveGeometry());
896 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
897 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
898 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
900 // Load the style sheet
901 private void loadStyleSheet() {
902 String fileName = Global.getFileManager().getQssDirPath("default.qss");
903 QFile file = new QFile(fileName);
904 file.open(OpenModeFlag.ReadOnly);
905 String styleSheet = file.readAll().toString();
907 setStyleSheet(styleSheet);
909 // Save column widths for the next time
910 private void saveNoteIndexWidth() {
912 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
913 Global.setColumnWidth("noteTableCreationPosition", width);
914 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
915 Global.setColumnWidth("noteTableChangedPosition", width);
916 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
917 Global.setColumnWidth("noteTableGuidPosition", width);
918 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
919 Global.setColumnWidth("noteTableNotebookPosition", width);
920 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
921 Global.setColumnWidth("noteTableTagPosition", width);
922 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
923 Global.setColumnWidth("noteTableTitlePosition", width);
924 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
925 Global.setColumnWidth("noteTableSourceUrlPosition", width);
926 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
927 Global.setColumnWidth("noteTableAuthorPosition", width);
928 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
929 Global.setColumnWidth("noteTableSubjectDatePosition", width);
930 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
931 Global.setColumnWidth("noteTableSynchronizedPosition", width);
935 //***************************************************************
936 //***************************************************************
937 //** These functions deal with Notebook menu items
938 //***************************************************************
939 //***************************************************************
940 // Setup the tree containing the user's notebooks.
941 private void initializeNotebookTree() {
942 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
943 notebookTree.itemSelectionChanged.connect(this, "notebookTreeSelection()");
944 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
945 // notebookTree.resize(Global.getSize("notebookTree"));
946 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
948 // Listener when a notebook is selected
949 private void notebookTreeSelection() {
950 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
953 clearAttributeFilter();
954 clearSavedSearchFilter();
955 if (Global.mimicEvernoteInterface) {
959 menuBar.noteRestoreAction.setVisible(false);
960 menuBar.notebookEditAction.setEnabled(true);
961 menuBar.notebookDeleteAction.setEnabled(true);
962 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
963 QTreeWidgetItem currentSelection;
964 selectedNotebookGUIDs.clear();
965 if (!Global.mimicEvernoteInterface) {
966 for (int i=0; i<selections.size(); i++) {
967 currentSelection = selections.get(i);
968 selectedNotebookGUIDs.add(currentSelection.text(2));
972 // There is the potential for no notebooks to be selected if this
973 // happens then we make it look like all notebooks were selecetd.
974 // If that happens, just select the "all notebooks"
975 selections = notebookTree.selectedItems();
976 if (selections.size()==0) {
977 selectedNotebookGUIDs.clear();
978 menuBar.notebookEditAction.setEnabled(false);
979 menuBar.notebookDeleteAction.setEnabled(false);
983 if (selections.size() > 0)
984 guid = (selections.get(0).text(2));
985 if (!guid.equals(""))
986 selectedNotebookGUIDs.add(guid);
988 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
989 listManager.loadNotesIndex();
990 noteIndexUpdated(false);
991 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
994 private void clearNotebookFilter() {
995 notebookTree.blockSignals(true);
996 notebookTree.clearSelection();
997 menuBar.noteRestoreAction.setVisible(false);
998 menuBar.notebookEditAction.setEnabled(false);
999 menuBar.notebookDeleteAction.setEnabled(false);
1000 selectedNotebookGUIDs.clear();
1001 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1002 notebookTree.blockSignals(false);
1004 // Triggered when the notebook DB has been updated
1005 private void notebookIndexUpdated() {
1006 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1007 if (selectedNotebookGUIDs == null)
1008 selectedNotebookGUIDs = new ArrayList<String>();
1009 List<Notebook> books = conn.getNotebookTable().getAll();
1010 for (int i=books.size()-1; i>=0; i--) {
1011 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1012 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1014 j=listManager.getArchiveNotebookIndex().size();
1020 listManager.countNotebookResults(listManager.getNoteIndex());
1021 notebookTree.blockSignals(true);
1022 notebookTree.load(books, listManager.getLocalNotebooks());
1023 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1024 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1026 selectedNotebookGUIDs.remove(i);
1028 notebookTree.blockSignals(false);
1030 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1032 // Show/Hide note information
1033 private void toggleNotebookWindow() {
1034 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1035 if (notebookTree.isVisible())
1036 notebookTree.hide();
1038 notebookTree.show();
1039 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1040 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1041 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1043 // Add a new notebook
1044 @SuppressWarnings("unused")
1045 private void addNotebook() {
1046 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1047 NotebookEdit edit = new NotebookEdit();
1048 edit.setNotebooks(listManager.getNotebookIndex());
1051 if (!edit.okPressed())
1054 Calendar currentTime = new GregorianCalendar();
1055 Long l = new Long(currentTime.getTimeInMillis());
1056 String randint = new String(Long.toString(l));
1058 Notebook newBook = new Notebook();
1059 newBook.setUpdateSequenceNum(0);
1060 newBook.setGuid(randint);
1061 newBook.setName(edit.getNotebook());
1062 newBook.setServiceCreated(new Date().getTime());
1063 newBook.setServiceUpdated(new Date().getTime());
1064 newBook.setDefaultNotebook(false);
1065 newBook.setPublished(false);
1067 listManager.getNotebookIndex().add(newBook);
1069 listManager.getLocalNotebooks().add(newBook.getGuid());
1070 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1071 notebookIndexUpdated();
1072 listManager.countNotebookResults(listManager.getNoteIndex());
1073 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1074 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1076 // Edit an existing notebook
1077 @SuppressWarnings("unused")
1078 private void editNotebook() {
1079 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1080 NotebookEdit edit = new NotebookEdit();
1081 edit.setTitle(tr("Edit Notebook"));
1082 edit.setLocalCheckboxEnabled(false);
1083 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1084 QTreeWidgetItem currentSelection;
1085 currentSelection = selections.get(0);
1086 edit.setNotebook(currentSelection.text(0));
1087 edit.setNotebooks(listManager.getNotebookIndex());
1090 if (!edit.okPressed())
1093 String guid = currentSelection.text(2);
1094 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1095 currentSelection.setText(0, edit.getNotebook());
1097 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1098 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1099 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1100 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1101 i=listManager.getNotebookIndex().size();
1105 // Build a list of non-closed notebooks
1106 List<Notebook> nbooks = new ArrayList<Notebook>();
1107 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1108 boolean found=false;
1109 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1110 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1114 nbooks.add(listManager.getNotebookIndex().get(i));
1117 browserWindow.setNotebookList(nbooks);
1118 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1120 // Delete an existing notebook
1121 @SuppressWarnings("unused")
1122 private void deleteNotebook() {
1123 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1124 boolean assigned = false;
1125 // Check if any notes have this notebook
1126 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1127 for (int i=0; i<selections.size(); i++) {
1128 QTreeWidgetItem currentSelection;
1129 currentSelection = selections.get(i);
1130 String guid = currentSelection.text(2);
1131 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1132 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1133 if (noteGuid.equals(guid)) {
1135 j=listManager.getNoteIndex().size();
1136 i=selections.size();
1141 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1142 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1146 if (conn.getNotebookTable().getAll().size() == 1) {
1147 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1151 // If all notebooks are clear, verify the delete
1152 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected notebooks?"),
1153 QMessageBox.StandardButton.Yes,
1154 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1158 // If confirmed, delete the notebook
1159 for (int i=selections.size()-1; i>=0; i--) {
1160 QTreeWidgetItem currentSelection;
1161 currentSelection = selections.get(i);
1162 String guid = currentSelection.text(2);
1163 conn.getNotebookTable().expungeNotebook(guid, true);
1164 listManager.deleteNotebook(guid);
1166 // for (int i=<dbRunner.getLocalNotebooks().size()-1; i>=0; i--) {
1167 // if (dbRunner.getLocalNotebooks().get(i).equals(arg0))
1169 notebookTreeSelection();
1170 notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1171 listManager.countNotebookResults(listManager.getNoteIndex());
1172 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1173 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1175 // A note's notebook has been updated
1176 @SuppressWarnings("unused")
1177 private void updateNoteNotebook(String guid, String notebookGuid) {
1179 // Update the list manager
1180 listManager.updateNoteNotebook(guid, notebookGuid);
1181 listManager.countNotebookResults(listManager.getNoteIndex());
1182 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1184 // Find the name of the notebook
1185 String notebookName = null;
1186 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1187 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1188 notebookName = listManager.getNotebookIndex().get(i).getName();
1193 // If we found the name, update the browser window
1194 if (notebookName != null) {
1195 updateListNoteNotebook(guid, notebookName);
1196 if (guid.equals(currentNoteGuid)) {
1197 int pos = browserWindow.notebookBox.findText(notebookName);
1199 browserWindow.notebookBox.setCurrentIndex(pos);
1203 // If we're dealing with the current note, then we need to be sure and update the notebook there
1204 if (guid.equals(currentNoteGuid)) {
1205 if (currentNote != null) {
1206 currentNote.setNotebookGuid(notebookGuid);
1210 // Open/close notebooks
1211 @SuppressWarnings("unused")
1212 private void closeNotebooks() {
1213 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1215 if (!na.okClicked())
1219 listManager.getArchiveNotebookIndex().clear();
1221 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1222 String text = na.getClosedBookList().takeItem(i).text();
1223 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1224 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1225 Notebook n = listManager.getNotebookIndex().get(j);
1226 conn.getNotebookTable().setArchived(n.getGuid(),true);
1227 listManager.getArchiveNotebookIndex().add(n);
1228 j=listManager.getNotebookIndex().size();
1233 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1234 String text = na.getOpenBookList().takeItem(i).text();
1235 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1236 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1237 Notebook n = listManager.getNotebookIndex().get(j);
1238 conn.getNotebookTable().setArchived(n.getGuid(),false);
1239 j=listManager.getNotebookIndex().size();
1243 notebookTreeSelection();
1244 listManager.loadNotesIndex();
1245 notebookIndexUpdated();
1246 noteIndexUpdated(false);
1247 // noteIndexUpdated(false);
1249 // Build a list of non-closed notebooks
1250 List<Notebook> nbooks = new ArrayList<Notebook>();
1251 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1252 boolean found=false;
1253 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1254 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1258 nbooks.add(listManager.getNotebookIndex().get(i));
1261 browserWindow.setNotebookList(nbooks);
1268 //***************************************************************
1269 //***************************************************************
1270 //** These functions deal with Tag menu items
1271 //***************************************************************
1272 //***************************************************************
1273 // Add a new notebook
1274 @SuppressWarnings("unused")
1275 private void addTag() {
1276 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1277 TagEdit edit = new TagEdit();
1278 edit.setTagList(listManager.getTagIndex());
1281 if (!edit.okPressed())
1284 Calendar currentTime = new GregorianCalendar();
1285 Long l = new Long(currentTime.getTimeInMillis());
1286 String randint = new String(Long.toString(l));
1288 Tag newTag = new Tag();
1289 newTag.setUpdateSequenceNum(0);
1290 newTag.setGuid(randint);
1291 newTag.setName(edit.getTag());
1292 conn.getTagTable().addTag(newTag, true);
1293 listManager.getTagIndex().add(newTag);
1296 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1298 private void reloadTagTree() {
1299 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1300 tagIndexUpdated(false);
1301 boolean filter = false;
1302 listManager.countTagResults(listManager.getNoteIndex());
1303 if (notebookTree.selectedItems().size() > 0
1304 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1306 if (tagTree.selectedItems().size() > 0)
1308 tagTree.showAllTags(!filter);
1309 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1311 // Edit an existing tag
1312 @SuppressWarnings("unused")
1313 private void editTag() {
1314 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1315 TagEdit edit = new TagEdit();
1316 edit.setTitle("Edit Tag");
1317 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1318 QTreeWidgetItem currentSelection;
1319 currentSelection = selections.get(0);
1320 edit.setTag(currentSelection.text(0));
1321 edit.setTagList(listManager.getTagIndex());
1324 if (!edit.okPressed())
1327 String guid = currentSelection.text(2);
1328 currentSelection.setText(0,edit.getTag());
1330 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1331 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1332 listManager.getTagIndex().get(i).setName(edit.getTag());
1333 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1334 updateListTagName(guid);
1335 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1336 browserWindow.setTag(getTagNamesForNote(currentNote));
1337 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1341 browserWindow.setTag(getTagNamesForNote(currentNote));
1342 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1344 // Delete an existing tag
1345 @SuppressWarnings("unused")
1346 private void deleteTag() {
1347 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1349 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1350 QMessageBox.StandardButton.Yes,
1351 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1355 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1356 for (int i=selections.size()-1; i>=0; i--) {
1357 QTreeWidgetItem currentSelection;
1358 currentSelection = selections.get(i);
1359 removeTagItem(currentSelection.text(2));
1361 tagIndexUpdated(true);
1363 listManager.countTagResults(listManager.getNoteIndex());
1364 // tagTree.updateCounts(listManager.getTagCounter());
1365 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1367 // Remove a tag tree item. Go recursively down & remove the children too
1368 private void removeTagItem(String guid) {
1369 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1370 String parent = listManager.getTagIndex().get(j).getParentGuid();
1371 if (parent != null && parent.equals(guid)) {
1372 //Remove this tag's children
1373 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1376 //Now, remove this tag
1377 removeListTagName(guid);
1378 conn.getTagTable().expungeTag(guid, true);
1379 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1380 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1381 listManager.getTagIndex().remove(a);
1386 // Setup the tree containing the user's tags
1387 private void initializeTagTree() {
1388 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1389 tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1390 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1391 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1393 // Listener when a tag is selected
1394 private void tagTreeSelection() {
1395 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1398 clearAttributeFilter();
1399 clearSavedSearchFilter();
1401 menuBar.noteRestoreAction.setVisible(false);
1403 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1404 QTreeWidgetItem currentSelection;
1405 selectedTagGUIDs.clear();
1406 for (int i=0; i<selections.size(); i++) {
1407 currentSelection = selections.get(i);
1408 selectedTagGUIDs.add(currentSelection.text(2));
1410 if (selections.size() > 0) {
1411 menuBar.tagEditAction.setEnabled(true);
1412 menuBar.tagDeleteAction.setEnabled(true);
1415 menuBar.tagEditAction.setEnabled(false);
1416 menuBar.tagDeleteAction.setEnabled(false);
1418 listManager.setSelectedTags(selectedTagGUIDs);
1419 listManager.loadNotesIndex();
1420 noteIndexUpdated(false);
1421 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1423 // trigger the tag index to be refreshed
1424 @SuppressWarnings("unused")
1425 private void tagIndexUpdated() {
1426 tagIndexUpdated(true);
1428 private void tagIndexUpdated(boolean reload) {
1429 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1430 if (selectedTagGUIDs == null)
1431 selectedTagGUIDs = new ArrayList<String>();
1432 // selectedTagGUIDs.clear(); // clear out old entries
1434 tagTree.blockSignals(true);
1436 tagTree.load(listManager.getTagIndex());
1437 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1438 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1440 selectedTagGUIDs.remove(i);
1442 tagTree.blockSignals(false);
1444 browserWindow.setTag(getTagNamesForNote(currentNote));
1445 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1447 // Show/Hide note information
1448 private void toggleTagWindow() {
1449 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1450 if (tagTree.isVisible())
1454 menuBar.hideTags.setChecked(tagTree.isVisible());
1455 Global.saveWindowVisible("tagTree", tagTree.isVisible());
1456 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1458 // A note's tags have been updated
1459 @SuppressWarnings("unused")
1460 private void updateNoteTags(String guid, List<String> tags) {
1461 // Save any new tags. We'll need them later.
1462 List<String> newTags = new ArrayList<String>();
1463 for (int i=0; i<tags.size(); i++) {
1464 if (conn.getTagTable().findTagByName(tags.get(i))==null)
1465 newTags.add(tags.get(i));
1468 listManager.saveNoteTags(guid, tags);
1469 listManager.countTagResults(listManager.getNoteIndex());
1470 StringBuffer names = new StringBuffer("");
1471 for (int i=0; i<tags.size(); i++) {
1472 names = names.append(tags.get(i));
1473 if (i<tags.size()-1) {
1474 names.append(Global.tagDelimeter + " ");
1477 browserWindow.setTag(names.toString());
1480 // Now, we need to add any new tags to the tag tree
1481 for (int i=0; i<newTags.size(); i++)
1482 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
1484 // Get a string containing all tag names for a note
1485 private String getTagNamesForNote(Note n) {
1486 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
1487 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
1489 StringBuffer buffer = new StringBuffer(100);
1490 Vector<String> v = new Vector<String>();
1491 List<String> guids = n.getTagGuids();
1496 for (int i=0; i<guids.size(); i++) {
1497 v.add(listManager.getTagNameByGuid(guids.get(i)));
1499 Comparator<String> comparator = Collections.reverseOrder();
1500 Collections.sort(v,comparator);
1501 Collections.reverse(v);
1503 for (int i = 0; i<v.size(); i++) {
1505 buffer.append(", ");
1506 buffer.append(v.get(i));
1509 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
1510 return buffer.toString();
1512 // Tags were added via dropping notes from the note list
1513 @SuppressWarnings("unused")
1514 private void tagsAdded(String noteGuid, String tagGuid) {
1515 String tagName = null;
1516 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1517 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
1518 tagName = listManager.getTagIndex().get(i).getName();
1519 i=listManager.getTagIndex().size();
1522 if (tagName == null)
1525 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
1526 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
1527 List<String> tagNames = new ArrayList<String>();
1528 tagNames.add(new String(tagName));
1529 Note n = listManager.getMasterNoteIndex().get(i);
1530 for (int j=0; j<n.getTagNames().size(); j++) {
1531 tagNames.add(new String(n.getTagNames().get(j)));
1533 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
1534 if (n.getGuid().equals(currentNoteGuid)) {
1535 Collections.sort(tagNames);
1536 String display = "";
1537 for (int j=0; j<tagNames.size(); j++) {
1538 display = display+tagNames.get(j);
1539 if (j+2<tagNames.size())
1540 display = display+Global.tagDelimeter+" ";
1542 browserWindow.setTag(display);
1544 i=listManager.getMasterNoteIndex().size();
1549 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
1551 private void clearTagFilter() {
1552 tagTree.blockSignals(true);
1553 tagTree.clearSelection();
1554 menuBar.noteRestoreAction.setVisible(false);
1555 menuBar.tagEditAction.setEnabled(false);
1556 menuBar.tagDeleteAction.setEnabled(false);
1557 selectedTagGUIDs.clear();
1558 listManager.setSelectedTags(selectedTagGUIDs);
1559 tagTree.blockSignals(false);
1563 //***************************************************************
1564 //***************************************************************
1565 //** These functions deal with Saved Search menu items
1566 //***************************************************************
1567 //***************************************************************
1568 // Add a new notebook
1569 @SuppressWarnings("unused")
1570 private void addSavedSearch() {
1571 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
1572 SavedSearchEdit edit = new SavedSearchEdit();
1573 edit.setSearchList(listManager.getSavedSearchIndex());
1576 if (!edit.okPressed())
1579 Calendar currentTime = new GregorianCalendar();
1580 Long l = new Long(currentTime.getTimeInMillis());
1581 String randint = new String(Long.toString(l));
1583 SavedSearch search = new SavedSearch();
1584 search.setUpdateSequenceNum(0);
1585 search.setGuid(randint);
1586 search.setName(edit.getName());
1587 search.setQuery(edit.getQuery());
1588 search.setFormat(QueryFormat.USER);
1589 listManager.getSavedSearchIndex().add(search);
1590 conn.getSavedSearchTable().addSavedSearch(search, true);
1591 savedSearchIndexUpdated();
1592 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
1594 // Edit an existing tag
1595 @SuppressWarnings("unused")
1596 private void editSavedSearch() {
1597 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
1598 SavedSearchEdit edit = new SavedSearchEdit();
1599 edit.setTitle(tr("Edit Search"));
1600 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1601 QTreeWidgetItem currentSelection;
1602 currentSelection = selections.get(0);
1603 String guid = currentSelection.text(1);
1604 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
1605 edit.setName(currentSelection.text(0));
1606 edit.setQuery(s.getQuery());
1607 edit.setSearchList(listManager.getSavedSearchIndex());
1610 if (!edit.okPressed())
1613 List<SavedSearch> list = listManager.getSavedSearchIndex();
1614 SavedSearch search = null;
1615 boolean found = false;
1616 for (int i=0; i<list.size(); i++) {
1617 search = list.get(i);
1618 if (search.getGuid().equals(guid)) {
1625 search.setName(edit.getName());
1626 search.setQuery(edit.getQuery());
1627 conn.getSavedSearchTable().updateSavedSearch(search, true);
1628 savedSearchIndexUpdated();
1629 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
1631 // Delete an existing tag
1632 @SuppressWarnings("unused")
1633 private void deleteSavedSearch() {
1634 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
1636 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
1637 QMessageBox.StandardButton.Yes,
1638 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1642 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1643 for (int i=selections.size()-1; i>=0; i--) {
1644 QTreeWidgetItem currentSelection;
1645 currentSelection = selections.get(i);
1646 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
1647 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
1648 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
1649 listManager.getSavedSearchIndex().remove(j);
1650 j=listManager.getSavedSearchIndex().size()+1;
1653 selections.remove(i);
1655 savedSearchIndexUpdated();
1656 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
1658 // Setup the tree containing the user's tags
1659 private void initializeSavedSearchTree() {
1660 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
1661 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
1662 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
1664 // Listener when a tag is selected
1665 @SuppressWarnings("unused")
1666 private void savedSearchTreeSelection() {
1667 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
1669 clearNotebookFilter();
1672 clearAttributeFilter();
1674 String currentGuid = selectedSavedSearchGUID;
1675 menuBar.savedSearchEditAction.setEnabled(true);
1676 menuBar.savedSearchDeleteAction.setEnabled(true);
1677 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1678 QTreeWidgetItem currentSelection;
1679 selectedSavedSearchGUID = "";
1680 for (int i=0; i<selections.size(); i++) {
1681 currentSelection = selections.get(i);
1682 if (currentSelection.text(1).equals(currentGuid)) {
1683 currentSelection.setSelected(false);
1685 selectedSavedSearchGUID = currentSelection.text(1);
1687 // i = selections.size() +1;
1690 // There is the potential for no notebooks to be selected if this
1691 // happens then we make it look like all notebooks were selecetd.
1692 // If that happens, just select the "all notebooks"
1693 if (selections.size()==0) {
1694 clearSavedSearchFilter();
1696 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1698 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
1700 private void clearSavedSearchFilter() {
1701 menuBar.savedSearchEditAction.setEnabled(false);
1702 menuBar.savedSearchDeleteAction.setEnabled(false);
1703 savedSearchTree.blockSignals(true);
1704 savedSearchTree.clearSelection();
1705 savedSearchTree.blockSignals(false);
1706 selectedSavedSearchGUID = "";
1707 searchField.setEditText("");
1708 searchPerformed = false;
1709 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1711 // trigger the tag index to be refreshed
1712 private void savedSearchIndexUpdated() {
1713 if (selectedSavedSearchGUID == null)
1714 selectedSavedSearchGUID = new String();
1715 savedSearchTree.blockSignals(true);
1716 savedSearchTree.load(listManager.getSavedSearchIndex());
1717 savedSearchTree.selectGuid(selectedSavedSearchGUID);
1718 savedSearchTree.blockSignals(false);
1720 // trigger when the saved search selection changes
1721 @SuppressWarnings("unused")
1722 private void updateSavedSearchSelection() {
1723 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
1725 menuBar.savedSearchEditAction.setEnabled(true);
1726 menuBar.savedSearchDeleteAction.setEnabled(true);
1727 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1729 if (selections.size() > 0) {
1730 menuBar.savedSearchEditAction.setEnabled(true);
1731 menuBar.savedSearchDeleteAction.setEnabled(true);
1732 selectedSavedSearchGUID = selections.get(0).text(1);
1733 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
1734 searchField.setEditText(s.getQuery());
1736 menuBar.savedSearchEditAction.setEnabled(false);
1737 menuBar.savedSearchDeleteAction.setEnabled(false);
1738 selectedSavedSearchGUID = "";
1739 searchField.setEditText("");
1741 searchFieldChanged();
1743 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
1747 // Show/Hide note information
1748 private void toggleSavedSearchWindow() {
1749 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
1750 if (savedSearchTree.isVisible())
1751 savedSearchTree.hide();
1753 savedSearchTree.show();
1754 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
1756 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
1757 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
1763 //***************************************************************
1764 //***************************************************************
1765 //** These functions deal with Help menu & tool menu items
1766 //***************************************************************
1767 //***************************************************************
1768 // Show database status
1769 @SuppressWarnings("unused")
1770 private void databaseStatus() {
1772 int dirty = conn.getNoteTable().getDirtyCount();
1773 int unindexed = conn.getNoteTable().getUnindexedCount();
1774 DatabaseStatus status = new DatabaseStatus();
1775 status.setUnsynchronized(dirty);
1776 status.setUnindexed(unindexed);
1777 status.setNoteCount(conn.getNoteTable().getNoteCount());
1778 status.setNotebookCount(listManager.getNotebookIndex().size());
1779 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
1780 status.setTagCount(listManager.getTagIndex().size());
1781 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
1782 status.setWordCount(conn.getWordsTable().getWordCount());
1786 // Compact the database
1787 @SuppressWarnings("unused")
1788 private void compactDatabase() {
1789 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
1790 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
1791 "but please be aware that depending upon the size of your database this can be time consuming " +
1792 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
1793 QMessageBox.StandardButton.Yes,
1794 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
1797 setMessage("Compacting database.");
1799 listManager.compactDatabase();
1801 setMessage("Database compact is complete.");
1802 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
1804 @SuppressWarnings("unused")
1805 private void accountInformation() {
1806 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
1807 AccountDialog dialog = new AccountDialog();
1809 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
1811 @SuppressWarnings("unused")
1812 private void releaseNotes() {
1813 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
1814 QDialog dialog = new QDialog(this);
1815 QHBoxLayout layout = new QHBoxLayout();
1816 QTextEdit textBox = new QTextEdit();
1817 layout.addWidget(textBox);
1818 textBox.setReadOnly(true);
1819 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
1820 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
1821 QIODevice.OpenModeFlag.Text)))
1823 textBox.setText(file.readAll().toString());
1825 dialog.setWindowTitle(tr("Release Notes"));
1826 dialog.setLayout(layout);
1828 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
1830 // Called when user picks Log from the help menu
1831 @SuppressWarnings("unused")
1832 private void logger() {
1833 logger.log(logger.HIGH, "Entering NeverNote.logger");
1834 QDialog dialog = new QDialog(this);
1835 QHBoxLayout layout = new QHBoxLayout();
1836 QListWidget textBox = new QListWidget();
1837 layout.addWidget(textBox);
1838 textBox.addItems(emitLog);
1840 dialog.setLayout(layout);
1841 dialog.setWindowTitle(tr("Mesasge Log"));
1843 logger.log(logger.HIGH, "Leaving NeverNote.logger");
1845 // Menu option "help/about" was selected
1846 @SuppressWarnings("unused")
1847 private void about() {
1848 logger.log(logger.HIGH, "Entering NeverNote.about");
1849 QMessageBox.about(this,
1850 tr("About NeverNote"),
1851 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
1853 +tr("<hr></center>Evernote"
1854 +" Generic client.<br><br>"
1855 +"Licensed under GPL v2. <br><hr><br>"
1856 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
1857 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
1858 +"PDFRenderer is licened under the LGPL<br>"
1859 +"Jazzy is licened under the LGPL<br>"
1860 +"Java is a registered trademark of Sun Microsystems.<br><hr>"));
1861 logger.log(logger.HIGH, "Leaving NeverNote.about");
1863 // Hide the entire left hand side
1864 @SuppressWarnings("unused")
1865 private void toggleLeftSide() {
1868 hidden = !menuBar.hideLeftSide.isChecked();
1869 menuBar.hideLeftSide.setChecked(!hidden);
1871 if (notebookTree.isVisible() != hidden)
1872 toggleNotebookWindow();
1873 if (savedSearchTree.isVisible() != hidden)
1874 toggleSavedSearchWindow();
1875 if (tagTree.isVisible() != hidden)
1877 if (attributeTree.isVisible() != hidden)
1878 toggleAttributesWindow();
1879 if (trashTree.isVisible() != hidden)
1880 toggleTrashWindow();
1882 Global.saveWindowVisible("leftPanel", hidden);
1887 //***************************************************************
1888 //***************************************************************
1889 //** These functions deal with the Toolbar
1890 //***************************************************************
1891 //***************************************************************
1892 // Text in the search bar has been cleared
1893 private void searchFieldCleared() {
1894 searchField.setEditText("");
1895 saveNoteIndexWidth();
1897 // text in the search bar changed. We only use this to tell if it was cleared,
1898 // otherwise we trigger off searchFieldChanged.
1899 @SuppressWarnings("unused")
1900 private void searchFieldTextChanged(String text) {
1901 if (text.trim().equals("")) {
1902 searchFieldCleared();
1903 if (searchPerformed) {
1905 listManager.setEnSearch("");
1906 ///// listManager.clearNoteIndexSearch();
1907 //noteIndexUpdated(true);
1908 listManager.loadNotesIndex();
1909 refreshEvernoteNote(true);
1910 noteIndexUpdated(false);
1912 searchPerformed = false;
1915 // Text in the toolbar has changed
1916 private void searchFieldChanged() {
1917 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
1919 saveNoteIndexWidth();
1920 String text = searchField.currentText();
1921 listManager.setEnSearch(text.trim());
1922 listManager.loadNotesIndex();
1923 //--->>> noteIndexUpdated(true);
1924 noteIndexUpdated(false);
1925 refreshEvernoteNote(true);
1926 searchPerformed = true;
1927 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
1930 // Build the window tool bar
1931 private void setupToolBar() {
1932 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
1933 toolBar = addToolBar(tr("Tool Bar"));
1934 menuBar.setupToolBarVisible();
1935 if (!Global.isWindowVisible("toolBar"))
1936 toolBar.setVisible(false);
1938 toolBar.setVisible(true);
1940 prevButton = toolBar.addAction("Previous");
1941 QIcon prevIcon = new QIcon(iconPath+"back.png");
1942 prevButton.setIcon(prevIcon);
1943 prevButton.triggered.connect(this, "previousViewedAction()");
1945 nextButton = toolBar.addAction("Next");
1946 QIcon nextIcon = new QIcon(iconPath+"forward.png");
1947 nextButton.setIcon(nextIcon);
1948 nextButton.triggered.connect(this, "nextViewedAction()");
1950 upButton = toolBar.addAction("Up");
1951 QIcon upIcon = new QIcon(iconPath+"up.png");
1952 upButton.setIcon(upIcon);
1953 upButton.triggered.connect(this, "upAction()");
1955 downButton = toolBar.addAction("Down");
1956 QIcon downIcon = new QIcon(iconPath+"down.png");
1957 downButton.setIcon(downIcon);
1958 downButton.triggered.connect(this, "downAction()");
1960 synchronizeButton = toolBar.addAction("Synchronize");
1961 synchronizeAnimation = new ArrayList<QIcon>();
1962 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-0.png"));
1963 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-1.png"));
1964 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-2.png"));
1965 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-3.png"));
1966 synchronizeButton.setIcon(synchronizeAnimation.get(0));
1967 synchronizeFrame = 0;
1968 synchronizeButton.triggered.connect(this, "evernoteSync()");
1970 printButton = toolBar.addAction("Print");
1971 QIcon printIcon = new QIcon(iconPath+"print.png");
1972 printButton.setIcon(printIcon);
1973 printButton.triggered.connect(this, "printNote()");
1975 tagButton = toolBar.addAction("Tag");
1976 QIcon tagIcon = new QIcon(iconPath+"tag.png");
1977 tagButton.setIcon(tagIcon);
1978 tagButton.triggered.connect(browserWindow, "modifyTags()");
1980 attributeButton = toolBar.addAction("Attributes");
1981 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
1982 attributeButton.setIcon(attributeIcon);
1983 attributeButton.triggered.connect(this, "toggleNoteInformation()");
1985 emailButton = toolBar.addAction("Email");
1986 QIcon emailIcon = new QIcon(iconPath+"email.png");
1987 emailButton.setIcon(emailIcon);
1988 emailButton.triggered.connect(this, "emailNote()");
1990 deleteButton = toolBar.addAction("Delete");
1991 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
1992 deleteButton.setIcon(deleteIcon);
1993 deleteButton.triggered.connect(this, "deleteNote()");
1995 newButton = toolBar.addAction("New");
1996 QIcon newIcon = new QIcon(iconPath+"new.png");
1997 newButton.triggered.connect(this, "addNote()");
1998 newButton.setIcon(newIcon);
1999 toolBar.addSeparator();
2000 toolBar.addWidget(new QLabel(tr("Quota:")));
2001 toolBar.addWidget(quotaBar);
2002 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2006 zoomSpinner = new QSpinBox();
2007 zoomSpinner.setMinimum(10);
2008 zoomSpinner.setMaximum(1000);
2009 zoomSpinner.setAccelerated(true);
2010 zoomSpinner.setSingleStep(10);
2011 zoomSpinner.setValue(100);
2012 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2013 toolBar.addWidget(new QLabel(tr("Zoom")));
2014 toolBar.addWidget(zoomSpinner);
2016 //toolBar.addWidget(new QLabel(" "));
2017 toolBar.addSeparator();
2018 toolBar.addWidget(new QLabel(tr(" Search:")));
2019 toolBar.addWidget(searchField);
2020 QSizePolicy sizePolicy = new QSizePolicy();
2021 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2022 searchField.setSizePolicy(sizePolicy);
2023 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2025 searchClearButton = toolBar.addAction("Search Clear");
2026 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2027 searchClearButton.setIcon(searchClearIcon);
2028 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2030 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2032 // Update the sychronize button picture
2033 @SuppressWarnings("unused")
2034 private void updateSyncButton() {
2036 if (synchronizeFrame == 4)
2037 synchronizeFrame = 0;
2038 synchronizeButton.setIcon(synchronizeAnimation.get(synchronizeFrame));
2040 // Synchronize with Evernote
2041 @SuppressWarnings("unused")
2042 private void evernoteSync() {
2043 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2044 if (!Global.isConnected)
2046 if (Global.isConnected)
2047 synchronizeAnimationTimer.start(200);
2049 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2051 private void updateQuotaBar() {
2052 long limit = Global.getUploadLimit();
2053 long amount = Global.getUploadAmount();
2054 if (amount>0 && limit>0) {
2055 int percent =(int)(amount*100/limit);
2056 quotaBar.setValue(percent);
2058 quotaBar.setValue(0);
2061 @SuppressWarnings("unused")
2062 private void zoomChanged() {
2063 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2066 //****************************************************************
2067 //****************************************************************
2068 //* System Tray functions
2069 //****************************************************************
2070 //****************************************************************
2071 private void trayToggleVisible() {
2079 @SuppressWarnings("unused")
2080 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2081 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2082 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2083 trayToggleVisible();
2088 //***************************************************************
2089 //***************************************************************
2090 //** These functions deal with the trash tree
2091 //***************************************************************
2092 //***************************************************************
2093 // Setup the tree containing the trash.
2094 @SuppressWarnings("unused")
2095 private void trashTreeSelection() {
2096 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2098 clearNotebookFilter();
2100 clearAttributeFilter();
2101 clearSavedSearchFilter();
2103 String tempGuid = currentNoteGuid;
2105 // currentNoteGuid = "";
2106 currentNote = new Note();
2107 selectedNoteGUIDs.clear();
2108 listManager.getSelectedNotebooks().clear();
2109 listManager.getSelectedTags().clear();
2110 listManager.setSelectedSavedSearch("");
2111 browserWindow.clear();
2113 // toggle the add buttons
2114 newButton.setEnabled(!newButton.isEnabled());
2115 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2116 menuBar.noteAdd.setVisible(true);
2118 List<QTreeWidgetItem> selections = trashTree.selectedItems();
2119 if (selections.size() == 0) {
2120 currentNoteGuid = trashNoteGuid;
2121 trashNoteGuid = tempGuid;
2122 Global.showDeleted = false;
2123 menuBar.noteRestoreAction.setEnabled(false);
2124 menuBar.noteRestoreAction.setVisible(false);
2127 currentNoteGuid = trashNoteGuid;
2128 trashNoteGuid = tempGuid;
2129 menuBar.noteRestoreAction.setEnabled(true);
2130 menuBar.noteRestoreAction.setVisible(true);
2131 Global.showDeleted = true;
2133 listManager.loadNotesIndex();
2134 noteIndexUpdated(false);
2135 //// browserWindow.setEnabled(newButton.isEnabled());
2136 browserWindow.setReadOnly(!newButton.isEnabled());
2137 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2139 // Empty the trash file
2140 @SuppressWarnings("unused")
2141 private void emptyTrash() {
2142 // browserWindow.clear();
2143 listManager.emptyTrash();
2144 if (trashTree.selectedItems().size() > 0) {
2145 listManager.getSelectedNotebooks().clear();
2146 listManager.getSelectedTags().clear();
2147 listManager.setSelectedSavedSearch("");
2148 newButton.setEnabled(!newButton.isEnabled());
2149 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2150 menuBar.noteAdd.setVisible(true);
2151 browserWindow.clear();
2154 clearNotebookFilter();
2155 clearSavedSearchFilter();
2156 clearAttributeFilter();
2158 Global.showDeleted = false;
2159 menuBar.noteRestoreAction.setEnabled(false);
2160 menuBar.noteRestoreAction.setVisible(false);
2162 listManager.loadNotesIndex();
2163 //--->>> noteIndexUpdated(true);
2164 noteIndexUpdated(false);
2167 // Show/Hide trash window
2168 private void toggleTrashWindow() {
2169 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2170 if (trashTree.isVisible())
2174 menuBar.hideTrash.setChecked(trashTree.isVisible());
2176 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2177 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2179 private void clearTrashFilter() {
2180 Global.showDeleted = false;
2181 newButton.setEnabled(true);
2182 menuBar.noteAdd.setEnabled(true);
2183 menuBar.noteAdd.setVisible(true);
2184 trashTree.blockSignals(true);
2185 trashTree.clearSelection();
2186 trashTree.blockSignals(false);
2191 //***************************************************************
2192 //***************************************************************
2193 //** These functions deal with connection settings
2194 //***************************************************************
2195 //***************************************************************
2196 // SyncRunner had a problem and things are disconnected
2197 @SuppressWarnings("unused")
2198 private void remoteErrorDisconnect() {
2199 menuBar.connectAction.setText(tr("Connect"));
2200 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2201 menuBar.synchronizeAction.setEnabled(false);
2202 synchronizeAnimationTimer.stop();
2205 // Do a manual connect/disconnect
2206 private void remoteConnect() {
2207 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2209 if (Global.isConnected) {
2210 Global.isConnected = false;
2211 syncRunner.enDisconnect();
2212 setupConnectMenuOptions();
2217 AESEncrypter aes = new AESEncrypter();
2219 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
2220 } catch (FileNotFoundException e) {
2221 // File not found, so we'll just get empty strings anyway.
2223 String userid = aes.getUserid();
2224 String password = aes.getPassword();
2225 if (!userid.equals("") && !password.equals("")) {
2226 Global.username = userid;
2227 Global.password = password;
2230 // Show the login dialog box
2231 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
2232 LoginDialog login = new LoginDialog();
2235 if (!login.okPressed()) {
2239 Global.username = login.getUserid();
2240 Global.password = login.getPassword();
2242 syncRunner.username = Global.username;
2243 syncRunner.password = Global.password;
2244 syncRunner.userStoreUrl = Global.userStoreUrl;
2245 syncRunner.noteStoreUrl = Global.noteStoreUrl;
2246 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
2247 syncRunner.enConnect();
2248 Global.isConnected = syncRunner.isConnected;
2250 setupConnectMenuOptions();
2251 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
2253 private void setupConnectMenuOptions() {
2254 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
2255 if (!Global.isConnected) {
2256 menuBar.connectAction.setText(tr("Connect"));
2257 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
2258 menuBar.synchronizeAction.setEnabled(false);
2260 menuBar.connectAction.setText(tr("Disconnect"));
2261 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
2262 menuBar.synchronizeAction.setEnabled(true);
2264 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
2269 //***************************************************************
2270 //***************************************************************
2271 //** These functions deal with the GUI Attribute tree
2272 //***************************************************************
2273 //***************************************************************
2274 @SuppressWarnings("unused")
2275 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
2278 clearNotebookFilter();
2280 clearSavedSearchFilter();
2282 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
2283 if (item.childCount() > 0) {
2284 item.setSelected(false);
2286 Global.createdBeforeFilter.reset();
2287 Global.createdSinceFilter.reset();
2288 Global.changedBeforeFilter.reset();
2289 Global.changedSinceFilter.reset();
2290 Global.containsFilter.reset();
2291 attributeTreeSelected = item;
2292 DateAttributeFilterTable f = null;
2293 f = findDateAttributeFilterTable(item.parent());
2295 f.select(item.parent().indexOfChild(item));
2297 Global.containsFilter.select(item.parent().indexOfChild(item));
2300 listManager.loadNotesIndex();
2301 noteIndexUpdated(false);
2304 attributeTreeSelected = null;
2305 item.setSelected(false);
2306 Global.createdBeforeFilter.reset();
2307 Global.createdSinceFilter.reset();
2308 Global.changedBeforeFilter.reset();
2309 Global.changedSinceFilter.reset();
2310 Global.containsFilter.reset();
2311 listManager.loadNotesIndex();
2312 noteIndexUpdated(false);
2314 // This determines what attribute filter we need, depending upon the selection
2315 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
2316 if (w.parent() != null && w.childCount() > 0) {
2317 QTreeWidgetItem parent = w.parent();
2318 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
2319 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2320 return Global.createdSinceFilter;
2321 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
2322 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2323 return Global.createdBeforeFilter;
2324 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
2325 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
2326 return Global.changedSinceFilter;
2327 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
2328 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
2329 return Global.changedBeforeFilter;
2334 // Show/Hide attribute search window
2335 private void toggleAttributesWindow() {
2336 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
2337 if (attributeTree.isVisible())
2338 attributeTree.hide();
2340 attributeTree.show();
2341 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
2343 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
2344 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
2346 private void clearAttributeFilter() {
2347 Global.createdBeforeFilter.reset();
2348 Global.createdSinceFilter.reset();
2349 Global.changedBeforeFilter.reset();
2350 Global.changedSinceFilter.reset();
2351 Global.containsFilter.reset();
2352 attributeTreeSelected = null;
2353 attributeTree.blockSignals(true);
2354 attributeTree.clearSelection();
2355 attributeTree.blockSignals(false);
2359 //***************************************************************
2360 //***************************************************************
2361 //** These functions deal with the GUI Note index table
2362 //***************************************************************
2363 //***************************************************************
2364 // Initialize the note list table
2365 private void initializeNoteTable() {
2366 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
2367 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
2368 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
2369 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
2371 // Show/Hide trash window
2372 @SuppressWarnings("unused")
2373 private void toggleNoteListWindow() {
2374 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
2375 if (noteTableView.isVisible())
2376 noteTableView.hide();
2378 noteTableView.show();
2379 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
2381 Global.saveWindowVisible("noteList", noteTableView.isVisible());
2382 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
2384 // Handle the event that a user selects a note from the table
2385 @SuppressWarnings("unused")
2386 private void noteTableSelection() {
2387 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
2389 if (historyGuids.size() == 0) {
2390 historyGuids.add(currentNoteGuid);
2391 historyPosition = 1;
2393 noteTableView.showColumn(Global.noteTableGuidPosition);
2395 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2396 noteTableView.hideColumn(Global.noteTableGuidPosition);
2398 if (selections.size() > 0) {
2400 menuBar.noteDuplicateAction.setEnabled(true);
2401 menuBar.noteOnlineHistoryAction.setEnabled(true);
2402 menuBar.noteMergeAction.setEnabled(true);
2403 selectedNoteGUIDs.clear();
2404 if (selections.size() != 1 || Global.showDeleted) {
2405 menuBar.noteDuplicateAction.setEnabled(false);
2407 if (selections.size() != 1 || !Global.isConnected) {
2408 menuBar.noteOnlineHistoryAction.setEnabled(false);
2410 if (selections.size() == 1) {
2411 menuBar.noteMergeAction.setEnabled(false);
2413 for (int i=0; i<selections.size(); i++) {
2414 int row = selections.get(i).row();
2416 upButton.setEnabled(false);
2418 upButton.setEnabled(true);
2419 if (row < listManager.getNoteTableModel().rowCount()-1)
2420 downButton.setEnabled(true);
2422 downButton.setEnabled(false);
2423 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
2424 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
2425 currentNoteGuid = (String)ix.values().toArray()[0];
2426 selectedNoteGUIDs.add(currentNoteGuid);
2430 nextButton.setEnabled(true);
2431 prevButton.setEnabled(true);
2433 int endPosition = historyGuids.size()-1;
2434 for (int j=historyPosition; j<=endPosition; j++) {
2435 historyGuids.remove(historyGuids.size()-1);
2437 historyGuids.add(currentNoteGuid);
2438 historyPosition = historyGuids.size();
2440 if (historyPosition <= 1)
2441 prevButton.setEnabled(false);
2442 if (historyPosition == historyGuids.size())
2443 nextButton.setEnabled(false);
2445 fromHistory = false;
2446 scrollToGuid(currentNoteGuid);
2447 refreshEvernoteNote(true);
2448 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
2450 // Trigger a refresh when the note db has been updated
2451 private void noteIndexUpdated(boolean reload) {
2452 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
2454 refreshEvernoteNoteList();
2455 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
2456 noteTableView.load(reload);
2457 scrollToGuid(currentNoteGuid);
2458 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
2460 // Called when the list of notes is updated
2461 private void refreshEvernoteNoteList() {
2462 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
2463 browserWindow.setDisabled(false);
2464 if (selectedNoteGUIDs == null)
2465 selectedNoteGUIDs = new ArrayList<String>();
2466 selectedNoteGUIDs.clear(); // clear out old entries
2468 String saveCurrentNoteGuid = new String();
2469 String tempNoteGuid = new String();
2471 historyGuids.clear();
2472 historyPosition = 0;
2473 prevButton.setEnabled(false);
2474 nextButton.setEnabled(false);
2476 if (currentNoteGuid == null)
2477 currentNoteGuid = new String();
2479 for (Note note : listManager.getNoteIndex()) {
2480 tempNoteGuid = note.getGuid();
2481 if (currentNoteGuid.equals(tempNoteGuid)) {
2482 saveCurrentNoteGuid = new String(tempNoteGuid);
2486 if (listManager.getNoteIndex().size() == 0) {
2487 currentNoteGuid = "";
2489 browserWindow.clear();
2490 browserWindow.setDisabled(true);
2493 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() >0) {
2494 currentNoteGuid = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1).getGuid();
2495 currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
2496 refreshEvernoteNote(true);
2498 refreshEvernoteNote(false);
2502 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
2504 // Called when the previous arrow button is clicked
2505 @SuppressWarnings("unused")
2506 private void previousViewedAction() {
2507 if (!prevButton.isEnabled())
2509 if (historyPosition == 0)
2512 if (historyPosition <= 0)
2514 String historyGuid = historyGuids.get(historyPosition-1);
2516 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2517 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
2518 if (modelIndex != null) {
2519 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2520 String tableGuid = (String)ix.values().toArray()[0];
2521 if (tableGuid.equals(historyGuid)) {
2522 noteTableView.selectRow(i);
2528 @SuppressWarnings("unused")
2529 private void nextViewedAction() {
2530 if (!nextButton.isEnabled())
2532 String historyGuid = historyGuids.get(historyPosition);
2535 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2536 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
2537 if (modelIndex != null) {
2538 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2539 String tableGuid = (String)ix.values().toArray()[0];
2540 if (tableGuid.equals(historyGuid)) {
2541 noteTableView.selectRow(i);
2547 // Called when the up arrow is clicked
2548 @SuppressWarnings("unused")
2549 private void upAction() {
2550 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2551 int row = selections.get(0).row();
2553 noteTableView.selectRow(row-1);
2556 // Called when the down arrow is clicked
2557 @SuppressWarnings("unused")
2558 private void downAction() {
2559 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2560 int row = selections.get(0).row();
2561 int max = listManager.getNoteTableModel().rowCount();
2563 noteTableView.selectRow(row+1);
2566 // Update a tag string for a specific note in the list
2567 @SuppressWarnings("unused")
2568 private void updateListTags(String guid, List<String> tags) {
2569 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
2570 StringBuffer tagBuffer = new StringBuffer();
2571 for (int i=0; i<tags.size(); i++) {
2572 tagBuffer.append(tags.get(i));
2573 if (i<tags.size()-1)
2574 tagBuffer.append(", ");
2577 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2578 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2579 if (modelIndex != null) {
2580 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2581 String tableGuid = (String)ix.values().toArray()[0];
2582 if (tableGuid.equals(guid)) {
2583 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
2584 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2589 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
2591 // Update a title for a specific note in the list
2592 @SuppressWarnings("unused")
2593 private void updateListAuthor(String guid, String author) {
2594 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2596 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2597 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2598 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2599 if (modelIndex != null) {
2600 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2601 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2602 String tableGuid = (String)ix.values().toArray()[0];
2603 if (tableGuid.equals(guid)) {
2604 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
2605 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2610 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2612 private void updateListNoteNotebook(String guid, String notebook) {
2613 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
2614 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
2615 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
2617 // Update a title for a specific note in the list
2618 @SuppressWarnings("unused")
2619 private void updateListSourceUrl(String guid, String url) {
2620 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2622 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2623 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2624 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2625 if (modelIndex != null) {
2626 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2627 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2628 String tableGuid = (String)ix.values().toArray()[0];
2629 if (tableGuid.equals(guid)) {
2630 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2631 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
2636 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2638 private void updateListGuid(String oldGuid, String newGuid) {
2639 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2641 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2642 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2643 if (modelIndex != null) {
2644 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2645 String tableGuid = (String)ix.values().toArray()[0];
2646 if (tableGuid.equals(oldGuid)) {
2647 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
2648 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2653 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2655 private void updateListTagName(String guid) {
2656 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2658 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2659 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2660 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2662 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2663 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2664 if (modelIndex != null) {
2665 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2666 String noteGuid = (String)ix.values().toArray()[0];
2667 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2668 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2669 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2670 i=listManager.getNoteTableModel().rowCount();
2676 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2678 private void removeListTagName(String guid) {
2679 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2681 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2682 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2683 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
2684 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
2685 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
2688 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2689 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2690 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2691 if (modelIndex != null) {
2692 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2693 String noteGuid = (String)ix.values().toArray()[0];
2694 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2695 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
2696 // listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2697 i=listManager.getNoteTableModel().rowCount();
2703 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2705 private void updateListNotebookName(String oldName, String newName) {
2706 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
2708 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2709 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
2710 if (modelIndex != null) {
2711 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2712 String tableName = (String)ix.values().toArray()[0];
2713 if (tableName.equalsIgnoreCase(oldName)) {
2714 // listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2715 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
2719 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
2721 @SuppressWarnings("unused")
2722 private void updateListDateCreated(String guid, QDateTime date) {
2723 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
2725 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2726 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2727 if (modelIndex != null) {
2728 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2729 String tableGuid = (String)ix.values().toArray()[0];
2730 if (tableGuid.equals(guid)) {
2731 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2736 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2738 @SuppressWarnings("unused")
2739 private void updateListDateSubject(String guid, QDateTime date) {
2740 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
2742 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2743 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2744 if (modelIndex != null) {
2745 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2746 String tableGuid = (String)ix.values().toArray()[0];
2747 if (tableGuid.equals(guid)) {
2748 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2749 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2754 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2756 @SuppressWarnings("unused")
2757 private void updateListDateChanged(String guid, QDateTime date) {
2758 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2760 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2761 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2762 if (modelIndex != null) {
2763 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2764 String tableGuid = (String)ix.values().toArray()[0];
2765 if (tableGuid.equals(guid)) {
2766 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2767 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2772 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2774 private void updateListDateChanged() {
2775 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2776 QDateTime date = new QDateTime(QDateTime.currentDateTime());
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 tableGuid = (String)ix.values().toArray()[0];
2782 if (tableGuid.equals(currentNoteGuid)) {
2783 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2784 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2789 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2792 @SuppressWarnings("unused")
2793 private void scrollToCurrentGuid() {
2794 //scrollToGuid(currentNoteGuid);
2795 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2796 if (selections.size() == 0)
2798 QModelIndex index = selections.get(0);
2799 int row = selections.get(0).row();
2800 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
2803 // Scroll to a particular index item
2804 private void scrollToGuid(String guid) {
2805 if (currentNote == null || guid == null)
2807 if (currentNote.isActive() && Global.showDeleted) {
2808 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2809 if (!listManager.getNoteIndex().get(i).isActive()) {
2810 currentNote = listManager.getNoteIndex().get(i);
2811 currentNoteGuid = currentNote.getGuid();
2812 i = listManager.getNoteIndex().size();
2817 if (!currentNote.isActive() && !Global.showDeleted) {
2818 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2819 if (listManager.getNoteIndex().get(i).isActive()) {
2820 currentNote = listManager.getNoteIndex().get(i);
2821 currentNoteGuid = currentNote.getGuid();
2822 i = listManager.getNoteIndex().size();
2828 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2829 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
2830 if (currentNoteGuid.equals(index.data())) {
2831 // noteTableView.setCurrentIndex(index);
2832 noteTableView.selectRow(i);
2833 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
2834 i=listManager.getNoteTableModel().rowCount();
2838 // Show/Hide columns
2839 private void showColumns() {
2840 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
2841 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
2842 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
2843 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
2844 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
2845 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
2846 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
2847 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
2849 // Open a separate window
2850 @SuppressWarnings("unused")
2851 private void listDoubleClick() {
2854 // Title color has changed
2855 @SuppressWarnings("unused")
2856 private void titleColorChanged(Integer color) {
2857 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2859 QColor backgroundColor = new QColor();
2860 QColor foregroundColor = new QColor(QColor.black);
2861 backgroundColor.setRgb(color);
2863 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
2864 foregroundColor.setRgb(QColor.white.rgb());
2866 if (selectedNoteGUIDs.size() == 0)
2867 selectedNoteGUIDs.add(currentNoteGuid);
2869 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
2870 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2871 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2872 if (modelIndex != null) {
2873 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2874 String tableGuid = (String)ix.values().toArray()[0];
2875 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
2876 for (int k=0; k<Global.noteTableColumnCount; k++) {
2877 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
2878 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
2879 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
2881 i=listManager.getNoteTableModel().rowCount();
2886 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2890 //***************************************************************
2891 //***************************************************************
2892 //** These functions deal with Note specific things
2893 //***************************************************************
2894 //***************************************************************
2895 @SuppressWarnings("unused")
2896 private void setNoteDirty() {
2897 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
2899 // If the note is dirty, then it is unsynchronized by default.
2903 // Set the note as dirty and check if its status is synchronized in the display table
2905 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
2906 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
2910 // If this wasn't already marked as unsynchronized, then we need to update the table
2911 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
2912 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
2913 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
2914 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
2915 if (modelIndex != null) {
2916 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
2917 String tableGuid = (String)ix.values().toArray()[0];
2918 if (tableGuid.equals(currentNoteGuid)) {
2919 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
2925 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
2927 private void saveNote() {
2928 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
2930 logger.log(logger.EXTREME, "Note is dirty.");
2933 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
2934 preview.finished.connect(this, "saveThumbnail(String)");
2935 preview.setContent(browserWindow.getContent());
2937 logger.log(logger.EXTREME, "Saving to cache");
2938 QTextCodec codec = QTextCodec.codecForLocale();
2939 // QTextDecoder decoder = codec.makeDecoder();
2940 codec = QTextCodec.codecForName("UTF-8");
2941 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
2942 noteCache.put(currentNoteGuid, unicode.toString());
2944 logger.log(logger.EXTREME, "updating list manager");
2945 listManager.updateNoteContent(currentNoteGuid, browserWindow.getContent());
2946 // noteCache.put(currentNoteGuid, browserWindow.getContent());
2947 logger.log(logger.EXTREME, "Updating title");
2948 listManager.updateNoteTitle(currentNoteGuid, browserWindow.getTitle());
2949 updateListDateChanged();
2951 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
2952 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2953 if (listManager.getNoteIndex().get(i).getGuid().equals(currentNoteGuid)) {
2954 currentNote = listManager.getNoteIndex().get(i);
2955 i = listManager.getNoteIndex().size();
2962 // Get a note from Evernote (and put it in the browser)
2963 private void refreshEvernoteNote(boolean reload) {
2964 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
2965 if (Global.disableViewing) {
2966 browserWindow.setEnabled(false);
2970 if (!Global.showDeleted)
2971 browserWindow.setReadOnly(false);
2972 Global.cryptCounter =0;
2973 if (currentNoteGuid.equals("")) {
2974 browserWindow.setReadOnly(true);
2981 browserWindow.loadingData(true);
2983 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
2984 if (currentNote == null)
2987 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
2988 QByteArray js = new QByteArray();
2989 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
2990 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
2991 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>");
2992 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
2993 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
2994 js.append("</head>");
2995 js.append(rebuildNoteHTML(currentNoteGuid, currentNote.getContent()));
2996 js.append("</HTML>");
2997 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
2998 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
2999 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
3000 browserWindow.getBrowser().setContent(js);
3001 noteCache.put(currentNoteGuid, js.toString());
3002 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3003 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
3004 preview.finished.connect(this, "saveThumbnail(String)");
3005 preview.setContent(js.toString());
3008 logger.log(logger.HIGH, "Note content is being pulled from the cache");
3009 String cachedContent = modifyCachedTodoTags(noteCache.get(currentNoteGuid));
3010 browserWindow.getBrowser().setContent(new QByteArray(cachedContent));
3013 browserWindow.getBrowser().page().setContentEditable(!inkNote); // We don't allow editing of ink notes
3014 browserWindow.setNote(currentNote);
3016 // Build a list of non-closed notebooks
3017 List<Notebook> nbooks = new ArrayList<Notebook>();
3018 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3019 boolean found=false;
3020 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3021 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
3025 nbooks.add(listManager.getNotebookIndex().get(i));
3028 browserWindow.setNotebookList(nbooks);
3029 browserWindow.setTitle(currentNote.getTitle());
3030 browserWindow.setTag(getTagNamesForNote(currentNote));
3031 browserWindow.setAuthor(currentNote.getAttributes().getAuthor());
3033 browserWindow.setAltered(currentNote.getUpdated());
3034 browserWindow.setCreation(currentNote.getCreated());
3035 if (currentNote.getAttributes().getSubjectDate() > 0)
3036 browserWindow.setSubjectDate(currentNote.getAttributes().getSubjectDate());
3038 browserWindow.setSubjectDate(currentNote.getCreated());
3039 browserWindow.setUrl(currentNote.getAttributes().getSourceURL());
3040 browserWindow.setAllTags(listManager.getTagIndex());
3041 browserWindow.setCurrentTags(currentNote.getTagNames());
3043 scrollToGuid(currentNoteGuid);
3045 browserWindow.loadingData(false);
3046 if (thumbnailViewer.isActiveWindow())
3049 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
3051 // Save a generated thumbnail
3052 @SuppressWarnings("unused")
3053 private void saveThumbnail(String guid) {
3054 QFile tFile = new QFile(Global.getFileManager().getResDirPath("thumbnail-" + guid + ".png"));
3055 tFile.open(OpenModeFlag.ReadOnly);
3056 QByteArray imgBytes = tFile.readAll();
3058 conn.getNoteTable().setThumbnail(guid, imgBytes);
3059 conn.getNoteTable().setThumbnailNeeded(guid, false);
3060 thumbnailViewer.setThumbnail(QImage.fromData(imgBytes));
3061 if (thumbnailViewer.isVisible())
3062 thumbnailViewer.showFullScreen();
3065 QByteArray img2 = new QByteArray(conn.getNoteTable().getThumbnail(guid));
3066 QFile file = new QFile(Global.currentDir+"res/aaaa.png");
3067 file.open(OpenModeFlag.WriteOnly);
3072 // Show/Hide note information
3073 @SuppressWarnings("unused")
3074 private void toggleNoteInformation() {
3075 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
3076 browserWindow.toggleInformation();
3077 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
3078 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
3080 // Listener triggered when a print button is pressed
3081 @SuppressWarnings("unused")
3082 private void printNote() {
3083 logger.log(logger.HIGH, "Entering NeverNote.printNote");
3085 QPrintDialog dialog = new QPrintDialog();
3086 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
3087 QPrinter printer = dialog.printer();
3088 browserWindow.getBrowser().print(printer);
3090 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
3093 // Listener triggered when the email button is pressed
3094 @SuppressWarnings("unused")
3095 private void emailNote() {
3096 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
3098 if (Desktop.isDesktopSupported()) {
3099 Desktop desktop = Desktop.getDesktop();
3101 String text2 = browserWindow.getContentsToEmail();
3102 QUrl url = new QUrl("mailto:");
3103 url.addQueryItem("subject", currentNote.getTitle());
3104 url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
3105 QDesktopServices.openUrl(url);
3109 if (desktop.isSupported(Desktop.Action.MAIL)) {
3110 URI uriMailTo = null;
3112 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
3113 String text = browserWindow.getContentsToEmail();
3114 //text = "<b>" +text +"</b>";
3115 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3116 +"&BODY=" +text, null);
3117 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3118 +"&ATTACHMENT=d:/test.pdf", null);
3119 desktop.mail(uriMailTo);
3120 } catch (URISyntaxException e) {
3121 e.printStackTrace();
3122 } catch (IOException e) {
3123 e.printStackTrace();
3130 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
3132 // Reindex all notes
3133 @SuppressWarnings("unused")
3134 private void fullReindex() {
3135 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
3136 // If we are deleting non-trash notes
3137 if (currentNote.getDeleted() == 0) {
3138 if (QMessageBox.question(this, tr("Confirmation"), tr("This will cause all notes & attachments to be reindexed, "+
3139 "but please be aware that depending upon the size of your database updating all these records " +
3140 "can be time consuming and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
3141 QMessageBox.StandardButton.Yes,
3142 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3147 setMessage(tr("Marking notes for reindex."));
3148 conn.getNoteTable().reindexAllNotes();
3149 conn.getNoteTable().noteResourceTable.reindexAll();
3150 setMessage(tr("Database will be reindexed."));
3152 logger.log(logger.HIGH, "Leaving NeverNote.fullRefresh");
3154 // Listener when a user wants to reindex a specific note
3155 @SuppressWarnings("unused")
3156 private void reindexNote() {
3157 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
3158 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3159 conn.getNoteTable().setIndexNeeded(selectedNoteGUIDs.get(i), true);
3161 if (selectedNotebookGUIDs.size() > 1)
3162 setMessage(tr("Notes will be reindexed."));
3164 setMessage(tr("Note will be reindexed."));
3165 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
3168 @SuppressWarnings("unused")
3169 private void deleteNote() {
3170 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
3171 if (currentNote == null)
3173 if (currentNoteGuid.equals(""))
3176 // If we are deleting non-trash notes
3177 if (currentNote.isActive()) {
3178 if (Global.verifyDelete()) {
3179 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
3180 QMessageBox.StandardButton.Yes,
3181 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3185 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3186 selectedNoteGUIDs.add(currentNoteGuid);
3187 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3188 listManager.deleteNote(selectedNoteGUIDs.get(i));
3191 // If we are deleting from the trash.
3192 if (Global.verifyDelete()) {
3193 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
3194 QMessageBox.StandardButton.Yes,
3195 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
3199 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3200 selectedNoteGUIDs.add(currentNoteGuid);
3201 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
3202 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
3203 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
3204 if (modelIndex != null) {
3205 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3206 String tableGuid = (String)ix.values().toArray()[0];
3207 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
3208 listManager.getNoteTableModel().removeRow(j);
3213 listManager.expungeNote(selectedNoteGUIDs.get(i));
3216 currentNoteGuid = "";
3217 listManager.loadNotesIndex();
3218 noteIndexUpdated(false);
3219 refreshEvernoteNote(true);
3220 scrollToGuid(currentNoteGuid);
3221 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
3224 @SuppressWarnings("unused")
3225 private void addNote() {
3226 logger.log(logger.HIGH, "Inside NeverNote.addNote");
3227 // browserWindow.setEnabled(true);
3228 browserWindow.setReadOnly(false);
3230 Calendar currentTime = new GregorianCalendar();
3231 String noteString = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
3232 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
3233 "<en-note>\n<br clear=\"none\" /></en-note>");
3235 Long l = new Long(currentTime.getTimeInMillis());
3236 String randint = new String(Long.toString(l));
3238 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
3240 // for the first non-archived notebook. Finally, if nothing else we
3241 // pick the first notebook in the list.
3242 String notebook = null;
3243 listManager.getNotebookIndex().get(0).getGuid();
3244 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
3245 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
3246 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
3247 notebook = currentSelectedNotebook.text(2);
3249 boolean found = false;
3250 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
3251 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3252 boolean match = false;
3253 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3254 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
3256 j = listManager.getArchiveNotebookIndex().size();
3260 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
3262 // Now we have a list of good notebooks, so we can look for the default
3264 for (int i=0; i<goodNotebooks.size(); i++) {
3265 if (goodNotebooks.get(i).isDefaultNotebook()) {
3266 notebook = goodNotebooks.get(i).getGuid();
3268 i = goodNotebooks.size();
3272 if (goodNotebooks.size() > 0 && !found)
3273 notebook = goodNotebooks.get(0).getGuid();
3276 notebook = listManager.getNotebookIndex().get(0).getGuid();
3279 Note newNote = new Note();
3280 newNote.setUpdateSequenceNum(0);
3281 newNote.setGuid(randint);
3282 newNote.setNotebookGuid(notebook);
3283 newNote.setTitle("");
3284 newNote.setContent(noteString);
3285 newNote.setDeleted(0);
3286 newNote.setCreated(System.currentTimeMillis());
3287 newNote.setUpdated(System.currentTimeMillis());
3288 newNote.setActive(true);
3289 NoteAttributes na = new NoteAttributes();
3290 na.setLatitude(0.0);
3291 na.setLongitude(0.0);
3292 na.setAltitude(0.0);
3293 newNote.setAttributes(new NoteAttributes());
3294 newNote.setTagGuids(new ArrayList<String>());
3295 newNote.setTagNames(new ArrayList<String>());
3297 // If new notes are to be created based upon the selected tags, then we need to assign the tags
3298 if (Global.newNoteWithSelectedTags()) {
3299 List<QTreeWidgetItem> selections = tagTree.selectedItems();
3300 QTreeWidgetItem currentSelection;
3301 for (int i=0; i<selections.size(); i++) {
3302 currentSelection = selections.get(i);
3303 newNote.getTagGuids().add(currentSelection.text(2));
3304 newNote.getTagNames().add(currentSelection.text(0));
3308 conn.getNoteTable().addNote(newNote, true);
3309 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3310 listManager.addNote(newNote);
3311 // noteTableView.insertRow(newNote, true, -1);
3313 currentNote = newNote;
3314 currentNoteGuid = currentNote.getGuid();
3315 refreshEvernoteNote(true);
3316 listManager.countNotebookResults(listManager.getNoteIndex());
3317 browserWindow.titleLabel.setFocus();
3318 browserWindow.titleLabel.selectAll();
3319 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
3320 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
3322 // Restore a note from the trash;
3323 @SuppressWarnings("unused")
3324 private void restoreNote() {
3326 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3327 selectedNoteGUIDs.add(currentNoteGuid);
3328 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3329 listManager.restoreNote(selectedNoteGUIDs.get(i));
3331 currentNoteGuid = "";
3332 listManager.loadNotesIndex();
3333 noteIndexUpdated(false);
3336 // Search a note for specific txt
3337 @SuppressWarnings("unused")
3338 private void findText() {
3340 find.setFocusOnTextField();
3342 @SuppressWarnings("unused")
3343 private void doFindText() {
3344 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
3347 // Signal received that note content has changed. Normally we just need the guid to remove
3348 // it from the cache.
3349 @SuppressWarnings("unused")
3350 private void invalidateNoteCache(String guid, String content) {
3351 String v = noteCache.remove(guid);
3352 if (content != null) {
3353 //noteCache.put(guid, content);
3356 // Signal received that a note guid has changed
3357 @SuppressWarnings("unused")
3358 private void noteGuidChanged(String oldGuid, String newGuid) {
3359 if (noteCache.containsKey(oldGuid)) {
3360 String cache = noteCache.get(oldGuid);
3361 noteCache.put(newGuid, cache);
3362 noteCache.remove(oldGuid);
3364 listManager.updateNoteGuid(oldGuid, newGuid, false);
3365 if (currentNoteGuid.equals(oldGuid)) {
3366 if (currentNote != null)
3367 currentNote.setGuid(newGuid);
3368 currentNoteGuid = newGuid;
3370 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3371 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
3372 noteTableView.proxyModel.addGuid(newGuid);
3373 i=listManager.getNoteIndex().size();
3376 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
3377 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
3378 listManager.getNoteTableModel().titleColors.put(newGuid, color);
3379 listManager.getNoteTableModel().titleColors.remove(oldGuid);
3383 // Toggle the note editor button bar
3384 private void toggleEditorButtonBar() {
3385 if (browserWindow.buttonsVisible) {
3386 browserWindow.hideButtons();
3387 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
3388 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3390 browserWindow.buttonsVisible = true;
3391 showEditorButtons();
3393 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3395 // Show editor buttons
3396 private void showEditorButtons() {
3397 browserWindow.buttonLayout.setVisible(true);
3398 browserWindow.undoAction.setVisible(false);
3400 browserWindow.undoButton.setVisible(false);
3402 browserWindow.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
3403 browserWindow.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
3404 browserWindow.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
3405 browserWindow.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
3406 browserWindow.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
3407 browserWindow.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
3408 browserWindow.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
3409 browserWindow.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
3410 browserWindow.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
3411 browserWindow.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
3412 browserWindow.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
3413 browserWindow.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
3414 browserWindow.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
3415 browserWindow.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
3416 browserWindow.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
3417 browserWindow.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
3418 browserWindow.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
3419 browserWindow.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
3420 browserWindow.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
3421 browserWindow.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
3422 browserWindow.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
3424 private void duplicateNote(String guid) {
3426 Calendar currentTime = new GregorianCalendar();
3427 Long l = new Long(currentTime.getTimeInMillis());
3428 String newGuid = new String(Long.toString(l));
3430 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
3431 Note newNote = oldNote.deepCopy();
3432 newNote.setGuid(newGuid);
3433 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
3434 oldNote.setResources(resList);
3435 duplicateNote(oldNote);
3437 private void duplicateNote(Note oldNote) {
3439 // Now that we have a good notebook guid, we need to move the conflicting note
3440 // to the local notebook
3441 Calendar currentTime = new GregorianCalendar();
3442 Long l = new Long(currentTime.getTimeInMillis());
3443 String newGuid = new String(Long.toString(l));
3445 Note newNote = oldNote.deepCopy();
3446 newNote.setUpdateSequenceNum(0);
3447 newNote.setGuid(newGuid);
3448 newNote.setDeleted(0);
3449 newNote.setActive(true);
3450 List<Resource> resList = oldNote.getResources();
3451 if (resList == null)
3452 resList = new ArrayList<Resource>();
3454 for (int i=0; i<resList.size(); i++) {
3456 while (l == prevGuid) {
3457 currentTime = new GregorianCalendar();
3458 l = new Long(currentTime.getTimeInMillis());
3461 String newResGuid = new String(Long.toString(l));
3462 resList.get(i).setNoteGuid(newGuid);
3463 resList.get(i).setGuid(newResGuid);
3464 resList.get(i).setUpdateSequenceNum(0);
3465 resList.get(i).setActive(true);
3466 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
3468 newNote.setResources(resList);
3469 listManager.addNote(newNote);
3470 conn.getNoteTable().addNote(newNote, true);
3471 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3472 noteTableView.insertRow(newNote, true, -1);
3473 listManager.countNotebookResults(listManager.getNoteIndex());
3477 @SuppressWarnings("unused")
3478 private void mergeNotes() {
3479 logger.log(logger.HIGH, "Merging notes");
3482 String masterGuid = null;
3483 List<String> sources = new ArrayList<String>();
3485 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
3486 int r = noteTableView.selectionModel().selectedRows().get(i).row();
3487 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
3488 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3490 masterGuid = (String)ix.values().toArray()[0];
3492 sources.add((String)ix.values().toArray()[0]);
3495 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
3496 logger.log(logger.EXTREME, "Children count: "+sources.size());
3497 mergeNoteContents(masterGuid, sources);
3498 currentNoteGuid = masterGuid;
3499 noteIndexUpdated(false);
3500 refreshEvernoteNote(true);
3503 private void mergeNoteContents(String targetGuid, List<String> sources) {
3504 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
3505 String newContent = target.getContent();
3506 newContent = newContent.replace("</en-note>", "<br></br>");
3508 for (int i=0; i<sources.size(); i++) {
3509 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
3510 if (source.isSetTitle()) {
3511 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
3513 String sourceContent = source.getContent();
3514 logger.log(logger.EXTREME, "Merging contents into note");
3515 logger.log(logger.EXTREME, sourceContent);
3516 logger.log(logger.EXTREME, "End of content");
3517 int startOfNote = sourceContent.indexOf("<en-note>");
3518 sourceContent = sourceContent.substring(startOfNote+9);
3519 int endOfNote = sourceContent.indexOf("</en-note>");
3520 sourceContent = sourceContent.substring(0,endOfNote);
3521 newContent = newContent + sourceContent;
3522 logger.log(logger.EXTREME, "New note content");
3523 logger.log(logger.EXTREME, newContent);
3524 logger.log(logger.EXTREME, "End of content");
3525 for (int j=0; j<source.getResourcesSize(); j++) {
3526 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
3527 Resource r = source.getResources().get(j);
3528 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3530 Calendar currentTime = new GregorianCalendar();
3531 Long l = new Long(currentTime.getTimeInMillis());
3535 while (l == prevGuid) {
3536 currentTime = new GregorianCalendar();
3537 l = new Long(currentTime.getTimeInMillis());
3539 String newResGuid = new String(Long.toString(l));
3540 newRes.setNoteGuid(targetGuid);
3541 newRes.setGuid(newResGuid);
3542 newRes.setUpdateSequenceNum(0);
3543 newRes.setActive(true);
3544 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
3547 logger.log(logger.EXTREME, "Updating note");
3548 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
3549 for (int i=0; i<sources.size(); i++) {
3550 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
3551 listManager.deleteNote(sources.get(i));
3553 logger.log(logger.EXTREME, "Exiting merge note");
3555 // A resource within a note has had a guid change
3556 @SuppressWarnings("unused")
3557 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
3558 if (!oldGuid.equals(newGuid))
3559 Global.resourceMap.put(oldGuid, newGuid);
3561 // View a thumbnail of the note
3562 public void thumbnailView() {
3564 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
3565 QFile thumbnail = new QFile(thumbnailName);
3566 if (!thumbnail.exists()) {
3568 QImage img = new QImage();
3569 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
3570 thumbnailViewer.setThumbnail(img);
3572 thumbnailViewer.setThumbnail(thumbnailName);
3573 if (!thumbnailViewer.isVisible())
3574 thumbnailViewer.showFullScreen();
3576 // An error happened while saving a note. Inform the user
3577 @SuppressWarnings("unused")
3578 private void saveRunnerError(String guid, String msg) {
3580 String title = "*Unknown*";
3581 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
3582 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
3583 title = listManager.getMasterNoteIndex().get(i).getTitle();
3584 i=listManager.getMasterNoteIndex().size();
3587 msg = "An error has happened saving the note \"" +title+
3588 "\". \nThis is probably due to a document that is too complex for Nevernote to process. "+
3589 "As a result, changes to the note may not be saved.\n\nPlease review the note for any potential problems.";
3591 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
3595 //**********************************************************
3596 //**********************************************************
3597 //* Online user actions
3598 //**********************************************************
3599 //**********************************************************
3600 private void setupOnlineMenu() {
3601 if (!Global.isConnected) {
3602 menuBar.noteOnlineHistoryAction.setEnabled(false);
3605 menuBar.noteOnlineHistoryAction.setEnabled(true);
3608 @SuppressWarnings("unused")
3609 private void viewNoteHistory() {
3610 if (currentNoteGuid == null || currentNoteGuid.equals(""))
3612 if (currentNote.getUpdateSequenceNum() == 0) {
3613 setMessage(tr("Note has never been synchronized."));
3614 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
3618 setMessage(tr("Getting Note History"));
3620 Note currentOnlineNote = null;
3623 if (Global.isPremium())
3624 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
3626 versions = new ArrayList<NoteVersionId>();
3627 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
3628 } catch (EDAMUserException e) {
3629 setMessage("EDAMUserException: " +e.getMessage());
3631 } catch (EDAMSystemException e) {
3632 setMessage("EDAMSystemException: " +e.getMessage());
3634 } catch (EDAMNotFoundException e) {
3635 setMessage(tr("Note not found on server."));
3636 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
3638 } catch (TException e) {
3639 setMessage("EDAMTransactionException: " +e.getMessage());
3643 // If we've gotten this far, we have a good note.
3644 if (historyWindow == null) {
3645 historyWindow = new OnlineNoteHistory(conn);
3646 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
3647 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
3648 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
3650 historyWindow.historyCombo.clear();
3652 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
3653 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
3655 historyWindow.setCurrent(isDirty);
3657 loadHistoryWindowContent(currentOnlineNote);
3658 historyWindow.load(versions);
3659 setMessage(tr("History retrieved"));
3661 historyWindow.exec();
3663 private Note reloadHistoryWindow(String selection) {
3665 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
3666 String dateTimeFormat = new String(fmt);
3667 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
3671 for (int i=0; i<versions.size(); i++) {
3672 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getServiceUpdated()));
3673 if (versionDate.toString().equals(selection))
3677 if (index > -1 || selection.indexOf("Current") > -1) {
3678 Note historyNote = null;
3681 usn = versions.get(index).getUpdateSequenceNum();
3682 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
3684 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
3685 } catch (EDAMUserException e) {
3686 setMessage("EDAMUserException: " +e.getMessage());
3689 } catch (EDAMSystemException e) {
3690 setMessage("EDAMSystemException: " +e.getMessage());
3693 } catch (EDAMNotFoundException e) {
3694 setMessage("EDAMNotFoundException: " +e.getMessage());
3697 } catch (TException e) {
3698 setMessage("EDAMTransactionException: " +e.getMessage());
3704 if (historyNote != null)
3705 historyWindow.setContent(historyNote);
3711 private void loadHistoryWindowContent(Note note) {
3712 note.setUpdateSequenceNum(0);
3713 historyWindow.setContent(note);
3715 @SuppressWarnings("unused")
3716 private void restoreHistoryNoteAsNew() {
3717 setMessage(tr("Restoring as new note."));
3718 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
3719 setMessage(tr("Note has been restored as a new note."));
3721 @SuppressWarnings("unused")
3722 private void restoreHistoryNote() {
3723 setMessage(tr("Restoring note."));
3724 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
3725 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
3728 for (int i=0; i<n.getResourcesSize(); i++) {
3729 n.getResources().get(i).setActive(true);
3730 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
3732 listManager.addNote(n);
3733 conn.getNoteTable().addNote(n, true);
3734 refreshEvernoteNote(true);
3735 setMessage(tr("Note has been restored."));
3740 //**********************************************************
3741 //**********************************************************
3742 //* XML Modifying methods
3743 //**********************************************************
3744 //**********************************************************
3745 // find the appropriate icon for an attachment
3746 private String findIcon(String appl) {
3747 logger.log(logger.HIGH, "Entering NeverNote.findIcon");
3748 appl = appl.toLowerCase();
3749 String relativePath = appl + ".png";
3750 File f = Global.getFileManager().getImageDirFile(relativePath);
3752 return relativePath;
3756 logger.log(logger.HIGH, "Leaving NeverNote.findIcon");
3757 return "attachment.png";
3759 // Modify the en-media tag into an attachment
3760 private void modifyApplicationTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {
3761 logger.log(logger.HIGH, "Entering NeverNote.modifyApplicationTags");
3762 if (appl.equalsIgnoreCase("vnd.evernote.ink"))
3764 String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());
3765 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);
3766 if (r == null || r.getData() == null)
3767 resourceErrorMessage();
3769 if (r.getData()!=null) {
3770 // Did we get a generic applicaiton? Then look at the file name to
3771 // try and find a good application type for the icon
3772 if (appl.equalsIgnoreCase("octet-stream")) {
3773 if (r.getAttributes() != null && r.getAttributes().getFileName() != null) {
3774 String fn = r.getAttributes().getFileName();
3775 int pos = fn.lastIndexOf(".");
3777 appl = fn.substring(pos+1);
3782 String fileDetails = null;
3783 if (r.getAttributes() != null && r.getAttributes().getFileName() != null && !r.getAttributes().getFileName().equals(""))
3784 fileDetails = r.getAttributes().getFileName();
3785 String contextFileName;
3786 FileManager fileManager = Global.getFileManager();
3787 if (fileDetails != null && !fileDetails.equals("")) {
3788 enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +fileDetails);
3789 contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + fileDetails);
3791 enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +appl);
3792 contextFileName = fileManager.getResDirPath(r.getGuid() + Global.attachmentNameDelimeter + appl);
3794 contextFileName = contextFileName.replace("\\", "/");
3795 enmedia.setAttribute("onContextMenu", "window.jambi.resourceContextMenu('" +contextFileName +"');");
3796 if (fileDetails == null || fileDetails.equals(""))
3798 enmedia.setAttribute("en-tag", "en-media");
3799 enmedia.setAttribute("guid", r.getGuid());
3800 enmedia.setTagName("a");
3801 QDomElement newText = doc.createElement("img");
3802 boolean goodPreview = false;
3803 String filePath = "";
3804 if (appl.equalsIgnoreCase("pdf") && Global.pdfPreview()) {
3806 Resource res = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3807 if (res.getAttributes() != null &&
3808 res.getAttributes().getFileName() != null &&
3809 !res.getAttributes().getFileName().trim().equals(""))
3810 fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();
3812 fileName = res.getGuid()+".pdf";
3813 QFile file = new QFile(fileManager.getResDirPath(fileName));
3814 QFile.OpenMode mode = new QFile.OpenMode();
3815 mode.set(QFile.OpenModeFlag.WriteOnly);
3817 QDataStream out = new QDataStream(file);
3818 Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);
3819 QByteArray binData = new QByteArray(resBinary.getData().getBody());
3821 out.writeBytes(binData.toByteArray());
3823 PDFPreview pdfPreview = new PDFPreview();
3824 goodPreview = pdfPreview.setupPreview(file.fileName(), appl,0);
3826 QDomElement span = doc.createElement("span");
3827 QDomElement table = doc.createElement("table");
3828 span.setAttribute("pdfNavigationTable", "true");
3829 QDomElement tr = doc.createElement("tr");
3830 QDomElement td = doc.createElement("td");
3831 QDomElement left = doc.createElement("img");
3832 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3833 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3834 left.setAttribute("onMouseOver", "style.cursor='hand'");
3835 QDomElement right = doc.createElement("img");
3836 right.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3837 left.setAttribute("onMouseDown", "window.jambi.previousPage('" +file.fileName() +"')");
3838 // NFC TODO: should these be file:// URLs?
3839 left.setAttribute("src", Global.getFileManager().getImageDirPath("small_left.png"));
3840 right.setAttribute("src", Global.getFileManager().getImageDirPath("small_right.png"));
3841 right.setAttribute("onMouseOver", "style.cursor='hand'");
3843 table.appendChild(tr);
3845 td.appendChild(left);
3846 td.appendChild(right);
3847 span.appendChild(table);
3848 enmedia.parentNode().insertBefore(span, enmedia);
3850 filePath = fileName+".png";
3852 String icon = findIcon(appl);
3853 if (icon.equals("attachment.png"))
3854 icon = findIcon(fileDetails.substring(fileDetails.indexOf(".")+1));
3855 // NFC TODO: should this be a 'file://' URL?
3856 newText.setAttribute("src", Global.getFileManager().getImageDirPath(icon));
3858 // NFC TODO: should this be a 'file://' URL?
3859 newText.setAttribute("src", fileManager.getResDirPath(filePath));
3860 newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");
3862 newText.setAttribute("title", fileDetails);
3863 enmedia.removeChild(enmedia.firstChild());
3865 enmedia.appendChild(newText);
3868 logger.log(logger.HIGH, "Leaving NeverNote.modifyApplicationTags");
3870 // Modify the en-to tag into an input field
3871 private void modifyTodoTags(QDomElement todo) {
3872 logger.log(logger.HIGH, "Entering NeverNote.modifyTodoTags");
3873 todo.setAttribute("type", "checkbox");
3874 String checked = todo.attribute("checked");
3875 todo.removeAttribute("checked");
3876 if (checked.equalsIgnoreCase("true"))
3877 todo.setAttribute("checked", "");
3879 todo.setAttribute("unchecked","");
3880 todo.setAttribute("value", checked);
3881 todo.setAttribute("onClick", "value=checked;window.jambi.contentChanged(); ");
3882 todo.setTagName("input");
3883 logger.log(logger.HIGH, "Leaving NeverNote.modifyTodoTags");
3885 // Modify any cached todo tags that may have changed
3886 private String modifyCachedTodoTags(String note) {
3887 logger.log(logger.HIGH, "Entering NeverNote.modifyCachedTodoTags");
3888 StringBuffer html = new StringBuffer(note);
3889 for (int i=html.indexOf("<input", 0); i>-1; i=html.indexOf("<input", i)) {
3890 int endPos =html.indexOf(">",i+1);
3891 String input = html.substring(i,endPos);
3892 if (input.indexOf("value=\"true\"") > 0)
3893 input = input.replace(" unchecked=\"\"", " checked=\"\"");
3895 input = input.replace(" checked=\"\"", " unchecked=\"\"");
3896 html.replace(i, endPos, input);
3899 logger.log(logger.HIGH, "Leaving NeverNote.modifyCachedTodoTags");
3900 return html.toString();
3902 // Modify the en-media tag into an image tag so it can be displayed.
3903 private void modifyImageTags(QDomElement docElem, QDomElement enmedia, QDomAttr hash) {
3904 logger.log(logger.HIGH, "Entering NeverNote.modifyImageTags");
3905 String type = enmedia.attribute("type");
3906 if (type.startsWith("image/"))
3907 type = "."+type.substring(6);
3911 String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNoteGuid, hash.value());
3912 QFile tfile = new QFile(Global.getFileManager().getResDirPath(resGuid + type));
3913 if (!tfile.exists()) {
3915 if (resGuid != null)
3916 r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid,true);
3917 if (r==null || r.getData() == null || r.getData().getBody().length == 0)
3918 resourceErrorMessage();
3919 if (r!= null && r.getData() != null && r.getData().getBody().length > 0) {
3920 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));
3921 QByteArray binData = new QByteArray(r.getData().getBody());
3922 tfile.write(binData);
3924 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3925 enmedia.setAttribute("en-tag", "en-media");
3926 enmedia.setNodeValue("");
3927 enmedia.setAttribute("guid", r.getGuid());
3928 enmedia.setTagName("img");
3931 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3932 enmedia.setAttribute("en-tag", "en-media");
3933 enmedia.setAttribute("onContextMenu", "window.jambi.imageContextMenu('" +tfile.fileName() +"');");
3934 enmedia.setNodeValue("");
3935 enmedia.setAttribute("guid", resGuid);
3936 enmedia.setTagName("img");
3938 logger.log(logger.HIGH, "Leaving NeverNote.modifyImageTags");
3940 // Modify tags from Evernote specific things to XHTML tags.
3941 private QDomDocument modifyTags(QDomDocument doc) {
3942 logger.log(logger.HIGH, "Entering NeverNote.modifyTags");
3943 if (tempFiles == null)
3944 tempFiles = new ArrayList<QTemporaryFile>();
3946 QDomElement docElem = doc.documentElement();
3948 // Modify en-media tags
3949 QDomNodeList anchors = docElem.elementsByTagName("en-media");
3950 int enMediaCount = anchors.length();
3951 for (int i=enMediaCount-1; i>=0; i--) {
3952 QDomElement enmedia = anchors.at(i).toElement();
3953 if (enmedia.hasAttribute("type")) {
3954 QDomAttr attr = enmedia.attributeNode("type");
3955 QDomAttr hash = enmedia.attributeNode("hash");
3956 String[] type = attr.nodeValue().split("/");
3957 String appl = type[1];
3959 if (type[0] != null) {
3960 if (type[0].equals("image")) {
3961 modifyImageTags(docElem, enmedia, hash);
3963 if (!type[0].equals("image")) {
3964 modifyApplicationTags(doc, docElem, enmedia, hash, appl);
3971 anchors = docElem.elementsByTagName("en-todo");
3972 int enTodoCount = anchors.length();
3973 for (int i=enTodoCount-1; i>=0; i--) {
3974 QDomElement enmedia = anchors.at(i).toElement();
3975 modifyTodoTags(enmedia);
3978 // Modify en-crypt tags
3979 anchors = docElem.elementsByTagName("en-crypt");
3980 int enCryptLen = anchors.length();
3981 for (int i=enCryptLen-1; i>=0; i--) {
3982 QDomElement enmedia = anchors.at(i).toElement();
3983 enmedia.setAttribute("contentEditable","false");
3984 enmedia.setAttribute("src", Global.getFileManager().getImageDirPath("encrypt.png"));
3985 enmedia.setAttribute("en-tag","en-crypt");
3986 enmedia.setAttribute("alt", enmedia.text());
3987 Global.cryptCounter++;
3988 enmedia.setAttribute("id", "crypt"+Global.cryptCounter.toString());
3989 String encryptedText = enmedia.text();
3991 // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
3992 if (encryptedText.endsWith("\n"))
3993 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
3994 if (encryptedText.endsWith("\r"))
3995 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
3998 String hint = enmedia.attribute("hint");
3999 hint = hint.replace("'","'");
4000 enmedia.setAttribute("onClick", "window.jambi.decryptText('crypt"+Global.cryptCounter.toString()+"', '"+encryptedText+"', '"+hint+"');");
4001 enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
4002 enmedia.setTagName("img");
4003 enmedia.removeChild(enmedia.firstChild()); // Remove the actual encrypted text
4008 anchors = docElem.elementsByTagName("a");
4009 enCryptLen = anchors.length();
4010 for (int i=0; i<anchors.length(); i++) {
4011 QDomElement element = anchors.at(i).toElement();
4012 element.setAttribute("title", element.attribute("href"));
4015 logger.log(logger.HIGH, "Leaving NeverNote.modifyTags");
4018 // Rebuild the note HTML to something usable
4019 private String rebuildNoteHTML(String noteGuid, String note) {
4020 logger.log(logger.HIGH, "Entering NeverNote.rebuildNoteHTML");
4021 logger.log(logger.EXTREME, "Note guid: " +noteGuid);
4022 logger.log(logger.EXTREME, "Note Text:" +note);
4023 QDomDocument doc = new QDomDocument();
4024 QDomDocument.Result result = doc.setContent(note);
4025 if (!result.success) {
4026 logger.log(logger.MEDIUM, "Parse error when rebuilding HTML");
4027 logger.log(logger.MEDIUM, "Note guid: " +noteGuid);
4028 logger.log(logger.EXTREME, "Start of unmodified note HTML");
4029 logger.log(logger.EXTREME, note);
4030 logger.log(logger.EXTREME, "End of unmodified note HTML");
4034 if (tempFiles == null)
4035 tempFiles = new ArrayList<QTemporaryFile>();
4038 doc = modifyTags(doc);
4039 doc = addHilight(doc);
4040 QDomElement docElem = doc.documentElement();
4041 docElem.setTagName("Body");
4042 // docElem.setAttribute("bgcolor", "green");
4043 logger.log(logger.EXTREME, "Rebuilt HTML:");
4044 logger.log(logger.EXTREME, doc.toString());
4045 logger.log(logger.HIGH, "Leaving NeverNote.rebuildNoteHTML");
4046 // Fix the stupid problem where inserting an <img> tag after an <a> tag (which is done
4047 // to get the <en-media> application tag to work properly) causes spaces to be inserted
4048 // between the <a> & <img>. This messes things up later. This is an ugly hack.
4049 StringBuffer html = new StringBuffer(doc.toString());
4050 for (int i=html.indexOf("<a en-tag=\"en-media\" ", 0); i>-1; i=html.indexOf("<a en-tag=\"en-media\" ", i)) {
4051 i=html.indexOf(">\n",i+1);
4052 int z = html.indexOf("<img",i);
4053 for (int j=z-1; j>i; j--)
4054 html.deleteCharAt(j);
4055 i=html.indexOf("/>", z+1);
4056 z = html.indexOf("</a>",i);
4057 for (int j=z-1; j>i+1; j--)
4058 html.deleteCharAt(j);
4060 return html.toString();
4062 // Scan and do hilighting of words
4063 private QDomDocument addHilight(QDomDocument doc) {
4064 EnSearch e = listManager.getEnSearch();
4065 if (e.hilightWords == null || e.hilightWords.size() == 0)
4067 XMLInsertHilight hilight = new XMLInsertHilight(doc, listManager.getEnSearch().hilightWords);
4068 return hilight.getDoc();
4071 // An error has happended fetching a resource. let the user know
4072 private void resourceErrorMessage() {
4075 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4076 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4077 "In a perfect world this wouldn't happen, but it has.\n" +
4078 "It is embarasing when a program like me, designed to save all your\n"+
4079 "precious data, has a problem finding data.\n\n" +
4080 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
4081 "In the mean time, I'm not going to let you make changes to this note.\n" +
4082 "Don't get angry. I'm doing it to prevent you from messing up\n"+
4083 "this note on the Evernote servers. Sorry."+
4084 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4086 //// browserWindow.setEnabled(false);
4087 browserWindow.setReadOnly(true);
4093 //**********************************************************
4094 //**********************************************************
4096 //**********************************************************
4097 //**********************************************************
4098 // We should now do a sync with Evernote
4099 private void syncTimer() {
4100 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
4101 syncRunner.syncNeeded = true;
4102 syncRunner.disableUploads = Global.disableUploads;
4104 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
4106 private void syncStart() {
4107 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
4109 if (!syncRunning && Global.isConnected) {
4110 syncRunner.setConnected(true);
4111 syncRunner.setKeepRunning(Global.keepRunning);
4112 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
4114 if (syncThreadsReady > 0) {
4115 saveNoteIndexWidth();
4116 if (syncRunner.addWork("SYNC")) {
4118 syncRunner.syncNeeded = true;
4123 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
4125 @SuppressWarnings("unused")
4126 private void syncThreadComplete(Boolean refreshNeeded) {
4127 setMessage(tr("Finalizing Synchronization"));
4129 syncRunning = false;
4130 syncRunner.syncNeeded = false;
4131 synchronizeAnimationTimer.stop();
4132 synchronizeButton.setIcon(synchronizeAnimation.get(0));
4134 if (currentNote == null) {
4135 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
4137 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
4138 noteIndexUpdated(false);
4139 noteTableView.selectionModel().blockSignals(true);
4140 scrollToGuid(currentNoteGuid);
4141 noteTableView.selectionModel().blockSignals(false);
4142 refreshEvernoteNote(false);
4143 scrollToGuid(currentNoteGuid);
4145 if (!syncRunner.error)
4146 setMessage(tr("Synchronization Complete"));
4148 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
4149 logger.log(logger.MEDIUM, "Sync complete.");
4151 public void saveUploadAmount(long t) {
4152 Global.saveUploadAmount(t);
4154 public void saveUserInformation(User user) {
4155 Global.saveUserInformation(user);
4157 public void saveEvernoteUpdateCount(int i) {
4158 Global.saveEvernoteUpdateCount(i);
4160 public void refreshLists() {
4161 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
4163 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
4164 tagIndexUpdated(true);
4165 notebookIndexUpdated();
4166 savedSearchIndexUpdated();
4167 listManager.loadNotesIndex();
4169 noteTableView.selectionModel().blockSignals(true);
4170 noteIndexUpdated(true);
4171 noteTableView.selectionModel().blockSignals(false);
4172 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
4176 @SuppressWarnings("unused")
4177 private void authTimer() {
4178 Calendar cal = Calendar.getInstance();
4180 // If we are not connected let's get out of here
4181 if (!Global.isConnected)
4184 // If this is the first time through, then we need to set this
4185 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
4186 // syncRunner.authRefreshTime = cal.getTimeInMillis();
4188 // long now = new Date().getTime();
4189 // if (now > Global.authRefreshTime && Global.isConnected) {
4190 syncRunner.authRefreshNeeded = true;
4194 @SuppressWarnings("unused")
4195 private void authRefreshComplete(boolean goodSync) {
4196 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
4197 Global.isConnected = syncRunner.isConnected;
4199 // authTimer.start((int)syncRunner.authTimeRemaining/4);
4200 authTimer.start(1000*60*15);
4201 logger.log(logger.LOW, "Authentication token has been renewed");
4202 // setMessage("Authentication token has been renewed.");
4204 authTimer.start(1000*60*5);
4205 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
4206 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
4208 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
4212 @SuppressWarnings("unused")
4213 private synchronized void indexTimer() {
4214 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
4217 // Look for any unindexed notes. We only refresh occasionally
4218 // and do one at a time to keep overhead down.
4219 if (!indexDisabled && indexRunner.getWorkQueueSize() == 0) {
4220 List<String> notes = conn.getNoteTable().getNextUnindexed(1);
4221 String unindexedNote = null;
4222 if (notes.size() > 0)
4223 unindexedNote = notes.get(0);
4224 if (unindexedNote != null && Global.keepRunning) {
4225 indexNoteContent(unindexedNote);
4227 if (notes.size()>0) {
4228 indexTimer.setInterval(100);
4231 List<String> unindexedResources = conn.getNoteTable().noteResourceTable.getNextUnindexed(1);
4232 if (unindexedResources.size() > 0 && indexRunner.getWorkQueueSize() == 0) {
4233 String unindexedResource = unindexedResources.get(0);
4234 if (unindexedResource != null && Global.keepRunning) {
4235 indexNoteResource(unindexedResource);
4238 if (unindexedResources.size() > 0) {
4239 indexTimer.setInterval(100);
4242 indexTimer.setInterval(indexTime);
4245 setMessage(tr("Index completed."));
4246 logger.log(logger.LOW, "Indexing has completed.");
4247 indexRunning = false;
4248 indexTimer.setInterval(indexTime);
4251 logger.log(logger.EXTREME, "Leaving neverNote index timer");
4253 private synchronized void indexNoteContent(String unindexedNote) {
4254 logger.log(logger.EXTREME, "Entering NeverNote.indexNoteContent()");
4255 logger.log(logger.MEDIUM, "Unindexed Note found: "+unindexedNote);
4256 indexRunner.setIndexType(indexRunner.CONTENT);
4257 indexRunner.addWork("CONTENT "+unindexedNote);
4258 if (!indexRunning) {
4259 setMessage(tr("Indexing notes."));
4260 logger.log(logger.LOW, "Beginning to index note contents.");
4261 indexRunning = true;
4263 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteContent()");
4265 private synchronized void indexNoteResource(String unindexedResource) {
4266 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4267 indexRunner.addWork(new String("RESOURCE "+unindexedResource));
4268 if (!indexRunning) {
4269 setMessage(tr("Indexing notes."));
4270 indexRunning = true;
4272 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4274 @SuppressWarnings("unused")
4275 private void indexThreadComplete(String guid) {
4276 logger.log(logger.MEDIUM, "Index complete for "+guid);
4278 @SuppressWarnings("unused")
4279 private synchronized void toggleNoteIndexing() {
4280 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
4281 indexDisabled = !indexDisabled;
4283 setMessage(tr("Indexing is now enabled."));
4285 setMessage(tr("Indexing is now disabled."));
4286 menuBar.disableIndexing.setChecked(indexDisabled);
4287 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
4290 @SuppressWarnings("unused")
4291 private void threadMonitorCheck() {
4296 alive = listManager.threadCheck(Global.tagCounterThreadId);
4299 if (tagDeadCount > MAX)
4300 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
4301 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4305 alive = listManager.threadCheck(Global.notebookCounterThreadId);
4307 notebookThreadDeadCount++;
4308 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
4309 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4311 notebookThreadDeadCount=0;
4313 alive = listManager.threadCheck(Global.trashCounterThreadId);
4316 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
4317 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4321 alive = listManager.threadCheck(Global.saveThreadId);
4323 saveThreadDeadCount++;
4324 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
4325 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4327 saveThreadDeadCount=0;
4329 if (!syncThread.isAlive()) {
4330 syncThreadDeadCount++;
4331 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
4332 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4334 syncThreadDeadCount=0;
4336 if (!indexThread.isAlive()) {
4337 indexThreadDeadCount++;
4338 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
4339 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
4341 indexThreadDeadCount=0;
4348 //**************************************************
4349 //* Backup & Restore
4350 //**************************************************
4351 @SuppressWarnings("unused")
4352 private void databaseBackup() {
4353 QFileDialog fd = new QFileDialog(this);
4354 fd.setFileMode(FileMode.AnyFile);
4355 fd.setConfirmOverwrite(true);
4356 fd.setWindowTitle(tr("Backup Database"));
4357 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4358 fd.setAcceptMode(AcceptMode.AcceptSave);
4359 fd.setDirectory(System.getProperty("user.home"));
4360 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4366 setMessage(tr("Backing up database"));
4368 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
4370 ExportData noteWriter = new ExportData(conn, true);
4371 String fileName = fd.selectedFiles().get(0);
4373 if (!fileName.endsWith(".nnex"))
4374 fileName = fileName +".nnex";
4375 noteWriter.exportData(fileName);
4376 setMessage(tr("Database backup completed."));
4381 @SuppressWarnings("unused")
4382 private void databaseRestore() {
4383 if (QMessageBox.question(this, tr("Confirmation"),
4384 tr("This is used to restore a database from backups.\n" +
4385 "It is HIGHLY recommened that this only be used to populate\n" +
4386 "an empty database. Restoring into a database that\n already has data" +
4387 " can cause problems.\n\nAre you sure you want to continue?"),
4388 QMessageBox.StandardButton.Yes,
4389 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4394 QFileDialog fd = new QFileDialog(this);
4395 fd.setFileMode(FileMode.ExistingFile);
4396 fd.setConfirmOverwrite(true);
4397 fd.setWindowTitle(tr("Restore Database"));
4398 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4399 fd.setAcceptMode(AcceptMode.AcceptOpen);
4400 fd.setDirectory(System.getProperty("user.home"));
4401 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4407 setMessage(tr("Restoring database"));
4408 ImportData noteReader = new ImportData(conn, true);
4409 noteReader.importData(fd.selectedFiles().get(0));
4411 if (noteReader.lastError != 0) {
4412 setMessage(noteReader.getErrorMessage());
4413 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
4418 listManager.loadNoteTitleColors();
4420 refreshEvernoteNote(true);
4421 setMessage(tr("Database has been restored."));
4424 @SuppressWarnings("unused")
4425 private void exportNotes() {
4426 QFileDialog fd = new QFileDialog(this);
4427 fd.setFileMode(FileMode.AnyFile);
4428 fd.setConfirmOverwrite(true);
4429 fd.setWindowTitle(tr("Backup Database"));
4430 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4431 fd.setAcceptMode(AcceptMode.AcceptSave);
4432 fd.setDirectory(System.getProperty("user.home"));
4433 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4439 setMessage(tr("Exporting Notes"));
4442 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4443 selectedNoteGUIDs.add(currentNoteGuid);
4445 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
4446 String fileName = fd.selectedFiles().get(0);
4448 if (!fileName.endsWith(".nnex"))
4449 fileName = fileName +".nnex";
4450 noteWriter.exportData(fileName);
4451 setMessage(tr("Export completed."));
4457 @SuppressWarnings("unused")
4458 private void importNotes() {
4459 QFileDialog fd = new QFileDialog(this);
4460 fd.setFileMode(FileMode.ExistingFile);
4461 fd.setConfirmOverwrite(true);
4462 fd.setWindowTitle(tr("Import Notes"));
4463 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4464 fd.setAcceptMode(AcceptMode.AcceptOpen);
4465 fd.setDirectory(System.getProperty("user.home"));
4466 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4472 setMessage("Importing Notes");
4475 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4476 selectedNoteGUIDs.add(currentNoteGuid);
4478 ImportData noteReader = new ImportData(conn, false);
4479 String fileName = fd.selectedFiles().get(0);
4481 if (!fileName.endsWith(".nnex"))
4482 fileName = fileName +".nnex";
4483 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
4484 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
4486 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
4488 noteReader.importData(fileName);
4490 if (noteReader.lastError != 0) {
4491 setMessage(noteReader.getErrorMessage());
4492 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
4497 listManager.loadNoteTitleColors();
4499 refreshEvernoteNote(false);
4500 setMessage(tr("Notes have been imported."));
4503 setMessage("Import completed.");
4510 //**************************************************
4511 //* Duplicate a note
4512 //**************************************************
4513 @SuppressWarnings("unused")
4514 private void duplicateNote() {
4516 duplicateNote(currentNoteGuid);
4521 //**************************************************
4523 //**************************************************
4524 public void setupFolderImports() {
4525 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
4527 if (importKeepWatcher == null)
4528 importKeepWatcher = new QFileSystemWatcher();
4529 if (importDeleteWatcher == null) {
4530 importDeleteWatcher = new QFileSystemWatcher();
4531 for (int i=0; i<records.size(); i++) {
4532 if (!records.get(i).keep)
4533 folderImportDelete(records.get(i).folder);
4539 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
4540 for (int i=0; i<records.size(); i++) {
4541 if (records.get(i).keep)
4542 importKeepWatcher.addPath(records.get(i).folder);
4544 importDeleteWatcher.addPath(records.get(i).folder);
4547 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
4548 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
4550 // Look at the files already there so we don't import them again if a new file is created
4551 if (importedFiles == null) {
4552 importedFiles = new ArrayList<String>();
4553 for (int j=0; j<records.size(); j++) {
4554 QDir dir = new QDir(records.get(j).folder);
4555 List<QFileInfo> list = dir.entryInfoList();
4556 for (int k=0; k<list.size(); k++) {
4557 if (list.get(k).isFile())
4558 importedFiles.add(list.get(k).absoluteFilePath());
4563 public void folderImport() {
4564 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
4565 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
4567 if (!dialog.okClicked())
4570 // We have some sort of update.
4571 if (importKeepWatcher.directories().size() > 0)
4572 importKeepWatcher.removePaths(importKeepWatcher.directories());
4573 if (importDeleteWatcher.directories().size() > 0)
4574 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
4576 conn.getWatchFolderTable().expungeAll();
4577 // Start building from the table
4578 for (int i=0; i<dialog.table.rowCount(); i++) {
4579 QTableWidgetItem item = dialog.table.item(i, 0);
4580 String dir = item.text();
4581 item = dialog.table.item(i, 1);
4582 String notebook = item.text();
4583 item = dialog.table.item(i, 2);
4585 if (item.text().equalsIgnoreCase("Keep"))
4590 String guid = conn.getNotebookTable().findNotebookByName(notebook);
4591 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
4593 setupFolderImports();
4596 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
4598 String whichOS = System.getProperty("os.name");
4599 if (whichOS.contains("Windows"))
4600 dirName = dirName.replace('/','\\');
4602 FileImporter importer = new FileImporter(logger, conn);
4604 QDir dir = new QDir(dirName);
4605 List<QFileInfo> list = dir.entryInfoList();
4606 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4608 for (int i=0; i<list.size(); i++){
4610 boolean redundant = false;
4611 // Check if we've already imported this one or if it existed before
4612 for (int j=0; j<importedFiles.size(); j++) {
4613 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
4618 importer.setFileInfo(list.get(i));
4619 importer.setFileName(list.get(i).absoluteFilePath());
4622 if (list.get(i).isFile() && importer.isValidType()) {
4624 if (!importer.importFile()) {
4625 // If we can't get to the file, it is probably locked. We'll try again later.
4626 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4627 importFilesKeep.add(list.get(i).absoluteFilePath());
4631 Note newNote = importer.getNote();
4632 newNote.setNotebookGuid(notebook);
4633 newNote.setTitle(dir.at(i));
4634 listManager.addNote(newNote);
4635 conn.getNoteTable().addNote(newNote, true);
4636 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4637 noteTableView.insertRow(newNote, true, -1);
4638 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4639 listManager.countNotebookResults(listManager.getNoteIndex());
4640 importedFiles.add(list.get(i).absoluteFilePath());
4648 public void folderImportDelete(String dirName) {
4650 String whichOS = System.getProperty("os.name");
4651 if (whichOS.contains("Windows"))
4652 dirName = dirName.replace('/','\\');
4654 FileImporter importer = new FileImporter(logger, conn);
4655 QDir dir = new QDir(dirName);
4656 List<QFileInfo> list = dir.entryInfoList();
4657 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4659 for (int i=0; i<list.size(); i++){
4660 importer.setFileInfo(list.get(i));
4661 importer.setFileName(list.get(i).absoluteFilePath());
4663 if (list.get(i).isFile() && importer.isValidType()) {
4665 if (!importer.importFile()) {
4666 // If we can't get to the file, it is probably locked. We'll try again later.
4667 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4668 importFilesKeep.add(list.get(i).absoluteFilePath());
4672 Note newNote = importer.getNote();
4673 newNote.setNotebookGuid(notebook);
4674 newNote.setTitle(dir.at(i));
4675 listManager.addNote(newNote);
4676 conn.getNoteTable().addNote(newNote, true);
4677 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4678 noteTableView.insertRow(newNote, true, -1);
4679 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4680 listManager.countNotebookResults(listManager.getNoteIndex());
4681 dir.remove(dir.at(i));
4687 //**************************************************
4689 //**************************************************
4690 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
4691 logger.log(logger.HIGH, "Entering exernalFileEdited");
4693 // Strip URL prefix and base dir path
4694 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
4695 String name = fileName.replace(dPath, "");
4696 int pos = name.lastIndexOf('.');
4699 guid = guid.substring(0,pos);
4701 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
4703 guid = name.substring(0, pos);
4706 QFile file = new QFile(fileName);
4707 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
4708 // If we can't get to the file, it is probably locked. We'll try again later.
4709 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4710 externalFiles.add(fileName);
4713 QByteArray binData = file.readAll();
4715 if (binData.size() == 0) {
4716 // If we can't get to the file, it is probably locked. We'll try again later.
4717 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4718 externalFiles.add(fileName);
4722 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
4724 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
4725 if (r == null || r.getData() == null || r.getData().getBody() == null)
4727 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
4728 MessageDigest md = MessageDigest.getInstance("MD5");
4729 md.update(binData.toByteArray());
4730 byte[] hash = md.digest();
4731 String newHash = Global.byteArrayToHexString(hash);
4732 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
4733 updateResourceContentHash(r.getGuid(), oldHash, newHash);
4735 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
4736 Data data = r.getData();
4737 data.setBody(binData.toByteArray());
4738 data.setBodyHash(hash);
4739 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
4741 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
4743 if (r.getNoteGuid().equals(currentNoteGuid)) {
4744 QWebSettings.setMaximumPagesInCache(0);
4745 QWebSettings.setObjectCacheCapacities(0, 0, 0);
4746 refreshEvernoteNote(true);
4747 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
4750 logger.log(logger.HIGH, "Exiting externalFielEdited");
4752 // This is a timer event that tries to save any external files that were edited. This
4753 // is only needed if we couldn't save a file earlier.
4754 public void externalFileEditedSaver() {
4755 for (int i=externalFiles.size()-1; i>=0; i--) {
4757 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
4758 externalFileEdited(externalFiles.get(i));
4759 externalFiles.remove(i);
4760 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4762 for (int i=0; i<importFilesKeep.size(); i++) {
4764 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
4765 folderImportKeep(importFilesKeep.get(i));
4766 importFilesKeep.remove(i);
4767 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4769 for (int i=0; i<importFilesDelete.size(); i++) {
4770 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
4771 folderImportDelete(importFilesDelete.get(i));
4772 importFilesDelete.remove(i);
4779 // If an attachment on the current note was edited, we need to update the current notes's hash
4780 // Update a note content's hash. This happens if a resource is edited outside of NN
4781 public void updateResourceContentHash(String guid, String oldHash, String newHash) {
4782 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
4784 for (;position>-1;) {
4785 endPos = browserWindow.getContent().indexOf(">", position+1);
4786 String oldSegment = browserWindow.getContent().substring(position,endPos);
4787 int hashPos = oldSegment.indexOf("hash=\"");
4788 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
4789 String hash = oldSegment.substring(hashPos+6, hashEnd);
4790 if (hash.equalsIgnoreCase(oldHash)) {
4791 String newSegment = oldSegment.replace(oldHash, newHash);
4792 String content = browserWindow.getContent().substring(0,position) +
4794 browserWindow.getContent().substring(endPos);
4795 browserWindow.getBrowser().setContent(new QByteArray(content));;
4798 position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
4805 //*************************************************
4806 //* Check database userid & passwords
4807 //*************************************************
4808 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
4809 Connection connection;
4812 Class.forName("org.h2.Driver");
4813 } catch (ClassNotFoundException e1) {
4814 e1.printStackTrace();
4819 String passwordString = null;
4820 if (cypherPassword==null || cypherPassword.trim().equals(""))
4821 passwordString = userPassword;
4823 passwordString = cypherPassword+" "+userPassword;
4824 connection = DriverManager.getConnection(url,userid,passwordString);
4825 } catch (SQLException e) {
4830 } catch (SQLException e) {
4831 e.printStackTrace();