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.QModelIndex;
68 import com.trolltech.qt.core.QSize;
69 import com.trolltech.qt.core.QTemporaryFile;
70 import com.trolltech.qt.core.QTextCodec;
71 import com.trolltech.qt.core.QThreadPool;
72 import com.trolltech.qt.core.QTimer;
73 import com.trolltech.qt.core.QUrl;
74 import com.trolltech.qt.core.Qt;
75 import com.trolltech.qt.core.Qt.SortOrder;
76 import com.trolltech.qt.core.Qt.WidgetAttribute;
77 import com.trolltech.qt.gui.QAbstractItemView;
78 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
79 import com.trolltech.qt.gui.QAction;
80 import com.trolltech.qt.gui.QApplication;
81 import com.trolltech.qt.gui.QCloseEvent;
82 import com.trolltech.qt.gui.QColor;
83 import com.trolltech.qt.gui.QComboBox;
84 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
85 import com.trolltech.qt.gui.QCursor;
86 import com.trolltech.qt.gui.QDesktopServices;
87 import com.trolltech.qt.gui.QDialog;
88 import com.trolltech.qt.gui.QFileDialog;
89 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
90 import com.trolltech.qt.gui.QFileDialog.FileMode;
91 import com.trolltech.qt.gui.QGridLayout;
92 import com.trolltech.qt.gui.QHBoxLayout;
93 import com.trolltech.qt.gui.QIcon;
94 import com.trolltech.qt.gui.QImage;
95 import com.trolltech.qt.gui.QLabel;
96 import com.trolltech.qt.gui.QListWidget;
97 import com.trolltech.qt.gui.QMainWindow;
98 import com.trolltech.qt.gui.QMenu;
99 import com.trolltech.qt.gui.QMessageBox;
100 import com.trolltech.qt.gui.QMessageBox.StandardButton;
101 import com.trolltech.qt.gui.QPixmap;
102 import com.trolltech.qt.gui.QPrintDialog;
103 import com.trolltech.qt.gui.QPrinter;
104 import com.trolltech.qt.gui.QProgressBar;
105 import com.trolltech.qt.gui.QSizePolicy;
106 import com.trolltech.qt.gui.QSizePolicy.Policy;
107 import com.trolltech.qt.gui.QSpinBox;
108 import com.trolltech.qt.gui.QSplashScreen;
109 import com.trolltech.qt.gui.QSplitter;
110 import com.trolltech.qt.gui.QStatusBar;
111 import com.trolltech.qt.gui.QSystemTrayIcon;
112 import com.trolltech.qt.gui.QTableWidgetItem;
113 import com.trolltech.qt.gui.QTextEdit;
114 import com.trolltech.qt.gui.QToolBar;
115 import com.trolltech.qt.gui.QTreeWidgetItem;
116 import com.trolltech.qt.webkit.QWebPage.WebAction;
117 import com.trolltech.qt.webkit.QWebSettings;
118 import com.trolltech.qt.xml.QDomAttr;
119 import com.trolltech.qt.xml.QDomDocument;
120 import com.trolltech.qt.xml.QDomElement;
121 import com.trolltech.qt.xml.QDomNodeList;
123 import cx.fbn.nevernote.dialog.AccountDialog;
124 import cx.fbn.nevernote.dialog.ConfigDialog;
125 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
126 import cx.fbn.nevernote.dialog.DatabaseStatus;
127 import cx.fbn.nevernote.dialog.FindDialog;
128 import cx.fbn.nevernote.dialog.LoginDialog;
129 import cx.fbn.nevernote.dialog.NotebookArchive;
130 import cx.fbn.nevernote.dialog.NotebookEdit;
131 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
132 import cx.fbn.nevernote.dialog.SavedSearchEdit;
133 import cx.fbn.nevernote.dialog.TagEdit;
134 import cx.fbn.nevernote.dialog.ThumbnailViewer;
135 import cx.fbn.nevernote.dialog.WatchFolder;
136 import cx.fbn.nevernote.filters.EnSearch;
137 import cx.fbn.nevernote.gui.AttributeTreeWidget;
138 import cx.fbn.nevernote.gui.BrowserWindow;
139 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
140 import cx.fbn.nevernote.gui.MainMenuBar;
141 import cx.fbn.nevernote.gui.NotebookTreeWidget;
142 import cx.fbn.nevernote.gui.PDFPreview;
143 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
144 import cx.fbn.nevernote.gui.TableView;
145 import cx.fbn.nevernote.gui.TagTreeWidget;
146 import cx.fbn.nevernote.gui.Thumbnailer;
147 import cx.fbn.nevernote.gui.TrashTreeWidget;
148 import cx.fbn.nevernote.signals.DBRunnerSignal;
149 import cx.fbn.nevernote.sql.DatabaseConnection;
150 import cx.fbn.nevernote.sql.runners.WatchFolderRecord;
151 import cx.fbn.nevernote.threads.DBRunner;
152 import cx.fbn.nevernote.threads.IndexRunner;
153 import cx.fbn.nevernote.threads.SyncRunner;
154 import cx.fbn.nevernote.utilities.AESEncrypter;
155 import cx.fbn.nevernote.utilities.ApplicationLogger;
156 import cx.fbn.nevernote.utilities.FileImporter;
157 import cx.fbn.nevernote.utilities.ListManager;
158 import cx.fbn.nevernote.utilities.SyncTimes;
159 import cx.fbn.nevernote.xml.ExportData;
160 import cx.fbn.nevernote.xml.ImportData;
161 import cx.fbn.nevernote.xml.XMLInsertHilight;
164 public class NeverNote extends QMainWindow{
166 QStatusBar statusBar; // Application status bar
168 DatabaseConnection conn;
170 MainMenuBar menuBar; // Main menu bar
171 FindDialog find; // Text search in note dialog
172 List<String> emitLog; // Messages displayed in the status bar;
173 QSystemTrayIcon trayIcon; // little tray icon
174 QMenu trayMenu; // System tray menu
175 QAction trayExitAction; // Exit the application
176 QAction trayShowAction; // toggle the show/hide action
177 QAction trayAddNoteAction; // Add a note from the system tray
179 NotebookTreeWidget notebookTree; // List of notebooks
180 AttributeTreeWidget attributeTree; // List of note attributes
181 TagTreeWidget tagTree; // list of user created tags
182 SavedSearchTreeWidget savedSearchTree; // list of saved searches
183 TrashTreeWidget trashTree; // Trashcan
184 TableView noteTableView; // List of notes (the widget).
186 public BrowserWindow browserWindow; // Window containing browser & labels
187 QToolBar toolBar; // The tool bar under the menu
188 // QLineEdit searchField; // The search filter bar on the toolbar
189 QComboBox searchField; // search filter bar on the toolbar;
190 boolean searchPerformed = false; // Search was done?
191 QProgressBar quotaBar; // The current quota usage
193 ApplicationLogger logger;
194 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
195 List<String> selectedTagGUIDs; // List of selected tag GUIDs
196 List<String> selectedNoteGUIDs; // List of selected notes
197 String selectedSavedSearchGUID; // Currently selected saved searches
199 NoteFilter filter; // Note filter
200 String currentNoteGuid; // GUID of the current note
201 Note currentNote; // The currently viewed note
202 boolean noteDirty; // Has the note been changed?
203 boolean inkNote; // if this is an ink note, it is read only
205 QThread dbThread; // Thread to handle DB communication
206 ListManager listManager; // DB runnable task
208 List<QTemporaryFile> tempFiles; // Array of temporary files;
210 QTimer indexTimer; // timer to start the index thread
211 IndexRunner indexRunner; // thread to index notes
214 QTimer syncTimer; // Sync on an interval
215 QTimer syncDelayTimer; // Sync delay to free up database
216 SyncRunner syncRunner; // thread to do a sync.
218 QTimer saveTimer; // Timer to save note contents
220 QTimer authTimer; // Refresh authentication
221 QTimer externalFileSaveTimer; // Save files altered externally
222 List<String> externalFiles; // External files to save later
223 List<String> importFilesKeep; // Auto-import files to save later
224 List<String> importFilesDelete; // Auto-import files to save later
226 int indexTime; // how often to try and index
227 boolean indexRunning; // Is indexing running?
228 boolean indexDisabled; // Is indexing disabled?
230 int syncThreadsReady; // number of sync threads that are free
231 int syncTime; // Sync interval
232 boolean syncRunning; // Is sync running?
233 boolean automaticSync; // do sync automatically?
234 QTreeWidgetItem attributeTreeSelected;
236 QAction prevButton; // Go to the previous item viewed
237 QAction nextButton; // Go to the next item in the history
238 QAction downButton; // Go to the next item in the list
239 QAction upButton; // Go to the prev. item in the list;
240 QAction synchronizeButton; // Synchronize with Evernote
241 List<QIcon> synchronizeAnimation; // Synchronize movie
242 QTimer synchronizeAnimationTimer; // Timer to change animation button
243 int synchronizeFrame; // Current frame being viewed
244 QAction printButton; // Print Button
245 QAction tagButton; // Tag edit button
246 QAction attributeButton; // Attribute information button
247 QAction emailButton; // Email button
248 QAction deleteButton; // Delete button
249 QAction newButton; // new Note Button;
250 QSpinBox zoomSpinner; // Zoom zoom
251 QAction searchClearButton; // Clear the search field
253 QSplitter mainLeftRightSplitter; // main splitter for left/right side
254 QSplitter leftSplitter1; // first left hand splitter
255 QSplitter browserIndexSplitter; // splitter between note index & note text
257 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
258 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
259 List<String> importedFiles; // History of imported files (so we don't import twice)
261 OnlineNoteHistory historyWindow; // online history window
262 List<NoteVersionId> versions; // history versions
264 QTimer threadMonitorTimer; // Timer to watch threads.
265 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
266 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
267 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
268 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
269 int tagDeadCount=0; // number of consecutive dead times for the tag thread
270 int trashDeadCount=0; // number of consecutive dead times for the trash thread
271 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
273 HashMap<String, String> noteCache; // Cash of note content
274 List<String> historyGuids; // GUIDs of previously viewed items
275 int historyPosition; // Position within the viewed items
276 boolean fromHistory; // Is this from the history queue?
277 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
278 Thumbnailer preview; // generate preview image
279 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
281 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
284 //***************************************************************
285 //***************************************************************
286 //** Constructor & main entry point
287 //***************************************************************
288 //***************************************************************
289 // Application Constructor
292 if (!lockApplication()) {
295 thread().setPriority(Thread.MAX_PRIORITY);
297 logger = new ApplicationLogger("nevernote.log");
298 logger.log(logger.HIGH, tr("Starting Application"));
299 conn = new DatabaseConnection(logger, Global.mainThreadId);
302 logger.log(logger.EXTREME, tr("Creating index connection"));
303 logger.log(logger.EXTREME, tr("Building DB thread"));
304 Global.dbRunnerSignal = new DBRunnerSignal();
305 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
306 boolean goodCheck = false;
308 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
310 if (!dialog.okPressed())
312 Global.cipherPassword = dialog.getPassword();
313 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
316 Global.dbRunner = new DBRunner(Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
317 logger.log(logger.EXTREME, tr("Starting DB thread"));
318 dbThread = new QThread(Global.dbRunner, "Database Thread");
320 logger.log(logger.EXTREME, tr("DB Thread has started"));
321 Global.dbRunnerSignal.start.emit();
322 logger.log(logger.EXTREME, tr("Setting main thread DB connection"));
323 logger.log(logger.EXTREME, tr("main DB thread setup complete."));
324 conn.checkDatabaseVersion();
326 // Start building the invalid XML tables
327 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
328 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
330 for (int i=0; i<elements.size(); i++) {
331 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
334 logger.log(logger.EXTREME, tr("Starting GUI build"));
335 Global.originalPalette = QApplication.palette();
336 QApplication.setStyle(Global.getStyle());
337 if (Global.useStandardPalette())
338 QApplication.setPalette(QApplication.style().standardPalette());
339 setWindowTitle("NeverNote");
341 mainLeftRightSplitter = new QSplitter();
342 setCentralWidget(mainLeftRightSplitter);
343 leftSplitter1 = new QSplitter();
344 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
346 browserIndexSplitter = new QSplitter();
347 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
349 //* Setup threads & thread timers
350 int indexRunnerCount = Global.getIndexThreads();
351 indexRunnerCount = 1;
352 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
354 logger.log(logger.EXTREME, tr("Building list manager"));
355 listManager = new ListManager(conn, logger, Global.mainThreadId);
357 logger.log(logger.EXTREME, tr("Building index runners & timers"));
358 indexRunner = new IndexRunner("indexRunner.log");
359 indexThread = new QThread(indexRunner, "Index Thread");
362 synchronizeAnimationTimer = new QTimer();
363 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
365 indexTimer = new QTimer();
366 indexTime = 1000*60*5; // look for unindexed every 5 minutes
367 // indexTime = 1000*5;
368 indexTimer.start(indexTime); // Start indexing timer
369 indexTimer.timeout.connect(this, "indexTimer()");
370 indexDisabled = false;
371 indexRunning = false;
373 logger.log(logger.EXTREME, tr("Setting sync thread & timers"));
375 syncRunner = new SyncRunner("syncRunner.log");
376 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
377 syncTimer = new QTimer();
378 syncTimer.timeout.connect(this, "syncTimer()");
379 syncRunner.status.message.connect(this, "setMessage(String)");
380 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
381 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
384 automaticSync = true;
385 syncTimer.start(syncTime*60*1000);
387 automaticSync = false;
390 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
391 syncThread = new QThread(syncRunner, "Synchronization Thread");
395 logger.log(logger.EXTREME, tr("Starting authentication timer"));
396 authTimer = new QTimer();
397 authTimer.timeout.connect(this, "authTimer()");
398 authTimer.start(1000*60*15);
399 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
401 logger.log(logger.EXTREME, tr("Setting save note timer"));
402 saveTimer = new QTimer();
403 saveTimer.timeout.connect(this, "saveNote()");
404 if (Global.getAutoSaveInterval() > 0) {
405 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
406 // saveTimer.setInterval(1000*10); // auto save every 20 seconds;
411 logger.log(logger.EXTREME, tr("Starting external file monitor timer"));
412 externalFileSaveTimer = new QTimer();
413 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
414 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
415 externalFiles = new ArrayList<String>();
416 importFilesDelete = new ArrayList<String>();
417 importFilesKeep = new ArrayList<String>();
418 externalFileSaveTimer.start();
420 notebookTree = new NotebookTreeWidget();
421 attributeTree = new AttributeTreeWidget();
422 tagTree = new TagTreeWidget(conn);
423 savedSearchTree = new SavedSearchTreeWidget();
424 trashTree = new TrashTreeWidget();
425 noteTableView = new TableView(logger);
427 QGridLayout leftGrid = new QGridLayout();
428 leftSplitter1.setLayout(leftGrid);
429 leftGrid.addWidget(notebookTree, 1, 1);
430 leftGrid.addWidget(tagTree,2,1);
431 leftGrid.addWidget(attributeTree,3,1);
432 leftGrid.addWidget(savedSearchTree,4,1);
433 leftGrid.addWidget(trashTree, 5, 1);
435 // Setup the browser window
436 noteCache = new HashMap<String,String>();
437 browserWindow = new BrowserWindow(conn);
439 browserIndexSplitter.addWidget(noteTableView);
440 browserIndexSplitter.addWidget(browserWindow);
442 mainLeftRightSplitter.addWidget(leftSplitter1);
443 mainLeftRightSplitter.addWidget(browserIndexSplitter);
445 searchField = new QComboBox();
446 searchField.setEditable(true);
447 searchField.activatedIndex.connect(this, "searchFieldChanged()");
448 searchField.setDuplicatesEnabled(false);
449 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
451 quotaBar = new QProgressBar();
453 // Setup the thumbnail viewer
454 thumbnailViewer = new ThumbnailViewer();
455 thumbnailViewer.upArrow.connect(this, "upAction()");
456 thumbnailViewer.downArrow.connect(this, "downAction()");
457 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
458 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
460 listManager.loadNotesIndex();
461 initializeNotebookTree();
463 initializeSavedSearchTree();
464 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
465 attributeTreeSelected = null;
466 initializeNoteTable();
468 selectedNoteGUIDs = new ArrayList<String>();
469 statusBar = new QStatusBar();
470 setStatusBar(statusBar);
471 menuBar = new MainMenuBar(this);
472 emitLog = new ArrayList<String>();
474 tagTree.setDeleteAction(menuBar.tagDeleteAction);
475 tagTree.setEditAction(menuBar.tagEditAction);
476 tagTree.setAddAction(menuBar.tagAddAction);
477 tagTree.setVisible(Global.isWindowVisible("tagTree"));
478 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
479 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
480 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
482 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
483 notebookTree.setEditAction(menuBar.notebookEditAction);
484 notebookTree.setAddAction(menuBar.notebookAddAction);
485 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
486 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
487 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
489 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
490 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
491 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
492 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
493 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
494 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
496 noteTableView.setAddAction(menuBar.noteAdd);
497 noteTableView.setDeleteAction(menuBar.noteDelete);
498 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
499 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
500 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
501 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
502 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
503 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
504 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
505 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
506 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
508 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
509 trashTree.setEmptyAction(menuBar.emptyTrashAction);
510 trashTree.setVisible(Global.isWindowVisible("trashTree"));
511 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
512 trashTree.updateCounts(listManager.getTrashCount());
514 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
515 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
517 noteTableView.setVisible(Global.isWindowVisible("noteList"));
518 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
520 if (!Global.isWindowVisible("editorButtonBar"))
521 toggleEditorButtonBar();
522 if (!Global.isWindowVisible("leftPanel"))
523 menuBar.hideLeftSide.setChecked(true);
527 find = new FindDialog();
528 find.getOkButton().clicked.connect(this, "doFindText()");
530 // Setup the tray icon menu bar
531 trayShowAction = new QAction("Show/Hide", this);
532 trayExitAction = new QAction("Exit", this);
533 trayAddNoteAction = new QAction("Add Note", this);
535 trayExitAction.triggered.connect(this, "close()");
536 trayAddNoteAction.triggered.connect(this, "addNote()");
537 trayShowAction.triggered.connect(this, "trayToggleVisible()");
539 trayMenu = new QMenu(this);
540 trayMenu.addAction(trayAddNoteAction);
541 trayMenu.addAction(trayShowAction);
542 trayMenu.addAction(trayExitAction);
545 trayIcon = new QSystemTrayIcon(this);
546 trayIcon.setToolTip("NeverNote");
547 trayIcon.setContextMenu(trayMenu);
548 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
551 currentNoteGuid = Global.getLastViewedNoteGuid();
552 historyGuids = new ArrayList<String>();
556 if (!currentNoteGuid.trim().equals("")) {
557 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
560 noteIndexUpdated(true);
562 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
563 if (menuBar.showEditorBar.isChecked())
565 tagIndexUpdated(true);
566 savedSearchIndexUpdated();
567 notebookIndexUpdated();
569 setupSyncSignalListeners();
570 setupBrowserSignalListeners();
571 setupIndexListeners();
574 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
575 tagTree.showAllTags(true);
577 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
578 setWindowIcon(appIcon);
579 trayIcon.setIcon(appIcon);
580 if (Global.showTrayIcon())
585 scrollToGuid(currentNoteGuid);
586 if (Global.automaticLogin()) {
588 if (Global.isConnected)
591 setupFolderImports();
594 restoreWindowState();
596 if (Global.mimicEvernoteInterface) {
597 notebookTree.selectGuid("");
600 threadMonitorTimer = new QTimer();
601 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
602 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
604 historyGuids.add(currentNoteGuid);
607 int sortCol = Global.getSortColumn();
608 int sortOrder = Global.getSortOrder();
609 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
614 public static void main(String[] args) {
615 QApplication.initialize(args);
616 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
617 QSplashScreen splash = new QSplashScreen(pixmap);
619 for (String arg : args) {
620 String lower = arg.toLowerCase();
621 if (lower.startsWith("--name="))
622 Global.setName(arg.substring(arg.indexOf('=')+1));
623 if (lower.startsWith("--home="))
624 Global.currentDir = arg.substring(arg.indexOf('=')+1);
625 if (lower.startsWith("--disable-viewing"))
626 Global.disableViewing = true;
629 boolean showSplash = Global.isWindowVisible("SplashScreen");
632 NeverNote application = new NeverNote();
633 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
634 if (Global.wasWindowMaximized())
635 application.showMaximized();
639 splash.finish(application);
641 System.out.println("Goodbye.");
646 public void closeEvent(QCloseEvent event) {
647 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
650 if (currentNote!= null & browserWindow!=null) {
651 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
652 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
655 setMessage("Beginning shutdown.");
657 externalFileEditedSaver();
658 if (Global.isConnected && Global.synchronizeOnClose()) {
659 setMessage("Performing synchronization before closing.");
660 syncRunner.addWork("SYNC");
662 setMessage("Closing Program.");
663 threadMonitorTimer.stop();
665 syncRunner.addWork("STOP");
666 indexRunner.addWork("STOP");
671 if (tempFiles != null)
674 browserWindow.noteSignal.tagsChanged.disconnect();
675 browserWindow.noteSignal.titleChanged.disconnect();
676 browserWindow.noteSignal.noteChanged.disconnect();
677 browserWindow.noteSignal.notebookChanged.disconnect();
678 browserWindow.noteSignal.createdDateChanged.disconnect();
679 browserWindow.noteSignal.alteredDateChanged.disconnect();
680 syncRunner.searchSignal.listChanged.disconnect();
681 syncRunner.tagSignal.listChanged.disconnect();
682 syncRunner.notebookSignal.listChanged.disconnect();
683 syncRunner.noteIndexSignal.listChanged.disconnect();
686 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
687 Global.setColumnPosition("noteTableCreationPosition", position);
688 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
689 Global.setColumnPosition("noteTableTagPosition", position);
690 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
691 Global.setColumnPosition("noteTableNotebookPosition", position);
692 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
693 Global.setColumnPosition("noteTableChangedPosition", position);
694 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
695 Global.setColumnPosition("noteTableAuthorPosition", position);
696 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
697 Global.setColumnPosition("noteTableSourceUrlPosition", position);
698 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
699 Global.setColumnPosition("noteTableSubjectDatePosition", position);
700 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
701 Global.setColumnPosition("noteTableTitlePosition", position);
702 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
703 Global.setColumnPosition("noteTableSynchronizedPosition", position);
705 saveNoteIndexWidth();
707 int width = notebookTree.columnWidth(0);
708 Global.setColumnWidth("notebookTreeName", width);
709 width = tagTree.columnWidth(0);
710 Global.setColumnWidth("tagTreeName", width);
712 Global.saveWindowMaximized(isMaximized());
713 Global.saveCurrentNoteGuid(currentNoteGuid);
715 int sortCol = noteTableView.proxyModel.sortColumn();
716 int sortOrder = noteTableView.proxyModel.sortOrder().value();
717 Global.setSortColumn(sortCol);
718 Global.setSortOrder(sortOrder);
722 Global.keepRunning = false;
724 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
725 indexRunner.thread().join(50);
726 logger.log(logger.MEDIUM, "Index thread has stopped");
727 } catch (InterruptedException e1) {
728 e1.printStackTrace();
730 if (!syncRunner.isIdle()) {
732 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
734 logger.log(logger.MEDIUM, "Sync thread has stopped");
735 } catch (InterruptedException e1) {
736 e1.printStackTrace();
740 logger.log(logger.EXTREME, "Shutting down database");
742 logger.log(logger.EXTREME, "Waiting for DB thread to terminate");
745 } catch (InterruptedException e) {
748 logger.log(logger.EXTREME, "DB Thread has terminated");
750 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
753 public void setMessage(String s) {
754 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
755 logger.log(logger.HIGH, "Message: " +s);
756 statusBar.showMessage(s);
758 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
761 private void waitCursor(boolean wait) {
763 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
765 QApplication.restoreOverrideCursor();
768 private void setupIndexListeners() {
769 indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
770 indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
771 // indexRunner.threadSignal.indexNeeded.connect(listManager, "setIndexNeeded(String, String, Boolean)");
773 private void setupSyncSignalListeners() {
774 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
775 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
776 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
777 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
778 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
780 // syncRunner.syncSignal.setSequenceDate.connect(this,"setSequenceDate(long)");
781 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
782 // syncRunner.syncSignal.setUpdateSequenceNumber.connect(this,"setUpdateSequenceNumber(int)");
783 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
784 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
786 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
787 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
788 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
790 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
793 private void setupBrowserSignalListeners() {
795 browserWindow.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
796 browserWindow.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
797 browserWindow.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
798 browserWindow.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
799 browserWindow.noteSignal.noteChanged.connect(this, "setNoteDirty()");
800 browserWindow.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
801 browserWindow.noteSignal.titleChanged.connect(this, "updateListTitle(String, String)");
802 browserWindow.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
803 browserWindow.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
804 browserWindow.noteSignal.createdDateChanged.connect(this, "updateListDateCreated(String, QDateTime)");
805 browserWindow.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
806 browserWindow.noteSignal.alteredDateChanged.connect(this, "updateListDateChanged(String, QDateTime)");
807 browserWindow.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
808 browserWindow.noteSignal.subjectDateChanged.connect(this, "updateListDateSubject(String, QDateTime)");
809 browserWindow.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
810 browserWindow.noteSignal.authorChanged.connect(this, "updateListAuthor(String, String)");
811 browserWindow.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
812 browserWindow.noteSignal.sourceUrlChanged.connect(this, "updateListSourceUrl(String, String)");
813 browserWindow.focusLost.connect(this, "saveNote()");
814 browserWindow.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
815 // browserWindow.resourceSignal.externalFileEdit.connect(this, "saveResourceLater(String, String)");
817 private boolean lockApplication() {
819 String fileName = Global.currentDir +"db" +File.separator +"NeverNote.lock.db";
820 // QFile.remove(fileName);
821 if (QFile.exists(fileName)) {
822 QMessageBox.question(this, "Lock File Detected",
823 "While starting I've found a database lock file.\n" +
824 "to prevent multiple instances from accessing the database \n"+
825 "at the same time. Please stop any other program, or (if you\n" +
826 "are sure nothing else is using the database) remove the file\n" +
832 /* String fileName = Global.currentDir +"nevernote.lock";
835 if (QFile.exists(fileName)) {
836 if (QMessageBox.question(this, "Confirmation",
837 "While starting I've found a lock file. This file is used to prevent multiple "+
838 "instances of this program running at once. If NeverNote has crashed this " +
839 "is just a file that wasn't cleaned up and you can safely, "+
840 "continue, but if there is another instance of this running you are " +
841 "running the risk of creating problems.\n\n" +
842 "Are you sure you want to continue?",
843 QMessageBox.StandardButton.Yes,
844 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
849 QFile file = new QFile(fileName);
850 file.open(OpenModeFlag.WriteOnly);
851 file.write(new QByteArray("This file is used to prevent multiple instances " +
852 "of NeverNote running more than once. " +
853 "It should be deleted when NeverNote ends"));
858 private void unlockApplication() {
859 String fileName = Global.currentDir +"nevernote.lock";
860 if (QFile.exists(fileName)) {
861 QFile.remove(fileName);
866 //***************************************************************
867 //***************************************************************
868 //* Settings and look & feel
869 //***************************************************************
870 //***************************************************************
871 @SuppressWarnings("unused")
872 private void settings() {
873 logger.log(logger.HIGH, "Entering NeverNote.settings");
874 ConfigDialog settings = new ConfigDialog(this);
875 String dateFormat = Global.getDateFormat();
876 String timeFormat = Global.getTimeFormat();
879 if (Global.showTrayIcon())
884 if (menuBar.showEditorBar.isChecked())
887 // Reset the save timer
888 if (Global.getAutoSaveInterval() > 0)
889 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
893 // This is a hack to force a reload of the index in case the date or time changed.
894 // if (!dateFormat.equals(Global.getDateFormat()) ||
895 // !timeFormat.equals(Global.getTimeFormat())) {
897 noteIndexUpdated(true);
900 logger.log(logger.HIGH, "Leaving NeverNote.settings");
902 // Restore things to the way they were
903 private void restoreWindowState() {
904 // We need to name things or this doesn't work.
905 setObjectName("NeverNote");
906 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
907 browserIndexSplitter.setObjectName("browserIndexSplitter");
908 leftSplitter1.setObjectName("leftSplitter1");
910 // Restore the actual positions.
911 restoreGeometry(Global.restoreGeometry(objectName()));
912 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
913 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
914 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
917 // Save window positions for the next start
918 private void saveWindowState() {
919 Global.saveGeometry(objectName(), saveGeometry());
920 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
921 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
922 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
924 // Load the style sheet
925 private void loadStyleSheet() {
926 String fileName = Global.currentDir +"qss"+System.getProperty("file.separator")+ "default.qss";
927 QFile file = new QFile(fileName);
928 file.open(OpenModeFlag.ReadOnly);
929 String styleSheet = file.readAll().toString();
931 setStyleSheet(styleSheet);
933 // Save column widths for the next time
934 private void saveNoteIndexWidth() {
936 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
937 Global.setColumnWidth("noteTableCreationPosition", width);
938 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
939 Global.setColumnWidth("noteTableChangedPosition", width);
940 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
941 Global.setColumnWidth("noteTableGuidPosition", width);
942 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
943 Global.setColumnWidth("noteTableNotebookPosition", width);
944 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
945 Global.setColumnWidth("noteTableTagPosition", width);
946 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
947 Global.setColumnWidth("noteTableTitlePosition", width);
948 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
949 Global.setColumnWidth("noteTableSourceUrlPosition", width);
950 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
951 Global.setColumnWidth("noteTableAuthorPosition", width);
952 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
953 Global.setColumnWidth("noteTableSubjectDatePosition", width);
954 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
955 Global.setColumnWidth("noteTableSynchronizedPosition", width);
959 //***************************************************************
960 //***************************************************************
961 //** These functions deal with Notebook menu items
962 //***************************************************************
963 //***************************************************************
964 // Setup the tree containing the user's notebooks.
965 private void initializeNotebookTree() {
966 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
967 notebookTree.itemSelectionChanged.connect(this, "notebookTreeSelection()");
968 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
969 // notebookTree.resize(Global.getSize("notebookTree"));
970 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
972 // Listener when a notebook is selected
973 @SuppressWarnings("unused")
974 private void notebookTreeSelection() {
975 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
978 clearAttributeFilter();
979 clearSavedSearchFilter();
980 if (Global.mimicEvernoteInterface) {
985 menuBar.noteRestoreAction.setVisible(false);
986 menuBar.notebookEditAction.setEnabled(true);
987 menuBar.notebookDeleteAction.setEnabled(true);
988 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
989 QTreeWidgetItem currentSelection;
990 selectedNotebookGUIDs.clear();
991 if (!Global.mimicEvernoteInterface) {
992 for (int i=0; i<selections.size(); i++) {
993 currentSelection = selections.get(i);
994 selectedNotebookGUIDs.add(currentSelection.text(2));
998 // There is the potential for no notebooks to be selected if this
999 // happens then we make it look like all notebooks were selecetd.
1000 // If that happens, just select the "all notebooks"
1001 selections = notebookTree.selectedItems();
1002 if (selections.size()==0) {
1003 selectedNotebookGUIDs.clear();
1004 menuBar.notebookEditAction.setEnabled(false);
1005 menuBar.notebookDeleteAction.setEnabled(false);
1009 if (selections.size() > 0)
1010 guid = (selections.get(0).text(2));
1011 if (!guid.equals(""))
1012 selectedNotebookGUIDs.add(guid);
1014 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1015 listManager.loadNotesIndex();
1016 noteIndexUpdated(false);
1017 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1020 private void clearNotebookFilter() {
1021 notebookTree.blockSignals(true);
1022 notebookTree.clearSelection();
1023 menuBar.noteRestoreAction.setVisible(false);
1024 menuBar.notebookEditAction.setEnabled(false);
1025 menuBar.notebookDeleteAction.setEnabled(false);
1026 selectedNotebookGUIDs.clear();
1027 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1028 notebookTree.blockSignals(false);
1030 // Triggered when the notebook DB has been updated
1031 private void notebookIndexUpdated() {
1032 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1033 if (selectedNotebookGUIDs == null)
1034 selectedNotebookGUIDs = new ArrayList<String>();
1035 List<Notebook> books = conn.getNotebookTable().getAll();
1036 for (int i=books.size()-1; i>=0; i--) {
1037 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1038 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1040 j=listManager.getArchiveNotebookIndex().size();
1046 listManager.countNotebookResults(listManager.getNoteIndex());
1047 notebookTree.blockSignals(true);
1048 notebookTree.load(books, listManager.getLocalNotebooks());
1049 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1050 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1052 selectedNotebookGUIDs.remove(i);
1054 notebookTree.blockSignals(false);
1056 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1058 // Show/Hide note information
1059 private void toggleNotebookWindow() {
1060 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1061 if (notebookTree.isVisible())
1062 notebookTree.hide();
1064 notebookTree.show();
1065 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1066 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1067 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1069 // Add a new notebook
1070 @SuppressWarnings("unused")
1071 private void addNotebook() {
1072 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1073 NotebookEdit edit = new NotebookEdit();
1074 edit.setNotebooks(listManager.getNotebookIndex());
1077 if (!edit.okPressed())
1080 Calendar currentTime = new GregorianCalendar();
1081 Long l = new Long(currentTime.getTimeInMillis());
1082 String randint = new String(Long.toString(l));
1084 Notebook newBook = new Notebook();
1085 newBook.setUpdateSequenceNum(0);
1086 newBook.setGuid(randint);
1087 newBook.setName(edit.getNotebook());
1088 newBook.setServiceCreated(new Date().getTime());
1089 newBook.setServiceUpdated(new Date().getTime());
1090 newBook.setDefaultNotebook(false);
1091 newBook.setPublished(false);
1093 listManager.getNotebookIndex().add(newBook);
1095 listManager.getLocalNotebooks().add(newBook.getGuid());
1096 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1097 notebookIndexUpdated();
1098 listManager.countNotebookResults(listManager.getNoteIndex());
1099 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1100 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1102 // Edit an existing notebook
1103 @SuppressWarnings("unused")
1104 private void editNotebook() {
1105 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1106 NotebookEdit edit = new NotebookEdit();
1107 edit.setTitle("Edit Notebook");
1108 edit.setLocalCheckboxEnabled(false);
1109 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1110 QTreeWidgetItem currentSelection;
1111 currentSelection = selections.get(0);
1112 edit.setNotebook(currentSelection.text(0));
1113 edit.setNotebooks(listManager.getNotebookIndex());
1116 if (!edit.okPressed())
1119 String guid = currentSelection.text(2);
1120 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1121 currentSelection.setText(0, edit.getNotebook());
1123 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1124 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1125 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1126 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1127 i=listManager.getNotebookIndex().size();
1131 // Build a list of non-closed notebooks
1132 List<Notebook> nbooks = new ArrayList<Notebook>();
1133 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1134 boolean found=false;
1135 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1136 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1140 nbooks.add(listManager.getNotebookIndex().get(i));
1143 browserWindow.setNotebookList(nbooks);
1144 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1146 // Delete an existing notebook
1147 @SuppressWarnings("unused")
1148 private void deleteNotebook() {
1149 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1150 boolean assigned = false;
1151 // Check if any notes have this notebook
1152 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1153 for (int i=0; i<selections.size(); i++) {
1154 QTreeWidgetItem currentSelection;
1155 currentSelection = selections.get(i);
1156 String guid = currentSelection.text(2);
1157 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1158 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1159 if (noteGuid.equals(guid)) {
1161 j=listManager.getNoteIndex().size();
1162 i=selections.size();
1167 QMessageBox.information(this, "Unable to Delete", "Some of the selected notebook(s) contain notes.\n"+
1168 "Please delete the notes or move them to another notebook before deleting any notebooks.");
1172 if (conn.getNotebookTable().getAll().size() == 1) {
1173 QMessageBox.information(this, "Unable to Delete", "You must have at least one notebook.");
1177 // If all notebooks are clear, verify the delete
1178 if (QMessageBox.question(this, "Confirmation", "Delete the selected notebooks?",
1179 QMessageBox.StandardButton.Yes,
1180 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1184 // If confirmed, delete the notebook
1185 for (int i=selections.size()-1; i>=0; i--) {
1186 QTreeWidgetItem currentSelection;
1187 currentSelection = selections.get(i);
1188 String guid = currentSelection.text(2);
1189 conn.getNotebookTable().expungeNotebook(guid, true);
1190 listManager.deleteNotebook(guid);
1192 // for (int i=<dbRunner.getLocalNotebooks().size()-1; i>=0; i--) {
1193 // if (dbRunner.getLocalNotebooks().get(i).equals(arg0))
1195 notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1196 listManager.countNotebookResults(listManager.getNoteIndex());
1197 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1198 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1200 // A note's notebook has been updated
1201 @SuppressWarnings("unused")
1202 private void updateNoteNotebook(String guid, String notebookGuid) {
1204 // Update the list manager
1205 listManager.updateNoteNotebook(guid, notebookGuid);
1206 listManager.countNotebookResults(listManager.getNoteIndex());
1207 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1209 // Find the name of the notebook
1210 String notebookName = null;
1211 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1212 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1213 notebookName = listManager.getNotebookIndex().get(i).getName();
1214 i=listManager.getNotebookIndex().size();
1218 // If we found the name, update the browser window
1219 if (notebookName != null) {
1220 updateListNoteNotebook(guid, notebookName);
1221 if (guid.equals(currentNoteGuid)) {
1222 int pos = browserWindow.notebookBox.findText(notebookName);
1224 browserWindow.notebookBox.setCurrentIndex(pos);
1228 // If we're dealing with the current note, then we need to be sure and update the notebook there
1229 if (guid.equals(currentNoteGuid)) {
1230 if (currentNote != null) {
1231 currentNote.setNotebookGuid(notebookGuid);
1235 // Open/close notebooks
1236 @SuppressWarnings("unused")
1237 private void closeNotebooks() {
1238 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1240 if (!na.okClicked())
1244 listManager.getArchiveNotebookIndex().clear();
1246 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1247 String text = na.getClosedBookList().takeItem(i).text();
1248 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1249 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1250 Notebook n = listManager.getNotebookIndex().get(j);
1251 conn.getNotebookTable().setArchived(n.getGuid(),true);
1252 listManager.getArchiveNotebookIndex().add(n);
1253 j=listManager.getNotebookIndex().size();
1258 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1259 String text = na.getOpenBookList().takeItem(i).text();
1260 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1261 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1262 Notebook n = listManager.getNotebookIndex().get(j);
1263 conn.getNotebookTable().setArchived(n.getGuid(),false);
1264 j=listManager.getNotebookIndex().size();
1269 listManager.loadNotesIndex();
1270 notebookIndexUpdated();
1271 noteIndexUpdated(true);
1272 // noteIndexUpdated(false);
1274 // Build a list of non-closed notebooks
1275 List<Notebook> nbooks = new ArrayList<Notebook>();
1276 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1277 boolean found=false;
1278 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1279 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1283 nbooks.add(listManager.getNotebookIndex().get(i));
1286 browserWindow.setNotebookList(nbooks);
1293 //***************************************************************
1294 //***************************************************************
1295 //** These functions deal with Tag menu items
1296 //***************************************************************
1297 //***************************************************************
1298 // Add a new notebook
1299 @SuppressWarnings("unused")
1300 private void addTag() {
1301 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1302 TagEdit edit = new TagEdit();
1303 edit.setTagList(listManager.getTagIndex());
1306 if (!edit.okPressed())
1309 Calendar currentTime = new GregorianCalendar();
1310 Long l = new Long(currentTime.getTimeInMillis());
1311 String randint = new String(Long.toString(l));
1313 Tag newTag = new Tag();
1314 newTag.setUpdateSequenceNum(0);
1315 newTag.setGuid(randint);
1316 newTag.setName(edit.getTag());
1317 conn.getTagTable().addTag(newTag, true);
1318 listManager.getTagIndex().add(newTag);
1321 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1323 private void reloadTagTree() {
1324 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1325 tagIndexUpdated(false);
1326 boolean filter = false;
1327 listManager.countTagResults(listManager.getNoteIndex());
1328 if (notebookTree.selectedItems().size() > 0
1329 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1331 if (tagTree.selectedItems().size() > 0)
1333 tagTree.showAllTags(!filter);
1334 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1336 // Edit an existing tag
1337 @SuppressWarnings("unused")
1338 private void editTag() {
1339 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1340 TagEdit edit = new TagEdit();
1341 edit.setTitle("Edit Tag");
1342 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1343 QTreeWidgetItem currentSelection;
1344 currentSelection = selections.get(0);
1345 edit.setTag(currentSelection.text(0));
1346 edit.setTagList(listManager.getTagIndex());
1349 if (!edit.okPressed())
1352 String guid = currentSelection.text(2);
1353 currentSelection.setText(0,edit.getTag());
1355 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1356 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1357 listManager.getTagIndex().get(i).setName(edit.getTag());
1358 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1359 updateListTagName(guid);
1360 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1361 browserWindow.setTag(getTagNamesForNote(currentNote));
1362 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1366 browserWindow.setTag(getTagNamesForNote(currentNote));
1367 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1369 // Delete an existing tag
1370 @SuppressWarnings("unused")
1371 private void deleteTag() {
1372 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1374 if (QMessageBox.question(this, "Confirmation", "Delete the selected tags?",
1375 QMessageBox.StandardButton.Yes,
1376 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1380 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1381 for (int i=selections.size()-1; i>=0; i--) {
1382 QTreeWidgetItem currentSelection;
1383 currentSelection = selections.get(i);
1384 removeTagItem(currentSelection.text(2));
1386 tagIndexUpdated(true);
1387 listManager.countTagResults(listManager.getNoteIndex());
1388 // tagTree.updateCounts(listManager.getTagCounter());
1389 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1391 // Remove a tag tree item. Go recursively down & remove the children too
1392 private void removeTagItem(String guid) {
1393 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1394 String parent = listManager.getTagIndex().get(j).getParentGuid();
1395 if (parent != null && parent.equals(guid)) {
1396 //Remove this tag's children
1397 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1400 //Now, remove this tag
1401 removeListTagName(guid);
1402 conn.getTagTable().expungeTag(guid, true);
1403 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1404 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1405 listManager.getTagIndex().remove(a);
1410 // Setup the tree containing the user's tags
1411 private void initializeTagTree() {
1412 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1413 tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1414 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1415 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1417 // Listener when a tag is selected
1418 @SuppressWarnings("unused")
1419 private void tagTreeSelection() {
1420 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1422 List<QTreeWidgetItem> x = tagTree.selectedItems();
1423 for (int i=0; i<x.size(); i++) {
1427 clearAttributeFilter();
1428 clearSavedSearchFilter();
1430 menuBar.noteRestoreAction.setVisible(false);
1432 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1433 QTreeWidgetItem currentSelection;
1434 selectedTagGUIDs.clear();
1435 for (int i=0; i<selections.size(); i++) {
1436 currentSelection = selections.get(i);
1437 selectedTagGUIDs.add(currentSelection.text(2));
1439 if (selections.size() > 0) {
1440 menuBar.tagEditAction.setEnabled(true);
1441 menuBar.tagDeleteAction.setEnabled(true);
1444 menuBar.tagEditAction.setEnabled(false);
1445 menuBar.tagDeleteAction.setEnabled(false);
1447 listManager.setSelectedTags(selectedTagGUIDs);
1448 listManager.loadNotesIndex();
1449 noteIndexUpdated(false);
1450 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1452 // trigger the tag index to be refreshed
1453 @SuppressWarnings("unused")
1454 private void tagIndexUpdated() {
1455 tagIndexUpdated(true);
1457 private void tagIndexUpdated(boolean reload) {
1458 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1459 if (selectedTagGUIDs == null)
1460 selectedTagGUIDs = new ArrayList<String>();
1461 // selectedTagGUIDs.clear(); // clear out old entries
1463 tagTree.blockSignals(true);
1465 tagTree.load(listManager.getTagIndex());
1466 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1467 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1469 selectedTagGUIDs.remove(i);
1471 tagTree.blockSignals(false);
1473 browserWindow.setTag(getTagNamesForNote(currentNote));
1474 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1476 // Show/Hide note information
1477 private void toggleTagWindow() {
1478 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1479 if (tagTree.isVisible())
1483 menuBar.hideTags.setChecked(tagTree.isVisible());
1484 Global.saveWindowVisible("tagTree", tagTree.isVisible());
1485 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
1487 // A note's tags have been updated
1488 @SuppressWarnings("unused")
1489 private void updateNoteTags(String guid, List<String> tags) {
1490 listManager.saveNoteTags(guid, tags);
1491 listManager.countTagResults(listManager.getNoteIndex());
1492 StringBuffer names = new StringBuffer("");
1493 for (int i=0; i<tags.size(); i++) {
1494 names = names.append(tags.get(i));
1495 if (i<tags.size()-1) {
1496 names.append(Global.tagDelimeter + " ");
1499 browserWindow.setTag(names.toString());
1501 // tagTree.updateCounts(listManager.getTagCounter());
1503 // Get a string containing all tag names for a note
1504 private String getTagNamesForNote(Note n) {
1505 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
1506 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
1508 StringBuffer buffer = new StringBuffer(100);
1509 Vector<String> v = new Vector<String>();
1510 List<String> guids = n.getTagGuids();
1515 for (int i=0; i<guids.size(); i++) {
1516 v.add(listManager.getTagNameByGuid(guids.get(i)));
1518 Comparator<String> comparator = Collections.reverseOrder();
1519 Collections.sort(v,comparator);
1520 Collections.reverse(v);
1522 for (int i = 0; i<v.size(); i++) {
1524 buffer.append(", ");
1525 buffer.append(v.get(i));
1528 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
1529 return buffer.toString();
1531 // Tags were added via dropping notes from the note list
1532 @SuppressWarnings("unused")
1533 private void tagsAdded(String noteGuid, String tagGuid) {
1534 String tagName = null;
1535 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1536 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
1537 tagName = listManager.getTagIndex().get(i).getName();
1538 i=listManager.getTagIndex().size();
1541 if (tagName == null)
1544 for (int i=0; i<noteTableView.model.rowCount(); i++) {
1545 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
1546 if (modelIndex != null) {
1547 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
1548 String titleGuid = (String)ix.values().toArray()[0];
1549 if (titleGuid.equals(noteGuid)) {
1550 String text = (String)noteTableView.model.data(i, Global.noteTableTagPosition);
1551 if (!text.trim().equals(""))
1552 text = text + Global.tagDelimeter + " " +tagName;
1555 noteTableView.model.setData(i, Global.noteTableTagPosition, text);
1556 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
1557 if (noteGuid.equals(currentNoteGuid))
1558 browserWindow.setTag(text);
1559 i=noteTableView.model.rowCount();
1564 private void clearTagFilter() {
1565 tagTree.blockSignals(true);
1566 tagTree.clearSelection();
1567 menuBar.noteRestoreAction.setVisible(false);
1568 menuBar.tagEditAction.setEnabled(false);
1569 menuBar.tagDeleteAction.setEnabled(false);
1570 selectedTagGUIDs.clear();
1571 listManager.setSelectedTags(selectedTagGUIDs);
1572 tagTree.blockSignals(false);
1576 //***************************************************************
1577 //***************************************************************
1578 //** These functions deal with Saved Search menu items
1579 //***************************************************************
1580 //***************************************************************
1581 // Add a new notebook
1582 @SuppressWarnings("unused")
1583 private void addSavedSearch() {
1584 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
1585 SavedSearchEdit edit = new SavedSearchEdit();
1586 edit.setSearchList(listManager.getSavedSearchIndex());
1589 if (!edit.okPressed())
1592 Calendar currentTime = new GregorianCalendar();
1593 Long l = new Long(currentTime.getTimeInMillis());
1594 String randint = new String(Long.toString(l));
1596 SavedSearch search = new SavedSearch();
1597 search.setUpdateSequenceNum(0);
1598 search.setGuid(randint);
1599 search.setName(edit.getName());
1600 search.setQuery(edit.getQuery());
1601 search.setFormat(QueryFormat.USER);
1602 listManager.getSavedSearchIndex().add(search);
1603 conn.getSavedSearchTable().addSavedSearch(search, true);
1604 savedSearchIndexUpdated();
1605 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
1607 // Edit an existing tag
1608 @SuppressWarnings("unused")
1609 private void editSavedSearch() {
1610 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
1611 SavedSearchEdit edit = new SavedSearchEdit();
1612 edit.setTitle("Edit Search");
1613 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1614 QTreeWidgetItem currentSelection;
1615 currentSelection = selections.get(0);
1616 String guid = currentSelection.text(1);
1617 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
1618 edit.setName(currentSelection.text(0));
1619 edit.setQuery(s.getQuery());
1620 edit.setSearchList(listManager.getSavedSearchIndex());
1623 if (!edit.okPressed())
1626 List<SavedSearch> list = listManager.getSavedSearchIndex();
1627 SavedSearch search = null;
1628 boolean found = false;
1629 for (int i=0; i<list.size(); i++) {
1630 search = list.get(i);
1631 if (search.getGuid().equals(guid)) {
1638 search.setName(edit.getName());
1639 search.setQuery(edit.getQuery());
1640 conn.getSavedSearchTable().updateSavedSearch(search, true);
1641 savedSearchIndexUpdated();
1642 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
1644 // Delete an existing tag
1645 @SuppressWarnings("unused")
1646 private void deleteSavedSearch() {
1647 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
1649 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
1650 QMessageBox.StandardButton.Yes,
1651 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1655 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1656 for (int i=selections.size()-1; i>=0; i--) {
1657 QTreeWidgetItem currentSelection;
1658 currentSelection = selections.get(i);
1659 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
1660 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
1661 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
1662 listManager.getSavedSearchIndex().remove(j);
1663 j=listManager.getSavedSearchIndex().size()+1;
1666 selections.remove(i);
1668 savedSearchIndexUpdated();
1669 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
1671 // Setup the tree containing the user's tags
1672 private void initializeSavedSearchTree() {
1673 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
1674 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
1675 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
1677 // Listener when a tag is selected
1678 @SuppressWarnings("unused")
1679 private void savedSearchTreeSelection() {
1680 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
1682 clearNotebookFilter();
1685 clearAttributeFilter();
1687 String currentGuid = selectedSavedSearchGUID;
1688 menuBar.savedSearchEditAction.setEnabled(true);
1689 menuBar.savedSearchDeleteAction.setEnabled(true);
1690 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1691 QTreeWidgetItem currentSelection;
1692 selectedSavedSearchGUID = "";
1693 for (int i=0; i<selections.size(); i++) {
1694 currentSelection = selections.get(i);
1695 if (currentSelection.text(1).equals(currentGuid)) {
1696 currentSelection.setSelected(false);
1698 selectedSavedSearchGUID = currentSelection.text(1);
1700 // i = selections.size() +1;
1703 // There is the potential for no notebooks to be selected if this
1704 // happens then we make it look like all notebooks were selecetd.
1705 // If that happens, just select the "all notebooks"
1706 if (selections.size()==0) {
1707 clearSavedSearchFilter();
1709 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1711 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
1713 private void clearSavedSearchFilter() {
1714 menuBar.savedSearchEditAction.setEnabled(false);
1715 menuBar.savedSearchDeleteAction.setEnabled(false);
1716 savedSearchTree.blockSignals(true);
1717 savedSearchTree.clearSelection();
1718 savedSearchTree.blockSignals(false);
1719 selectedSavedSearchGUID = "";
1720 searchField.setEditText("");
1721 searchPerformed = false;
1722 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
1724 // trigger the tag index to be refreshed
1725 private void savedSearchIndexUpdated() {
1726 if (selectedSavedSearchGUID == null)
1727 selectedSavedSearchGUID = new String();
1728 savedSearchTree.blockSignals(true);
1729 savedSearchTree.load(listManager.getSavedSearchIndex());
1730 savedSearchTree.selectGuid(selectedSavedSearchGUID);
1731 savedSearchTree.blockSignals(false);
1733 // trigger when the saved search selection changes
1734 @SuppressWarnings("unused")
1735 private void updateSavedSearchSelection() {
1736 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
1738 menuBar.savedSearchEditAction.setEnabled(true);
1739 menuBar.savedSearchDeleteAction.setEnabled(true);
1740 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
1742 if (selections.size() > 0) {
1743 menuBar.savedSearchEditAction.setEnabled(true);
1744 menuBar.savedSearchDeleteAction.setEnabled(true);
1745 selectedSavedSearchGUID = selections.get(0).text(1);
1746 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
1747 searchField.setEditText(s.getQuery());
1749 menuBar.savedSearchEditAction.setEnabled(false);
1750 menuBar.savedSearchDeleteAction.setEnabled(false);
1751 selectedSavedSearchGUID = "";
1752 searchField.setEditText("");
1754 searchFieldChanged();
1756 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
1760 // Show/Hide note information
1761 private void toggleSavedSearchWindow() {
1762 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
1763 if (savedSearchTree.isVisible())
1764 savedSearchTree.hide();
1766 savedSearchTree.show();
1767 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
1769 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
1770 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
1776 //***************************************************************
1777 //***************************************************************
1778 //** These functions deal with Help menu & tool menu items
1779 //***************************************************************
1780 //***************************************************************
1781 // Show database status
1782 @SuppressWarnings("unused")
1783 private void databaseStatus() {
1785 int dirty = conn.getNoteTable().getDirtyCount();
1786 int unindexed = conn.getNoteTable().getUnindexedCount();
1787 DatabaseStatus status = new DatabaseStatus();
1788 status.setUnsynchronized(dirty);
1789 status.setUnindexed(unindexed);
1790 status.setNoteCount(conn.getNoteTable().getNoteCount());
1791 status.setNotebookCount(listManager.getNotebookIndex().size());
1792 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
1793 status.setTagCount(listManager.getTagIndex().size());
1794 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
1795 status.setWordCount(conn.getWordsTable().getWordCount());
1799 // Compact the database
1800 @SuppressWarnings("unused")
1801 private void compactDatabase() {
1802 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
1803 if (QMessageBox.question(this, "Confirmation", "This will free unused space in the database, "+
1804 "but please be aware that depending upon the size of your database this can be time consuming " +
1805 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?",
1806 QMessageBox.StandardButton.Yes,
1807 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
1810 setMessage("Compacting database.");
1812 listManager.compactDatabase();
1814 setMessage("Database compact is complete.");
1815 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
1817 @SuppressWarnings("unused")
1818 private void accountInformation() {
1819 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
1820 AccountDialog dialog = new AccountDialog();
1822 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
1824 @SuppressWarnings("unused")
1825 private void releaseNotes() {
1826 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
1827 QDialog dialog = new QDialog(this);
1828 QHBoxLayout layout = new QHBoxLayout();
1829 QTextEdit textBox = new QTextEdit();
1830 layout.addWidget(textBox);
1831 textBox.setReadOnly(true);
1832 QFile file = new QFile(Global.getDirectoryPath()+"release.txt");
1833 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
1834 QIODevice.OpenModeFlag.Text)))
1836 textBox.setText(file.readAll().toString());
1838 dialog.setWindowTitle("Release Notes");
1839 dialog.setLayout(layout);
1841 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
1843 // Called when user picks Log from the help menu
1844 @SuppressWarnings("unused")
1845 private void logger() {
1846 logger.log(logger.HIGH, "Entering NeverNote.logger");
1847 QDialog dialog = new QDialog(this);
1848 QHBoxLayout layout = new QHBoxLayout();
1849 QListWidget textBox = new QListWidget();
1850 layout.addWidget(textBox);
1851 textBox.addItems(emitLog);
1853 dialog.setLayout(layout);
1854 dialog.setWindowTitle("Mesasge Log");
1856 logger.log(logger.HIGH, "Leaving NeverNote.logger");
1858 // Menu option "help/about" was selected
1859 @SuppressWarnings("unused")
1860 private void about() {
1861 logger.log(logger.HIGH, "Entering NeverNote.about");
1862 QMessageBox.about(this,
1863 tr("About NeverNote"),
1864 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version "+Global.version+"<hr></center>Evernote"
1865 +" Generic client.<br><br>"
1866 +"Licensed under GPL v2. <br><hr><br>"
1867 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
1868 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
1869 +"PDFRenderer is licened under the LGPL<br>"
1870 +"Jazzy is licened under the LGPL<br>"
1871 +"Java is a registered trademark of Sun Microsystems.<br><hr>"));
1872 logger.log(logger.HIGH, "Leaving NeverNote.about");
1874 // Hide the entire left hand side
1875 @SuppressWarnings("unused")
1876 private void toggleLeftSide() {
1879 hidden = !menuBar.hideLeftSide.isChecked();
1880 menuBar.hideLeftSide.setChecked(!hidden);
1882 if (notebookTree.isVisible() != hidden)
1883 toggleNotebookWindow();
1884 if (savedSearchTree.isVisible() != hidden)
1885 toggleSavedSearchWindow();
1886 if (tagTree.isVisible() != hidden)
1888 if (attributeTree.isVisible() != hidden)
1889 toggleAttributesWindow();
1890 if (trashTree.isVisible() != hidden)
1891 toggleTrashWindow();
1893 Global.saveWindowVisible("leftPanel", hidden);
1898 //***************************************************************
1899 //***************************************************************
1900 //** These functions deal with the Toolbar
1901 //***************************************************************
1902 //***************************************************************
1903 // Text in the search bar has been cleared
1904 private void searchFieldCleared() {
1905 searchField.setEditText("");
1906 saveNoteIndexWidth();
1908 // text in the search bar changed. We only use this to tell if it was cleared,
1909 // otherwise we trigger off searchFieldChanged.
1910 @SuppressWarnings("unused")
1911 private void searchFieldTextChanged(String text) {
1912 if (text.trim().equals("")) {
1913 searchFieldCleared();
1914 if (searchPerformed) {
1916 listManager.setEnSearch("");
1917 ///// listManager.clearNoteIndexSearch();
1918 //noteIndexUpdated(true);
1919 listManager.loadNotesIndex();
1920 refreshEvernoteNote(true);
1921 noteIndexUpdated(false);
1923 searchPerformed = false;
1926 // Text in the toolbar has changed
1927 private void searchFieldChanged() {
1928 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
1930 saveNoteIndexWidth();
1931 String text = searchField.currentText();
1932 listManager.setEnSearch(text.trim());
1933 listManager.loadNotesIndex();
1934 //--->>> noteIndexUpdated(true);
1935 noteIndexUpdated(false);
1936 refreshEvernoteNote(true);
1937 searchPerformed = true;
1938 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
1940 // Build the window tool bar
1941 private void setupToolBar() {
1942 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
1943 toolBar = addToolBar(tr("toolBar"));
1945 prevButton = toolBar.addAction("Previous");
1946 QIcon prevIcon = new QIcon(iconPath+"back.png");
1947 prevButton.setIcon(prevIcon);
1948 prevButton.triggered.connect(this, "previousViewedAction()");
1950 nextButton = toolBar.addAction("Next");
1951 QIcon nextIcon = new QIcon(iconPath+"forward.png");
1952 nextButton.setIcon(nextIcon);
1953 nextButton.triggered.connect(this, "nextViewedAction()");
1955 upButton = toolBar.addAction("Up");
1956 QIcon upIcon = new QIcon(iconPath+"up.png");
1957 upButton.setIcon(upIcon);
1958 upButton.triggered.connect(this, "upAction()");
1960 downButton = toolBar.addAction("Down");
1961 QIcon downIcon = new QIcon(iconPath+"down.png");
1962 downButton.setIcon(downIcon);
1963 downButton.triggered.connect(this, "downAction()");
1965 synchronizeButton = toolBar.addAction("Synchronize");
1966 synchronizeAnimation = new ArrayList<QIcon>();
1967 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-0.png"));
1968 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-1.png"));
1969 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-2.png"));
1970 synchronizeAnimation.add(new QIcon(iconPath+"synchronize-3.png"));
1971 synchronizeButton.setIcon(synchronizeAnimation.get(0));
1972 synchronizeFrame = 0;
1973 synchronizeButton.triggered.connect(this, "evernoteSync()");
1975 printButton = toolBar.addAction("Print");
1976 QIcon printIcon = new QIcon(iconPath+"print.png");
1977 printButton.setIcon(printIcon);
1978 printButton.triggered.connect(this, "printNote()");
1980 tagButton = toolBar.addAction("Tag");
1981 QIcon tagIcon = new QIcon(iconPath+"tag.png");
1982 tagButton.setIcon(tagIcon);
1983 tagButton.triggered.connect(browserWindow, "modifyTags()");
1985 attributeButton = toolBar.addAction("Attributes");
1986 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
1987 attributeButton.setIcon(attributeIcon);
1988 attributeButton.triggered.connect(this, "toggleNoteInformation()");
1990 emailButton = toolBar.addAction("Email");
1991 QIcon emailIcon = new QIcon(iconPath+"email.png");
1992 emailButton.setIcon(emailIcon);
1993 emailButton.triggered.connect(this, "emailNote()");
1995 deleteButton = toolBar.addAction("Delete");
1996 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
1997 deleteButton.setIcon(deleteIcon);
1998 deleteButton.triggered.connect(this, "deleteNote()");
2000 newButton = toolBar.addAction("New");
2001 QIcon newIcon = new QIcon(iconPath+"new.png");
2002 newButton.triggered.connect(this, "addNote()");
2003 newButton.setIcon(newIcon);
2004 toolBar.addSeparator();
2005 toolBar.addWidget(new QLabel("Quota:"));
2006 toolBar.addWidget(quotaBar);
2007 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2011 zoomSpinner = new QSpinBox();
2012 zoomSpinner.setMinimum(10);
2013 zoomSpinner.setMaximum(1000);
2014 zoomSpinner.setAccelerated(true);
2015 zoomSpinner.setSingleStep(10);
2016 zoomSpinner.setValue(100);
2017 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2018 toolBar.addWidget(new QLabel("Zoom"));
2019 toolBar.addWidget(zoomSpinner);
2021 //toolBar.addWidget(new QLabel(" "));
2022 toolBar.addSeparator();
2023 toolBar.addWidget(new QLabel(" Search:"));
2024 toolBar.addWidget(searchField);
2025 QSizePolicy sizePolicy = new QSizePolicy();
2026 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2027 searchField.setSizePolicy(sizePolicy);
2028 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2030 searchClearButton = toolBar.addAction("Search Clear");
2031 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2032 searchClearButton.setIcon(searchClearIcon);
2033 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2035 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2037 // Update the sychronize button picture
2038 @SuppressWarnings("unused")
2039 private void updateSyncButton() {
2041 if (synchronizeFrame == 4)
2042 synchronizeFrame = 0;
2043 synchronizeButton.setIcon(synchronizeAnimation.get(synchronizeFrame));
2045 // Synchronize with Evernote
2046 @SuppressWarnings("unused")
2047 private void evernoteSync() {
2048 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2049 if (!Global.isConnected)
2051 if (Global.isConnected)
2052 synchronizeAnimationTimer.start(200);
2054 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2056 private void updateQuotaBar() {
2057 long limit = Global.getUploadLimit();
2058 long amount = Global.getUploadAmount();
2059 if (amount>0 && limit>0) {
2060 int percent =(int)(amount*100/limit);
2061 quotaBar.setValue(percent);
2063 quotaBar.setValue(0);
2066 @SuppressWarnings("unused")
2067 private void zoomChanged() {
2068 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2071 //****************************************************************
2072 //****************************************************************
2073 //* System Tray functions
2074 //****************************************************************
2075 //****************************************************************
2076 private void trayToggleVisible() {
2084 @SuppressWarnings("unused")
2085 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2086 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2087 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2088 trayToggleVisible();
2093 //***************************************************************
2094 //***************************************************************
2095 //** These functions deal with the trash tree
2096 //***************************************************************
2097 //***************************************************************
2098 // Setup the tree containing the trash.
2099 @SuppressWarnings("unused")
2100 private void trashTreeSelection() {
2101 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2103 clearNotebookFilter();
2105 clearAttributeFilter();
2106 clearSavedSearchFilter();
2108 String tempGuid = currentNoteGuid;
2110 // currentNoteGuid = "";
2111 currentNote = new Note();
2112 selectedNoteGUIDs.clear();
2113 listManager.getSelectedNotebooks().clear();
2114 listManager.getSelectedTags().clear();
2115 listManager.setSelectedSavedSearch("");
2116 browserWindow.clear();
2118 // toggle the add buttons
2119 newButton.setEnabled(!newButton.isEnabled());
2120 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2121 menuBar.noteAdd.setVisible(true);
2123 List<QTreeWidgetItem> selections = trashTree.selectedItems();
2124 if (selections.size() == 0) {
2125 currentNoteGuid = trashNoteGuid;
2126 trashNoteGuid = tempGuid;
2127 Global.showDeleted = false;
2128 menuBar.noteRestoreAction.setEnabled(false);
2129 menuBar.noteRestoreAction.setVisible(false);
2132 currentNoteGuid = trashNoteGuid;
2133 trashNoteGuid = tempGuid;
2134 menuBar.noteRestoreAction.setEnabled(true);
2135 menuBar.noteRestoreAction.setVisible(true);
2136 Global.showDeleted = true;
2138 listManager.loadNotesIndex();
2139 noteIndexUpdated(false);
2140 //// browserWindow.setEnabled(newButton.isEnabled());
2141 browserWindow.setReadOnly(!newButton.isEnabled());
2142 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
2144 // Empty the trash file
2145 @SuppressWarnings("unused")
2146 private void emptyTrash() {
2147 // browserWindow.clear();
2148 listManager.emptyTrash();
2149 if (trashTree.selectedItems().size() > 0) {
2150 listManager.getSelectedNotebooks().clear();
2151 listManager.getSelectedTags().clear();
2152 listManager.setSelectedSavedSearch("");
2153 newButton.setEnabled(!newButton.isEnabled());
2154 menuBar.noteAdd.setEnabled(newButton.isEnabled());
2155 menuBar.noteAdd.setVisible(true);
2156 browserWindow.clear();
2159 clearNotebookFilter();
2160 clearSavedSearchFilter();
2161 clearAttributeFilter();
2163 Global.showDeleted = false;
2164 menuBar.noteRestoreAction.setEnabled(false);
2165 menuBar.noteRestoreAction.setVisible(false);
2167 listManager.loadNotesIndex();
2168 //--->>> noteIndexUpdated(true);
2169 noteIndexUpdated(false);
2172 // Show/Hide trash window
2173 private void toggleTrashWindow() {
2174 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
2175 if (trashTree.isVisible())
2179 menuBar.hideTrash.setChecked(trashTree.isVisible());
2181 Global.saveWindowVisible("trashTree", trashTree.isVisible());
2182 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
2184 private void clearTrashFilter() {
2185 Global.showDeleted = false;
2186 newButton.setEnabled(true);
2187 menuBar.noteAdd.setEnabled(true);
2188 menuBar.noteAdd.setVisible(true);
2189 trashTree.blockSignals(true);
2190 trashTree.clearSelection();
2191 trashTree.blockSignals(false);
2196 //***************************************************************
2197 //***************************************************************
2198 //** These functions deal with connection settings
2199 //***************************************************************
2200 //***************************************************************
2201 // SyncRunner had a problem and things are disconnected
2202 @SuppressWarnings("unused")
2203 private void remoteErrorDisconnect() {
2204 menuBar.connectAction.setText("Connect");
2205 menuBar.connectAction.setToolTip("Connect to Evernote");
2206 menuBar.synchronizeAction.setEnabled(false);
2207 synchronizeAnimationTimer.stop();
2210 // Do a manual connect/disconnect
2211 private void remoteConnect() {
2212 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
2214 if (Global.isConnected) {
2215 Global.isConnected = false;
2216 syncRunner.enDisconnect();
2217 setupConnectMenuOptions();
2222 AESEncrypter aes = new AESEncrypter();
2224 aes.decrypt(new FileInputStream(Global.getDirectoryPath()+"secure.txt"));
2225 } catch (FileNotFoundException e) {
2226 // File not found, so we'll just get empty strings anyway.
2228 String userid = aes.getUserid();
2229 String password = aes.getPassword();
2230 if (!userid.equals("") && !password.equals("")) {
2231 Global.username = userid;
2232 Global.password = password;
2235 // Show the login dialog box
2236 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
2237 LoginDialog login = new LoginDialog();
2240 if (!login.okPressed()) {
2244 Global.username = login.getUserid();
2245 Global.password = login.getPassword();
2247 syncRunner.username = Global.username;
2248 syncRunner.password = Global.password;
2249 syncRunner.userStoreUrl = Global.userStoreUrl;
2250 syncRunner.noteStoreUrl = Global.noteStoreUrl;
2251 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
2252 syncRunner.enConnect();
2253 Global.isConnected = syncRunner.isConnected;
2255 setupConnectMenuOptions();
2256 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
2258 private void setupConnectMenuOptions() {
2259 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
2260 if (!Global.isConnected) {
2261 menuBar.connectAction.setText("Connect");
2262 menuBar.connectAction.setToolTip("Connect to Evernote");
2263 menuBar.synchronizeAction.setEnabled(false);
2265 menuBar.connectAction.setText("Disconnect");
2266 menuBar.connectAction.setToolTip("Disconnect from Evernote");
2267 menuBar.synchronizeAction.setEnabled(true);
2269 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
2274 //***************************************************************
2275 //***************************************************************
2276 //** These functions deal with the GUI Attribute tree
2277 //***************************************************************
2278 //***************************************************************
2279 @SuppressWarnings("unused")
2280 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
2283 clearNotebookFilter();
2285 clearSavedSearchFilter();
2287 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
2288 if (item.childCount() > 0) {
2289 item.setSelected(false);
2291 Global.createdBeforeFilter.reset();
2292 Global.createdSinceFilter.reset();
2293 Global.changedBeforeFilter.reset();
2294 Global.changedSinceFilter.reset();
2295 Global.containsFilter.reset();
2296 attributeTreeSelected = item;
2297 DateAttributeFilterTable f = null;
2298 f = findDateAttributeFilterTable(item.parent());
2300 f.select(item.text(0));
2302 String text = item.text(0);
2303 Global.containsFilter.select(text);
2306 listManager.loadNotesIndex();
2307 noteIndexUpdated(false);
2310 attributeTreeSelected = null;
2311 item.setSelected(false);
2312 Global.createdBeforeFilter.reset();
2313 Global.createdSinceFilter.reset();
2314 Global.changedBeforeFilter.reset();
2315 Global.changedSinceFilter.reset();
2316 Global.containsFilter.reset();
2317 listManager.loadNotesIndex();
2318 noteIndexUpdated(false);
2320 // This determines what attribute filter we need, depending upon the selection
2321 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
2322 if (w.parent() != null && w.childCount() > 0) {
2323 QTreeWidgetItem parent = w.parent();
2324 if (parent.text(0).equalsIgnoreCase("created") &&
2325 w.text(0).equalsIgnoreCase("since"))
2326 return Global.createdSinceFilter;
2327 if (parent.text(0).equalsIgnoreCase("created") &&
2328 w.text(0).equalsIgnoreCase("before"))
2329 return Global.createdBeforeFilter;
2330 if (parent.text(0).equalsIgnoreCase("last modified") &&
2331 w.text(0).equalsIgnoreCase("since"))
2332 return Global.changedSinceFilter;
2333 if (parent.text(0).equalsIgnoreCase("last modified") &&
2334 w.text(0).equalsIgnoreCase("before"))
2335 return Global.changedBeforeFilter;
2339 // Show/Hide attribute search window
2340 private void toggleAttributesWindow() {
2341 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
2342 if (attributeTree.isVisible())
2343 attributeTree.hide();
2345 attributeTree.show();
2346 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
2348 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
2349 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
2351 private void clearAttributeFilter() {
2352 Global.createdBeforeFilter.reset();
2353 Global.createdSinceFilter.reset();
2354 Global.changedBeforeFilter.reset();
2355 Global.changedSinceFilter.reset();
2356 Global.containsFilter.reset();
2357 attributeTreeSelected = null;
2358 attributeTree.blockSignals(true);
2359 attributeTree.clearSelection();
2360 attributeTree.blockSignals(false);
2364 //***************************************************************
2365 //***************************************************************
2366 //** These functions deal with the GUI Note index table
2367 //***************************************************************
2368 //***************************************************************
2369 // Initialize the note list table
2370 private void initializeNoteTable() {
2371 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
2372 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
2373 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
2374 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
2376 // Show/Hide trash window
2377 @SuppressWarnings("unused")
2378 private void toggleNoteListWindow() {
2379 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
2380 if (noteTableView.isVisible())
2381 noteTableView.hide();
2383 noteTableView.show();
2384 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
2386 Global.saveWindowVisible("noteList", noteTableView.isVisible());
2387 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
2389 // Handle the event that a user selects a note from the table
2390 @SuppressWarnings("unused")
2391 private void noteTableSelection() {
2392 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
2394 if (historyGuids.size() == 0) {
2395 historyGuids.add(currentNoteGuid);
2396 historyPosition = 1;
2398 noteTableView.showColumn(Global.noteTableGuidPosition);
2400 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2401 noteTableView.hideColumn(Global.noteTableGuidPosition);
2403 if (selections.size() > 0) {
2405 menuBar.noteDuplicateAction.setEnabled(true);
2406 menuBar.noteOnlineHistoryAction.setEnabled(true);
2407 menuBar.noteMergeAction.setEnabled(true);
2408 selectedNoteGUIDs.clear();
2409 if (selections.size() != 1 || Global.showDeleted) {
2410 menuBar.noteDuplicateAction.setEnabled(false);
2412 if (selections.size() != 1 || !Global.isConnected) {
2413 menuBar.noteOnlineHistoryAction.setEnabled(false);
2415 if (selections.size() == 1) {
2416 menuBar.noteMergeAction.setEnabled(false);
2418 for (int i=0; i<selections.size(); i++) {
2419 int row = selections.get(i).row();
2421 upButton.setEnabled(false);
2423 upButton.setEnabled(true);
2424 if (row < noteTableView.model.rowCount()-1)
2425 downButton.setEnabled(true);
2427 downButton.setEnabled(false);
2428 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
2429 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
2430 currentNoteGuid = (String)ix.values().toArray()[0];
2431 selectedNoteGUIDs.add(currentNoteGuid);
2435 nextButton.setEnabled(true);
2436 prevButton.setEnabled(true);
2438 int endPosition = historyGuids.size()-1;
2439 for (int j=historyPosition; j<=endPosition; j++) {
2440 historyGuids.remove(historyGuids.size()-1);
2442 historyGuids.add(currentNoteGuid);
2443 historyPosition = historyGuids.size();
2445 if (historyPosition <= 1)
2446 prevButton.setEnabled(false);
2447 if (historyPosition == historyGuids.size())
2448 nextButton.setEnabled(false);
2450 fromHistory = false;
2451 scrollToGuid(currentNoteGuid);
2452 refreshEvernoteNote(true);
2453 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
2455 // Trigger a refresh when the note db has been updated
2456 private void noteIndexUpdated(boolean reload) {
2457 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
2458 Global.traceReset();
2460 refreshEvernoteNoteList();
2461 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
2462 noteTableView.load(listManager, reload);
2463 scrollToGuid(currentNoteGuid);
2464 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
2466 // Called when the list of notes is updated
2467 private void refreshEvernoteNoteList() {
2468 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
2469 browserWindow.setDisabled(false);
2470 if (selectedNoteGUIDs == null)
2471 selectedNoteGUIDs = new ArrayList<String>();
2472 selectedNoteGUIDs.clear(); // clear out old entries
2474 String saveCurrentNoteGuid = new String();
2475 String tempNoteGuid = new String();
2477 historyGuids.clear();
2478 historyPosition = 0;
2479 prevButton.setEnabled(false);
2480 nextButton.setEnabled(false);
2482 if (currentNoteGuid == null)
2483 currentNoteGuid = new String();
2485 for (Note note : listManager.getNoteIndex()) {
2486 tempNoteGuid = note.getGuid();
2487 if (currentNoteGuid.equals(tempNoteGuid)) {
2488 saveCurrentNoteGuid = new String(tempNoteGuid);
2492 if (listManager.getNoteIndex().size() == 0) {
2493 currentNoteGuid = "";
2495 browserWindow.clear();
2496 browserWindow.setDisabled(true);
2499 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() >0) {
2500 currentNoteGuid = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1).getGuid();
2501 currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
2502 refreshEvernoteNote(true);
2504 refreshEvernoteNote(false);
2508 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
2510 // Called when the previous arrow button is clicked
2511 @SuppressWarnings("unused")
2512 private void previousViewedAction() {
2513 if (!prevButton.isEnabled())
2515 if (historyPosition == 0)
2518 if (historyPosition <= 0)
2520 String historyGuid = historyGuids.get(historyPosition-1);
2522 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2523 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
2524 if (modelIndex != null) {
2525 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2526 String tableGuid = (String)ix.values().toArray()[0];
2527 if (tableGuid.equals(historyGuid)) {
2528 noteTableView.selectRow(i);
2534 @SuppressWarnings("unused")
2535 private void nextViewedAction() {
2536 if (!nextButton.isEnabled())
2538 String historyGuid = historyGuids.get(historyPosition);
2541 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2542 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
2543 if (modelIndex != null) {
2544 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
2545 String tableGuid = (String)ix.values().toArray()[0];
2546 if (tableGuid.equals(historyGuid)) {
2547 noteTableView.selectRow(i);
2553 // Called when the up arrow is clicked
2554 @SuppressWarnings("unused")
2555 private void upAction() {
2556 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2557 int row = selections.get(0).row();
2559 noteTableView.selectRow(row-1);
2562 // Called when the down arrow is clicked
2563 @SuppressWarnings("unused")
2564 private void downAction() {
2565 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2566 int row = selections.get(0).row();
2567 int max = noteTableView.model.rowCount();
2569 noteTableView.selectRow(row+1);
2572 // Update a tag string for a specific note in the list
2573 @SuppressWarnings("unused")
2574 private void updateListTags(String guid, List<String> tags) {
2575 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
2576 StringBuffer tagBuffer = new StringBuffer();
2577 for (int i=0; i<tags.size(); i++) {
2578 tagBuffer.append(tags.get(i));
2579 if (i<tags.size()-1)
2580 tagBuffer.append(", ");
2583 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2584 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2585 if (modelIndex != null) {
2586 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2587 String tableGuid = (String)ix.values().toArray()[0];
2588 if (tableGuid.equals(guid)) {
2589 noteTableView.model.setData(i, Global.noteTableTagPosition,tagBuffer.toString());
2590 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2595 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
2597 // Update a title for a specific note in the list
2598 @SuppressWarnings("unused")
2599 private void updateListTitle(String guid, String title) {
2600 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2602 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2603 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2604 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2605 if (modelIndex != null) {
2606 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2607 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2608 String tableGuid = (String)ix.values().toArray()[0];
2609 if (tableGuid.equals(guid)) {
2610 noteTableView.model.setData(i, Global.noteTableTitlePosition,title);
2611 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2616 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2618 // Update a title for a specific note in the list
2619 @SuppressWarnings("unused")
2620 private void updateListAuthor(String guid, String author) {
2621 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2623 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2624 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2625 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2626 if (modelIndex != null) {
2627 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2628 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2629 String tableGuid = (String)ix.values().toArray()[0];
2630 if (tableGuid.equals(guid)) {
2631 noteTableView.model.setData(i, Global.noteTableAuthorPosition,author);
2632 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2637 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2639 private void updateListNoteNotebook(String guid, String notebook) {
2640 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2642 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2643 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2644 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2645 if (modelIndex != null) {
2646 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2647 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2648 String tableGuid = (String)ix.values().toArray()[0];
2649 if (tableGuid.equals(guid)) {
2650 noteTableView.model.setData(i, Global.noteTableNotebookPosition,notebook);
2651 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2656 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2658 // Update a title for a specific note in the list
2659 @SuppressWarnings("unused")
2660 private void updateListSourceUrl(String guid, String url) {
2661 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2663 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2664 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
2665 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2666 if (modelIndex != null) {
2667 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
2668 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2669 String tableGuid = (String)ix.values().toArray()[0];
2670 if (tableGuid.equals(guid)) {
2671 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2672 noteTableView.model.setData(i, Global.noteTableSourceUrlPosition,url);
2677 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2679 private void updateListGuid(String oldGuid, String newGuid) {
2680 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
2682 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2683 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2684 if (modelIndex != null) {
2685 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2686 String tableGuid = (String)ix.values().toArray()[0];
2687 if (tableGuid.equals(oldGuid)) {
2688 noteTableView.model.setData(i, Global.noteTableGuidPosition,newGuid);
2689 //noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2694 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
2696 private void updateListTagName(String guid) {
2697 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2699 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2700 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2701 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2703 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2704 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2705 if (modelIndex != null) {
2706 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2707 String noteGuid = (String)ix.values().toArray()[0];
2708 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2709 noteTableView.model.setData(i, Global.noteTableTagPosition, newName);
2710 //noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2711 i=noteTableView.model.rowCount();
2717 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2719 private void removeListTagName(String guid) {
2720 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
2722 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
2723 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
2724 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
2725 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
2726 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
2729 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
2730 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2731 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2732 if (modelIndex != null) {
2733 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2734 String noteGuid = (String)ix.values().toArray()[0];
2735 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
2736 noteTableView.model.setData(i, Global.noteTableTagPosition, newName);
2737 // noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2738 i=noteTableView.model.rowCount();
2744 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
2746 private void updateListNotebookName(String oldName, String newName) {
2747 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
2749 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2750 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableNotebookPosition);
2751 if (modelIndex != null) {
2752 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2753 String tableName = (String)ix.values().toArray()[0];
2754 if (tableName.equalsIgnoreCase(oldName)) {
2755 // noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2756 noteTableView.model.setData(i, Global.noteTableNotebookPosition, newName);
2760 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
2762 @SuppressWarnings("unused")
2763 private void updateListDateCreated(String guid, QDateTime date) {
2764 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
2766 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2767 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2768 if (modelIndex != null) {
2769 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2770 String tableGuid = (String)ix.values().toArray()[0];
2771 if (tableGuid.equals(guid)) {
2772 noteTableView.model.setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2777 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2779 @SuppressWarnings("unused")
2780 private void updateListDateSubject(String guid, QDateTime date) {
2781 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
2783 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2784 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2785 if (modelIndex != null) {
2786 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2787 String tableGuid = (String)ix.values().toArray()[0];
2788 if (tableGuid.equals(guid)) {
2789 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2790 noteTableView.model.setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2795 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
2797 @SuppressWarnings("unused")
2798 private void updateListDateChanged(String guid, QDateTime date) {
2799 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2801 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2802 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2803 if (modelIndex != null) {
2804 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2805 String tableGuid = (String)ix.values().toArray()[0];
2806 if (tableGuid.equals(guid)) {
2807 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2808 noteTableView.model.setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2813 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2815 private void updateListDateChanged() {
2816 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
2817 QDateTime date = new QDateTime(QDateTime.currentDateTime());
2818 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2819 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2820 if (modelIndex != null) {
2821 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2822 String tableGuid = (String)ix.values().toArray()[0];
2823 if (tableGuid.equals(currentNoteGuid)) {
2824 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2825 noteTableView.model.setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
2830 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
2833 @SuppressWarnings("unused")
2834 private void scrollToCurrentGuid() {
2835 //scrollToGuid(currentNoteGuid);
2836 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
2837 if (selections.size() == 0)
2839 QModelIndex index = selections.get(0);
2840 int row = selections.get(0).row();
2841 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
2844 // Scroll to a particular index item
2845 private void scrollToGuid(String guid) {
2846 if (currentNote == null || guid == null)
2848 if (currentNote.isActive() && Global.showDeleted) {
2849 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2850 if (!listManager.getNoteIndex().get(i).isActive()) {
2851 currentNote = listManager.getNoteIndex().get(i);
2852 currentNoteGuid = currentNote.getGuid();
2853 i = listManager.getNoteIndex().size();
2858 if (!currentNote.isActive() && !Global.showDeleted) {
2859 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2860 if (listManager.getNoteIndex().get(i).isActive()) {
2861 currentNote = listManager.getNoteIndex().get(i);
2862 currentNoteGuid = currentNote.getGuid();
2863 i = listManager.getNoteIndex().size();
2869 for (int i=0; i<noteTableView.model().rowCount(); i++) {
2870 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
2871 if (currentNoteGuid.equals(index.data())) {
2872 // noteTableView.setCurrentIndex(index);
2873 noteTableView.selectRow(i);
2874 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
2875 i=noteTableView.model.rowCount();
2879 // Show/Hide columns
2880 private void showColumns() {
2881 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
2882 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
2883 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
2884 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
2885 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
2886 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
2887 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
2888 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
2890 // Open a separate window
2891 @SuppressWarnings("unused")
2892 private void listDoubleClick() {
2895 // Title color has changed
2896 @SuppressWarnings("unused")
2897 private void titleColorChanged(Integer color) {
2898 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
2900 QColor backgroundColor = new QColor();
2901 QColor foregroundColor = new QColor(QColor.black);
2902 backgroundColor.setRgb(color);
2904 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
2905 foregroundColor.setRgb(QColor.white.rgb());
2907 if (selectedNoteGUIDs.size() == 0)
2908 selectedNoteGUIDs.add(currentNoteGuid);
2910 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
2911 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2912 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2913 if (modelIndex != null) {
2914 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2915 String tableGuid = (String)ix.values().toArray()[0];
2916 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
2917 for (int k=0; k<Global.noteTableColumnCount; k++) {
2918 noteTableView.model.setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
2919 noteTableView.model.setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
2920 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
2922 i=noteTableView.model.rowCount();
2927 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
2931 //***************************************************************
2932 //***************************************************************
2933 //** These functions deal with Note specific things
2934 //***************************************************************
2935 //***************************************************************
2936 @SuppressWarnings("unused")
2937 private void setNoteDirty() {
2938 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
2941 listManager.getUnsynchronizedNotes().add(currentNoteGuid);
2942 for (int i=0; i<noteTableView.model.rowCount(); i++) {
2943 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
2944 if (modelIndex != null) {
2945 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
2946 String tableGuid = (String)ix.values().toArray()[0];
2947 if (tableGuid.equals(currentNoteGuid)) {
2948 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, "false");
2953 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
2955 private void saveNote() {
2956 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
2958 logger.log(logger.EXTREME, "Note is dirty.");
2961 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
2962 preview.finished.connect(this, "saveThumbnail(String)");
2963 preview.setContent(browserWindow.getContent());
2965 logger.log(logger.EXTREME, "Saving to cache");
2966 QTextCodec codec = QTextCodec.codecForLocale();
2967 // QTextDecoder decoder = codec.makeDecoder();
2968 codec = QTextCodec.codecForName("UTF-8");
2969 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
2970 noteCache.put(currentNoteGuid, unicode.toString());
2972 logger.log(logger.EXTREME, "updating list manager");
2973 listManager.updateNoteContent(currentNoteGuid, browserWindow.getContent());
2974 logger.log(logger.EXTREME, "Updating title");
2975 listManager.updateNoteTitle(currentNoteGuid, browserWindow.getTitle());
2976 updateListDateChanged();
2978 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
2979 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
2980 if (listManager.getNoteIndex().get(i).getGuid().equals(currentNoteGuid)) {
2981 currentNote = listManager.getNoteIndex().get(i);
2982 i = listManager.getNoteIndex().size();
2989 // Get a note from Evernote (and put it in the browser)
2990 private void refreshEvernoteNote(boolean reload) {
2991 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
2992 if (Global.disableViewing) {
2993 browserWindow.setEnabled(false);
2997 if (!Global.showDeleted)
2998 browserWindow.setReadOnly(false);
2999 Global.cryptCounter =0;
3000 if (currentNoteGuid.equals("")) {
3001 browserWindow.setReadOnly(true);
3008 browserWindow.loadingData(true);
3010 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
3011 if (currentNote == null)
3014 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3015 QByteArray js = new QByteArray();
3016 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
3017 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
3018 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>");
3019 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
3020 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
3021 js.append("</head>");
3022 js.append(rebuildNoteHTML(currentNoteGuid, currentNote.getContent()));
3023 js.append("</HTML>");
3024 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
3025 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
3026 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
3027 browserWindow.getBrowser().setContent(js);
3028 noteCache.put(currentNoteGuid, js.toString());
3029 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
3030 preview = new Thumbnailer(currentNoteGuid, new QSize(1024,768));
3031 preview.finished.connect(this, "saveThumbnail(String)");
3032 preview.setContent(js.toString());
3035 logger.log(logger.HIGH, "Note content is being pulled from the cache");
3036 String cachedContent = modifyCachedTodoTags(noteCache.get(currentNoteGuid));
3037 browserWindow.getBrowser().setContent(new QByteArray(cachedContent));
3040 browserWindow.getBrowser().page().setContentEditable(!inkNote); // We don't allow editing of ink notes
3041 browserWindow.setNote(currentNote);
3043 // Build a list of non-closed notebooks
3044 List<Notebook> nbooks = new ArrayList<Notebook>();
3045 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3046 boolean found=false;
3047 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3048 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
3052 nbooks.add(listManager.getNotebookIndex().get(i));
3055 browserWindow.setNotebookList(nbooks);
3056 browserWindow.setTitle(currentNote.getTitle());
3057 browserWindow.setTag(getTagNamesForNote(currentNote));
3058 browserWindow.setAuthor(currentNote.getAttributes().getAuthor());
3060 browserWindow.setAltered(currentNote.getUpdated());
3061 browserWindow.setCreation(currentNote.getCreated());
3062 if (currentNote.getAttributes().getSubjectDate() > 0)
3063 browserWindow.setSubjectDate(currentNote.getAttributes().getSubjectDate());
3065 browserWindow.setSubjectDate(currentNote.getCreated());
3066 browserWindow.setUrl(currentNote.getAttributes().getSourceURL());
3067 browserWindow.setAllTags(listManager.getTagIndex());
3068 browserWindow.setCurrentTags(currentNote.getTagNames());
3070 scrollToGuid(currentNoteGuid);
3072 browserWindow.loadingData(false);
3073 if (thumbnailViewer.isActiveWindow())
3076 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
3078 // Save a generated thumbnail
3079 @SuppressWarnings("unused")
3080 private void saveThumbnail(String guid) {
3081 QFile tFile = new QFile(Global.currentDir+"res/thumbnail-"+guid+".png");
3082 tFile.open(OpenModeFlag.ReadOnly);
3083 QByteArray imgBytes = tFile.readAll();
3085 conn.getNoteTable().setThumbnail(guid, imgBytes);
3086 conn.getNoteTable().setThumbnailNeeded(guid, false);
3087 thumbnailViewer.setThumbnail(QImage.fromData(imgBytes));
3088 if (thumbnailViewer.isVisible())
3089 thumbnailViewer.showFullScreen();
3092 QByteArray img2 = new QByteArray(conn.getNoteTable().getThumbnail(guid));
3093 QFile file = new QFile(Global.currentDir+"res/aaaa.png");
3094 file.open(OpenModeFlag.WriteOnly);
3099 // Show/Hide note information
3100 @SuppressWarnings("unused")
3101 private void toggleNoteInformation() {
3102 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
3103 browserWindow.toggleInformation();
3104 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
3105 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
3107 // Listener triggered when a print button is pressed
3108 @SuppressWarnings("unused")
3109 private void printNote() {
3110 logger.log(logger.HIGH, "Entering NeverNote.printNote");
3112 QPrintDialog dialog = new QPrintDialog();
3113 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
3114 QPrinter printer = dialog.printer();
3115 browserWindow.getBrowser().print(printer);
3117 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
3120 // Listener triggered when the email button is pressed
3121 @SuppressWarnings("unused")
3122 private void emailNote() {
3123 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
3125 if (Desktop.isDesktopSupported()) {
3126 Desktop desktop = Desktop.getDesktop();
3128 String text2 = browserWindow.getContentsToEmail();
3129 QUrl url = new QUrl("mailto:");
3130 url.addQueryItem("subject", currentNote.getTitle());
3131 url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
3132 QDesktopServices.openUrl(url);
3136 if (desktop.isSupported(Desktop.Action.MAIL)) {
3137 URI uriMailTo = null;
3139 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
3140 String text = browserWindow.getContentsToEmail();
3141 //text = "<b>" +text +"</b>";
3142 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3143 +"&BODY=" +text, null);
3144 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
3145 +"&ATTACHMENT=d:/test.pdf", null);
3146 desktop.mail(uriMailTo);
3147 } catch (URISyntaxException e) {
3148 e.printStackTrace();
3149 } catch (IOException e) {
3150 e.printStackTrace();
3157 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
3159 // Reindex all notes
3160 @SuppressWarnings("unused")
3161 private void fullReindex() {
3162 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
3163 // If we are deleting non-trash notes
3164 if (currentNote.getDeleted() == 0) {
3165 if (QMessageBox.question(this, "Confirmation", "This will cause all notes & attachments to be reindexed, "+
3166 "but please be aware that depending upon the size of your database updating all these records " +
3167 "can be time consuming and NeverNote will be unresponsive until it is complete. Do you wish to continue?",
3168 QMessageBox.StandardButton.Yes,
3169 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3174 setMessage("Marking notes for reindex.");
3175 conn.getNoteTable().reindexAllNotes();
3176 conn.getNoteTable().noteResourceTable.reindexAll();
3177 setMessage("Database will be reindexed.");
3179 logger.log(logger.HIGH, "Leaving NeverNote.fullRefresh");
3181 // Listener when a user wants to reindex a specific note
3182 @SuppressWarnings("unused")
3183 private void reindexNote() {
3184 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
3185 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3186 conn.getNoteTable().setIndexNeeded(selectedNoteGUIDs.get(i), true);
3188 if (selectedNotebookGUIDs.size() > 1)
3189 setMessage("Notes will be reindexed.");
3191 setMessage("Note will be reindexed.");
3192 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
3195 @SuppressWarnings("unused")
3196 private void deleteNote() {
3197 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
3198 if (currentNote == null)
3200 if (currentNoteGuid.equals(""))
3203 // If we are deleting non-trash notes
3204 if (currentNote.isActive()) {
3205 if (Global.verifyDelete()) {
3206 if (QMessageBox.question(this, "Confirmation", "Delete selected note(s)?",
3207 QMessageBox.StandardButton.Yes,
3208 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
3212 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3213 selectedNoteGUIDs.add(currentNoteGuid);
3214 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3215 listManager.deleteNote(selectedNoteGUIDs.get(i));
3218 // If we are deleting from the trash.
3219 if (Global.verifyDelete()) {
3220 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
3221 QMessageBox.StandardButton.Yes,
3222 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
3226 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3227 selectedNoteGUIDs.add(currentNoteGuid);
3228 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
3229 for (int j=noteTableView.model.rowCount()-1; j>=0; j--) {
3230 QModelIndex modelIndex = noteTableView.model.index(j, Global.noteTableGuidPosition);
3231 if (modelIndex != null) {
3232 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
3233 String tableGuid = (String)ix.values().toArray()[0];
3234 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
3235 noteTableView.model.removeRow(j);
3240 listManager.expungeNote(selectedNoteGUIDs.get(i));
3243 currentNoteGuid = "";
3244 listManager.loadNotesIndex();
3245 noteIndexUpdated(false);
3246 refreshEvernoteNote(true);
3247 scrollToGuid(currentNoteGuid);
3248 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
3251 @SuppressWarnings("unused")
3252 private void addNote() {
3253 logger.log(logger.HIGH, "Inside NeverNote.addNote");
3254 // browserWindow.setEnabled(true);
3255 browserWindow.setReadOnly(false);
3257 Calendar currentTime = new GregorianCalendar();
3258 String noteString = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
3259 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
3260 "<en-note>\n<br clear=\"none\" /></en-note>");
3262 Long l = new Long(currentTime.getTimeInMillis());
3263 String randint = new String(Long.toString(l));
3265 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
3267 // for the first non-archived notebook. Finally, if nothing else we
3268 // pick the first notebook in the list.
3269 String notebook = null;
3270 listManager.getNotebookIndex().get(0).getGuid();
3271 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
3272 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
3273 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
3274 notebook = currentSelectedNotebook.text(2);
3276 boolean found = false;
3277 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
3278 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
3279 boolean match = false;
3280 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
3281 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
3283 j = listManager.getArchiveNotebookIndex().size();
3287 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
3289 // Now we have a list of good notebooks, so we can look for the default
3291 for (int i=0; i<goodNotebooks.size(); i++) {
3292 if (goodNotebooks.get(i).isDefaultNotebook()) {
3293 notebook = goodNotebooks.get(i).getGuid();
3295 i = goodNotebooks.size();
3299 if (goodNotebooks.size() > 0 && !found)
3300 notebook = goodNotebooks.get(0).getGuid();
3303 notebook = listManager.getNotebookIndex().get(0).getGuid();
3306 Note newNote = new Note();
3307 newNote.setUpdateSequenceNum(0);
3308 newNote.setGuid(randint);
3309 newNote.setNotebookGuid(notebook);
3310 newNote.setTitle("");
3311 newNote.setContent(noteString);
3312 newNote.setDeleted(0);
3313 newNote.setCreated(System.currentTimeMillis());
3314 newNote.setUpdated(System.currentTimeMillis());
3315 newNote.setActive(true);
3316 NoteAttributes na = new NoteAttributes();
3317 na.setLatitude(0.0);
3318 na.setLongitude(0.0);
3319 na.setAltitude(0.0);
3320 newNote.setAttributes(new NoteAttributes());
3321 conn.getNoteTable().addNote(newNote, true);
3322 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3323 noteTableView.insertRow(listManager, newNote, true, -1);
3325 currentNote = newNote;
3326 currentNoteGuid = currentNote.getGuid();
3327 listManager.addNote(newNote);
3328 refreshEvernoteNote(true);
3329 listManager.countNotebookResults(listManager.getNoteIndex());
3330 browserWindow.titleLabel.setFocus();
3331 browserWindow.titleLabel.selectAll();
3332 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
3333 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
3335 // Restore a note from the trash;
3336 @SuppressWarnings("unused")
3337 private void restoreNote() {
3339 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
3340 selectedNoteGUIDs.add(currentNoteGuid);
3341 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
3342 listManager.restoreNote(selectedNoteGUIDs.get(i));
3344 currentNoteGuid = "";
3345 listManager.loadNotesIndex();
3346 noteIndexUpdated(false);
3349 // Search a note for specific txt
3350 @SuppressWarnings("unused")
3351 private void findText() {
3353 find.setFocusOnTextField();
3355 @SuppressWarnings("unused")
3356 private void doFindText() {
3357 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
3360 // Signal received that note content has changed. Normally we just need the guid to remove
3361 // it from the cache.
3362 @SuppressWarnings("unused")
3363 private void invalidateNoteCache(String guid, String content) {
3364 String v = noteCache.remove(guid);
3365 if (content != null) {
3366 v = noteCache.put(guid, content);
3369 // Signal received that a note guid has changed
3370 @SuppressWarnings("unused")
3371 private void noteGuidChanged(String oldGuid, String newGuid) {
3372 if (noteCache.containsKey(oldGuid)) {
3373 String cache = noteCache.get(oldGuid);
3374 noteCache.put(newGuid, cache);
3375 noteCache.remove(oldGuid);
3377 listManager.updateNoteGuid(oldGuid, newGuid, false);
3378 if (currentNoteGuid.equals(oldGuid)) {
3379 if (currentNote != null)
3380 currentNote.setGuid(newGuid);
3381 currentNoteGuid = newGuid;
3383 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3384 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
3385 noteTableView.proxyModel.addGuid(newGuid);
3386 i=listManager.getNoteIndex().size();
3389 updateListGuid(oldGuid, newGuid);
3391 // Toggle the note editor button bar
3392 private void toggleEditorButtonBar() {
3393 if (browserWindow.buttonsVisible) {
3394 browserWindow.hideButtons();
3395 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
3396 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3398 browserWindow.buttonsVisible = true;
3399 showEditorButtons();
3401 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
3403 // Show editor buttons
3404 private void showEditorButtons() {
3405 browserWindow.undoButton.setVisible(false);
3406 browserWindow.redoButton.setVisible(false);
3407 browserWindow.cutButton.setVisible(false);
3408 browserWindow.copyButton.setVisible(false);
3409 browserWindow.pasteButton.setVisible(false);
3410 browserWindow.strikethroughButton.setVisible(false);
3411 browserWindow.underlineButton.setVisible(false);
3412 browserWindow.boldButton.setVisible(false);
3413 browserWindow.italicButton.setVisible(false);
3414 browserWindow.hlineButton.setVisible(false);
3415 browserWindow.indentButton.setVisible(false);
3416 browserWindow.outdentButton.setVisible(false);
3417 browserWindow.fontList.setVisible(false);
3418 browserWindow.fontSize.setVisible(false);
3419 browserWindow.fontColor.setVisible(false);
3420 browserWindow.fontHilight.setVisible(false);
3421 browserWindow.leftAlignButton.setVisible(false);
3422 browserWindow.centerAlignButton.setVisible(false);
3423 browserWindow.rightAlignButton.setVisible(false);
3424 browserWindow.indentButton.setVisible(false);
3425 browserWindow.outdentButton.setVisible(false);
3427 browserWindow.undoButton.setVisible(Global.isEditorButtonVisible("undo"));
3428 browserWindow.redoButton.setVisible(Global.isEditorButtonVisible("redo"));
3429 browserWindow.cutButton.setVisible(Global.isEditorButtonVisible("cut"));
3430 browserWindow.copyButton.setVisible(Global.isEditorButtonVisible("copy"));
3431 browserWindow.pasteButton.setVisible(Global.isEditorButtonVisible("paste"));
3432 browserWindow.strikethroughButton.setVisible(Global.isEditorButtonVisible("strikethrough"));
3433 browserWindow.underlineButton.setVisible(Global.isEditorButtonVisible("underline"));
3434 browserWindow.boldButton.setVisible(Global.isEditorButtonVisible("bold"));
3435 browserWindow.italicButton.setVisible(Global.isEditorButtonVisible("italic"));
3436 browserWindow.hlineButton.setVisible(Global.isEditorButtonVisible("hline"));
3437 browserWindow.indentButton.setVisible(Global.isEditorButtonVisible("indent"));
3438 browserWindow.outdentButton.setVisible(Global.isEditorButtonVisible("outdent"));
3439 browserWindow.bulletListButton.setVisible(Global.isEditorButtonVisible("bulletList"));
3440 browserWindow.numberListButton.setVisible(Global.isEditorButtonVisible("numberList"));
3441 browserWindow.fontList.setVisible(Global.isEditorButtonVisible("font"));
3442 browserWindow.fontSize.setVisible(Global.isEditorButtonVisible("fontSize"));
3443 browserWindow.fontColor.setVisible(Global.isEditorButtonVisible("fontColor"));
3444 browserWindow.fontHilight.setVisible(Global.isEditorButtonVisible("fontHilight"));
3445 browserWindow.leftAlignButton.setVisible(Global.isEditorButtonVisible("alignLeft"));
3446 browserWindow.centerAlignButton.setVisible(Global.isEditorButtonVisible("alignCenter"));
3447 browserWindow.rightAlignButton.setVisible(Global.isEditorButtonVisible("alignRight"));
3449 private void duplicateNote(String guid) {
3451 Calendar currentTime = new GregorianCalendar();
3452 Long l = new Long(currentTime.getTimeInMillis());
3453 String newGuid = new String(Long.toString(l));
3455 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
3456 Note newNote = oldNote.deepCopy();
3457 newNote.setGuid(newGuid);
3458 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
3459 oldNote.setResources(resList);
3460 duplicateNote(oldNote);
3462 private void duplicateNote(Note oldNote) {
3464 // Now that we have a good notebook guid, we need to move the conflicting note
3465 // to the local notebook
3466 Calendar currentTime = new GregorianCalendar();
3467 Long l = new Long(currentTime.getTimeInMillis());
3468 String newGuid = new String(Long.toString(l));
3470 Note newNote = oldNote.deepCopy();
3471 newNote.setUpdateSequenceNum(0);
3472 newNote.setGuid(newGuid);
3473 newNote.setDeleted(0);
3474 newNote.setActive(true);
3475 List<Resource> resList = oldNote.getResources();
3476 if (resList == null)
3477 resList = new ArrayList<Resource>();
3479 for (int i=0; i<resList.size(); i++) {
3481 while (l == prevGuid) {
3482 currentTime = new GregorianCalendar();
3483 l = new Long(currentTime.getTimeInMillis());
3486 String newResGuid = new String(Long.toString(l));
3487 resList.get(i).setNoteGuid(newGuid);
3488 resList.get(i).setGuid(newResGuid);
3489 resList.get(i).setUpdateSequenceNum(0);
3490 resList.get(i).setActive(true);
3491 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
3493 newNote.setResources(resList);
3494 listManager.addNote(newNote);
3495 conn.getNoteTable().addNote(newNote, true);
3496 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
3497 noteTableView.insertRow(listManager, newNote, true, -1);
3498 listManager.countNotebookResults(listManager.getNoteIndex());
3502 @SuppressWarnings("unused")
3503 private void mergeNotes() {
3504 logger.log(logger.HIGH, "Merging notes");
3507 String masterGuid = null;
3508 List<String> sources = new ArrayList<String>();
3510 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
3511 int r = noteTableView.selectionModel().selectedRows().get(i).row();
3512 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
3513 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3515 masterGuid = (String)ix.values().toArray()[0];
3517 sources.add((String)ix.values().toArray()[0]);
3520 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
3521 logger.log(logger.EXTREME, "Children count: "+sources.size());
3522 mergeNoteContents(masterGuid, sources);
3523 currentNoteGuid = masterGuid;
3524 noteIndexUpdated(false);
3525 refreshEvernoteNote(true);
3528 private void mergeNoteContents(String targetGuid, List<String> sources) {
3529 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
3530 String newContent = target.getContent();
3531 newContent = newContent.replace("</en-note>", "<br></br>");
3533 for (int i=0; i<sources.size(); i++) {
3534 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
3535 if (source.isSetTitle()) {
3536 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
3538 String sourceContent = source.getContent();
3539 logger.log(logger.EXTREME, "Merging contents into note");
3540 logger.log(logger.EXTREME, sourceContent);
3541 logger.log(logger.EXTREME, "End of content");
3542 int startOfNote = sourceContent.indexOf("<en-note>");
3543 sourceContent = sourceContent.substring(startOfNote+9);
3544 int endOfNote = sourceContent.indexOf("</en-note>");
3545 sourceContent = sourceContent.substring(0,endOfNote);
3546 newContent = newContent + sourceContent;
3547 logger.log(logger.EXTREME, "New note content");
3548 logger.log(logger.EXTREME, newContent);
3549 logger.log(logger.EXTREME, "End of content");
3550 for (int j=0; j<source.getResourcesSize(); j++) {
3551 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
3552 Resource r = source.getResources().get(j);
3553 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3555 Calendar currentTime = new GregorianCalendar();
3556 Long l = new Long(currentTime.getTimeInMillis());
3560 while (l == prevGuid) {
3561 currentTime = new GregorianCalendar();
3562 l = new Long(currentTime.getTimeInMillis());
3564 String newResGuid = new String(Long.toString(l));
3565 newRes.setNoteGuid(targetGuid);
3566 newRes.setGuid(newResGuid);
3567 newRes.setUpdateSequenceNum(0);
3568 newRes.setActive(true);
3569 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
3572 logger.log(logger.EXTREME, "Updating note");
3573 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
3574 for (int i=0; i<sources.size(); i++) {
3575 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
3576 listManager.deleteNote(sources.get(i));
3578 logger.log(logger.EXTREME, "Exiting merge note");
3580 // A resource within a note has had a guid change
3581 @SuppressWarnings("unused")
3582 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
3583 if (!oldGuid.equals(newGuid))
3584 Global.resourceMap.put(oldGuid, newGuid);
3586 // View a thumbnail of the note
3587 public void thumbnailView() {
3589 String thumbnailName = Global.currentDir+"res/thumbnail-"+currentNoteGuid+".png";
3590 QFile thumbnail = new QFile(thumbnailName);
3591 if (!thumbnail.exists()) {
3593 QImage img = new QImage();
3594 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
3595 thumbnailViewer.setThumbnail(img);
3597 thumbnailViewer.setThumbnail(thumbnailName);
3598 if (!thumbnailViewer.isVisible())
3599 thumbnailViewer.showFullScreen();
3602 //**********************************************************
3603 //**********************************************************
3604 //* Online user actions
3605 //**********************************************************
3606 //**********************************************************
3607 private void setupOnlineMenu() {
3608 if (!Global.isConnected) {
3609 menuBar.noteOnlineHistoryAction.setEnabled(false);
3612 menuBar.noteOnlineHistoryAction.setEnabled(true);
3615 @SuppressWarnings("unused")
3616 private void viewNoteHistory() {
3617 if (currentNoteGuid == null || currentNoteGuid.equals(""))
3619 if (currentNote.getUpdateSequenceNum() == 0) {
3620 setMessage("Note has never been synchronized.");
3621 QMessageBox.information(this, "Error", "This note has never been sent to Evernote, so there is no history.");
3625 setMessage("Getting Note History");
3627 Note currentOnlineNote = null;
3630 if (Global.isPremium())
3631 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
3633 versions = new ArrayList<NoteVersionId>();
3634 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
3635 } catch (EDAMUserException e) {
3636 setMessage("EDAMUserException: " +e.getMessage());
3638 } catch (EDAMSystemException e) {
3639 setMessage("EDAMSystemException: " +e.getMessage());
3641 } catch (EDAMNotFoundException e) {
3642 setMessage("Note not found on server.");
3643 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
3645 } catch (TException e) {
3646 setMessage("EDAMTransactionException: " +e.getMessage());
3650 // If we've gotten this far, we have a good note.
3651 if (historyWindow == null) {
3652 historyWindow = new OnlineNoteHistory(conn);
3653 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
3654 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
3655 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
3657 historyWindow.historyCombo.clear();
3659 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
3660 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
3662 historyWindow.setCurrent(isDirty);
3664 loadHistoryWindowContent(currentOnlineNote);
3665 historyWindow.load(versions);
3666 setMessage("History retrieved");
3668 historyWindow.exec();
3670 private Note reloadHistoryWindow(String selection) {
3672 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
3673 String dateTimeFormat = new String(fmt);
3674 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
3678 for (int i=0; i<versions.size(); i++) {
3679 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getServiceUpdated()));
3680 if (versionDate.toString().equals(selection))
3684 if (index > -1 || selection.indexOf("Current") > -1) {
3685 Note historyNote = null;
3688 usn = versions.get(index).getUpdateSequenceNum();
3689 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
3691 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
3692 } catch (EDAMUserException e) {
3693 setMessage("EDAMUserException: " +e.getMessage());
3696 } catch (EDAMSystemException e) {
3697 setMessage("EDAMSystemException: " +e.getMessage());
3700 } catch (EDAMNotFoundException e) {
3701 setMessage("EDAMNotFoundException: " +e.getMessage());
3704 } catch (TException e) {
3705 setMessage("EDAMTransactionException: " +e.getMessage());
3711 if (historyNote != null)
3712 historyWindow.setContent(historyNote);
3718 private void loadHistoryWindowContent(Note note) {
3719 note.setUpdateSequenceNum(0);
3720 historyWindow.setContent(note);
3722 @SuppressWarnings("unused")
3723 private void restoreHistoryNoteAsNew() {
3724 setMessage("Restoring as new note.");
3725 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
3726 setMessage("Note has been restored as a new note.");
3728 @SuppressWarnings("unused")
3729 private void restoreHistoryNote() {
3730 setMessage("Restoring note.");
3731 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
3732 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
3735 for (int i=0; i<n.getResourcesSize(); i++) {
3736 n.getResources().get(i).setActive(true);
3737 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
3739 listManager.addNote(n);
3740 conn.getNoteTable().addNote(n, true);
3741 refreshEvernoteNote(true);
3742 setMessage("Note has been restored.");
3747 //**********************************************************
3748 //**********************************************************
3749 //* XML Modifying methods
3750 //**********************************************************
3751 //**********************************************************
3752 // find the appropriate icon for an attachment
3753 private String findIcon(String appl) {
3754 logger.log(logger.HIGH, "Entering NeverNote.findIcon");
3755 appl = appl.toLowerCase();
3756 File f = new File(Global.getDirectoryPath()+"images"+File.separator +appl +".png");
3759 logger.log(logger.HIGH, "Leaving NeverNote.findIcon");
3760 return "attachment.png";
3762 // Modify the en-media tag into an attachment
3763 private void modifyApplicationTags(QDomDocument doc, QDomElement docElem, QDomElement enmedia, QDomAttr hash, String appl) {
3764 logger.log(logger.HIGH, "Entering NeverNote.modifyApplicationTags");
3765 if (appl.equalsIgnoreCase("vnd.evernote.ink"))
3767 String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNote.getGuid(), hash.value());
3768 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid, false);
3769 if (r == null || r.getData() == null)
3770 resourceErrorMessage();
3772 if (r.getData()!=null) {
3773 // Did we get a generic applicaiton? Then look at the file name to
3774 // try and find a good application type for the icon
3775 if (appl.equalsIgnoreCase("octet-stream")) {
3776 if (r.getAttributes() != null && r.getAttributes().getFileName() != null) {
3777 String fn = r.getAttributes().getFileName();
3778 int pos = fn.lastIndexOf(".");
3780 appl = fn.substring(pos+1);
3785 String fileDetails = null;
3786 if (r.getAttributes() != null && r.getAttributes().getFileName() != null && !r.getAttributes().getFileName().equals(""))
3787 fileDetails = r.getAttributes().getFileName();
3788 String contextFileName;
3789 String pathPrefix = Global.currentDir;
3790 pathPrefix = Global.getDirectoryPath()+"res/";
3791 if (fileDetails != null && !fileDetails.equals("")) {
3792 enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +fileDetails);
3793 contextFileName = Global.currentDir +"res/" +r.getGuid() +Global.attachmentNameDelimeter +fileDetails;
3795 enmedia.setAttribute("href", "nnres://" +r.getGuid() +Global.attachmentNameDelimeter +appl);
3796 contextFileName = pathPrefix+r.getGuid() +Global.attachmentNameDelimeter +appl;
3798 contextFileName = contextFileName.replace("\\", "/");
3799 enmedia.setAttribute("onContextMenu", "window.jambi.resourceContextMenu('" +contextFileName +"');");
3800 if (fileDetails == null || fileDetails.equals(""))
3802 enmedia.setAttribute("en-tag", "en-media");
3803 enmedia.setAttribute("guid", r.getGuid());
3804 enmedia.setTagName("a");
3805 QDomElement newText = doc.createElement("img");
3806 boolean goodPreview = false;
3807 String filePath = "";
3808 if (appl.equalsIgnoreCase("pdf") && Global.pdfPreview()) {
3810 Resource res = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
3811 if (res.getAttributes() != null &&
3812 res.getAttributes().getFileName() != null &&
3813 !res.getAttributes().getFileName().trim().equals(""))
3814 fileName = res.getGuid()+Global.attachmentNameDelimeter+res.getAttributes().getFileName();
3816 fileName = res.getGuid()+".pdf";
3817 QFile file = new QFile(Global.getDirectoryPath() +"res/"+fileName);
3818 QFile.OpenMode mode = new QFile.OpenMode();
3819 mode.set(QFile.OpenModeFlag.WriteOnly);
3821 QDataStream out = new QDataStream(file);
3822 Resource resBinary = conn.getNoteTable().noteResourceTable.getNoteResource(res.getGuid(), true);
3823 QByteArray binData = new QByteArray(resBinary.getData().getBody());
3825 out.writeBytes(binData.toByteArray());
3827 PDFPreview pdfPreview = new PDFPreview();
3828 goodPreview = pdfPreview.setupPreview(file.fileName(), appl,0);
3830 QDomElement span = doc.createElement("span");
3831 QDomElement table = doc.createElement("table");
3832 span.setAttribute("pdfNavigationTable", "true");
3833 QDomElement tr = doc.createElement("tr");
3834 QDomElement td = doc.createElement("td");
3835 QDomElement left = doc.createElement("img");
3836 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3837 left.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3838 left.setAttribute("onMouseOver", "style.cursor='hand'");
3839 QDomElement right = doc.createElement("img");
3840 right.setAttribute("onMouseDown", "window.jambi.nextPage('" +file.fileName() +"')");
3841 left.setAttribute("onMouseDown", "window.jambi.previousPage('" +file.fileName() +"')");
3842 left.setAttribute("src", Global.currentDir+"images/small_left.png");
3843 right.setAttribute("src", Global.currentDir+"images/small_right.png");
3844 right.setAttribute("onMouseOver", "style.cursor='hand'");
3846 table.appendChild(tr);
3848 td.appendChild(left);
3849 td.appendChild(right);
3850 span.appendChild(table);
3851 enmedia.parentNode().insertBefore(span, enmedia);
3853 filePath = fileName+".png";
3855 String icon = findIcon(appl);
3856 if (icon.equals("attachment.png"))
3857 icon = findIcon(fileDetails.substring(fileDetails.indexOf(".")+1));
3858 newText.setAttribute("src", Global.getDirectoryPath()+"images"+File.separator +icon);
3860 newText.setAttribute("src", Global.getDirectoryPath()+"res/"+filePath);
3861 newText.setAttribute("style", "border-style:solid; border-color:green; padding:0.5mm 0.5mm 0.5mm 0.5mm;");
3863 newText.setAttribute("title", fileDetails);
3864 enmedia.removeChild(enmedia.firstChild());
3866 enmedia.appendChild(newText);
3869 logger.log(logger.HIGH, "Leaving NeverNote.modifyApplicationTags");
3871 // Modify the en-to tag into an input field
3872 private void modifyTodoTags(QDomElement todo) {
3873 logger.log(logger.HIGH, "Entering NeverNote.modifyTodoTags");
3874 todo.setAttribute("type", "checkbox");
3875 String checked = todo.attribute("checked");
3876 todo.removeAttribute("checked");
3877 if (checked.equalsIgnoreCase("true"))
3878 todo.setAttribute("checked", "");
3880 todo.setAttribute("unchecked","");
3881 todo.setAttribute("value", checked);
3882 todo.setAttribute("onClick", "value=checked;window.jambi.contentChanged(); ");
3883 todo.setTagName("input");
3884 logger.log(logger.HIGH, "Leaving NeverNote.modifyTodoTags");
3886 // Modify any cached todo tags that may have changed
3887 private String modifyCachedTodoTags(String note) {
3888 logger.log(logger.HIGH, "Entering NeverNote.modifyCachedTodoTags");
3889 StringBuffer html = new StringBuffer(note);
3890 for (int i=html.indexOf("<input", 0); i>-1; i=html.indexOf("<input", i)) {
3891 int endPos =html.indexOf(">",i+1);
3892 String input = html.substring(i,endPos);
3893 if (input.indexOf("value=\"true\"") > 0)
3894 input = input.replace("unchecked=\"\"", "checked=\"\"");
3896 input = input.replace("checked=\"\"", "unchecked=\"\"");
3897 html.replace(i, endPos, input);
3900 logger.log(logger.HIGH, "Leaving NeverNote.modifyCachedTodoTags");
3901 return html.toString();
3903 // Modify the en-media tag into an image tag so it can be displayed.
3904 private void modifyImageTags(QDomElement docElem, QDomElement enmedia, QDomAttr hash) {
3905 logger.log(logger.HIGH, "Entering NeverNote.modifyImageTags");
3906 String type = enmedia.attribute("type");
3907 if (type.startsWith("image/"))
3908 type = "."+type.substring(6);
3912 String resGuid = conn.getNoteTable().noteResourceTable.getNoteResourceGuidByHashHex(currentNoteGuid, hash.value());
3913 QFile tfile = new QFile(Global.getDirectoryPath()+"res"+File.separator +resGuid+type);
3914 if (!tfile.exists()) {
3916 if (resGuid != null)
3917 r = conn.getNoteTable().noteResourceTable.getNoteResource(resGuid,true);
3918 if (r==null || r.getData() == null || r.getData().getBody().length == 0)
3919 resourceErrorMessage();
3920 if (r!= null && r.getData() != null && r.getData().getBody().length > 0) {
3921 tfile.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.WriteOnly));
3922 QByteArray binData = new QByteArray(r.getData().getBody());
3923 tfile.write(binData);
3925 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3926 enmedia.setAttribute("en-tag", "en-media");
3927 enmedia.setNodeValue("");
3928 enmedia.setAttribute("guid", r.getGuid());
3929 enmedia.setTagName("img");
3932 enmedia.setAttribute("src", QUrl.fromLocalFile(tfile.fileName()).toString());
3933 enmedia.setAttribute("en-tag", "en-media");
3934 enmedia.setAttribute("onContextMenu", "window.jambi.imageContextMenu('" +tfile.fileName() +"');");
3935 enmedia.setNodeValue("");
3936 enmedia.setAttribute("guid", resGuid);
3937 enmedia.setTagName("img");
3939 logger.log(logger.HIGH, "Leaving NeverNote.modifyImageTags");
3941 // Modify tags from Evernote specific things to XHTML tags.
3942 private QDomDocument modifyTags(QDomDocument doc) {
3943 logger.log(logger.HIGH, "Entering NeverNote.modifyTags");
3944 if (tempFiles == null)
3945 tempFiles = new ArrayList<QTemporaryFile>();
3947 QDomElement docElem = doc.documentElement();
3949 // Modify en-media tags
3950 QDomNodeList anchors = docElem.elementsByTagName("en-media");
3951 int enMediaCount = anchors.length();
3952 for (int i=enMediaCount-1; i>=0; i--) {
3953 QDomElement enmedia = anchors.at(i).toElement();
3954 if (enmedia.hasAttribute("type")) {
3955 QDomAttr attr = enmedia.attributeNode("type");
3956 QDomAttr hash = enmedia.attributeNode("hash");
3957 String[] type = attr.nodeValue().split("/");
3958 String appl = type[1];
3960 if (type[0] != null) {
3961 if (type[0].equals("image")) {
3962 modifyImageTags(docElem, enmedia, hash);
3964 if (!type[0].equals("image")) {
3965 modifyApplicationTags(doc, docElem, enmedia, hash, appl);
3972 anchors = docElem.elementsByTagName("en-todo");
3973 int enTodoCount = anchors.length();
3974 for (int i=enTodoCount-1; i>=0; i--) {
3975 QDomElement enmedia = anchors.at(i).toElement();
3976 modifyTodoTags(enmedia);
3979 // Modify en-crypt tags
3980 anchors = docElem.elementsByTagName("en-crypt");
3981 int enCryptLen = anchors.length();
3982 for (int i=enCryptLen-1; i>=0; i--) {
3983 QDomElement enmedia = anchors.at(i).toElement();
3984 enmedia.setAttribute("contentEditable","false");
3985 enmedia.setAttribute("src", Global.getDirectoryPath()+"images/encrypt.png");
3986 enmedia.setAttribute("en-tag","en-crypt");
3987 enmedia.setAttribute("alt", enmedia.text());
3988 Global.cryptCounter++;
3989 enmedia.setAttribute("id", "crypt"+Global.cryptCounter.toString());
3990 String encryptedText = enmedia.text();
3992 // If the encryption string contains crlf at the end, remove them because they mess up the javascript.
3993 if (encryptedText.endsWith("\n"))
3994 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
3995 if (encryptedText.endsWith("\r"))
3996 encryptedText = encryptedText.substring(0,encryptedText.length()-1);
3999 String hint = enmedia.attribute("hint");
4000 hint = hint.replace("'","'");
4001 enmedia.setAttribute("onClick", "window.jambi.decryptText('crypt"+Global.cryptCounter.toString()+"', '"+encryptedText+"', '"+hint+"');");
4002 enmedia.setAttribute("onMouseOver", "style.cursor='hand'");
4003 enmedia.setTagName("img");
4004 enmedia.removeChild(enmedia.firstChild()); // Remove the actual encrypted text
4007 logger.log(logger.HIGH, "Leaving NeverNote.modifyTags");
4010 // Rebuild the note HTML to something usable
4011 private String rebuildNoteHTML(String noteGuid, String note) {
4012 logger.log(logger.HIGH, "Entering NeverNote.rebuildNoteHTML");
4013 logger.log(logger.EXTREME, "Note guid: " +noteGuid);
4014 logger.log(logger.EXTREME, "Note Text:" +note);
4015 QDomDocument doc = new QDomDocument();
4016 QDomDocument.Result result = doc.setContent(note);
4017 if (!result.success) {
4018 logger.log(logger.MEDIUM, tr("Parse error when rebuilding HTML"));
4019 logger.log(logger.MEDIUM, tr("Note guid: " +noteGuid));
4020 logger.log(logger.EXTREME, tr("Start of unmodified note HTML"));
4021 logger.log(logger.EXTREME, note);
4022 logger.log(logger.EXTREME, tr("End of unmodified note HTML"));
4026 if (tempFiles == null)
4027 tempFiles = new ArrayList<QTemporaryFile>();
4030 doc = modifyTags(doc);
4031 doc = addHilight(doc);
4032 QDomElement docElem = doc.documentElement();
4033 docElem.setTagName("Body");
4034 // docElem.setAttribute("bgcolor", "green");
4035 logger.log(logger.EXTREME, "Rebuilt HTML:");
4036 logger.log(logger.EXTREME, doc.toString());
4037 logger.log(logger.HIGH, "Leaving NeverNote.rebuildNoteHTML");
4038 // Fix the stupid problem where inserting an <img> tag after an <a> tag (which is done
4039 // to get the <en-media> application tag to work properly) causes spaces to be inserted
4040 // between the <a> & <img>. This messes things up later. This is an ugly hack.
4041 StringBuffer html = new StringBuffer(doc.toString());
4042 for (int i=html.indexOf("<a en-tag=\"en-media\" ", 0); i>-1; i=html.indexOf("<a en-tag=\"en-media\" ", i)) {
4043 i=html.indexOf(">\n",i+1);
4044 int z = html.indexOf("<img",i);
4045 for (int j=z-1; j>i; j--)
4046 html.deleteCharAt(j);
4047 i=html.indexOf("/>", z+1);
4048 z = html.indexOf("</a>",i);
4049 for (int j=z-1; j>i+1; j--)
4050 html.deleteCharAt(j);
4052 return html.toString();
4054 // Scan and do hilighting of words
4055 private QDomDocument addHilight(QDomDocument doc) {
4056 EnSearch e = listManager.getEnSearch();
4057 if (e.hilightWords == null || e.hilightWords.size() == 0)
4059 XMLInsertHilight hilight = new XMLInsertHilight(doc, listManager.getEnSearch().hilightWords);
4060 return hilight.getDoc();
4063 // An error has happended fetching a resource. let the user know
4064 private void resourceErrorMessage() {
4067 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4068 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4069 "In a perfect world this wouldn't happen, but it has.\n" +
4070 "It is embarasing when a program like me, designed to save all your\n"+
4071 "precious data, has a problem finding data.\n\n" +
4072 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
4073 "In the mean time, I'm not going to let you make changes to this note.\n" +
4074 "Don't get angry. I'm doing it to prevent you from messing up\n"+
4075 "this note on the Evernote servers. Sorry."+
4076 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4078 //// browserWindow.setEnabled(false);
4079 browserWindow.setReadOnly(true);
4085 //**********************************************************
4086 //**********************************************************
4088 //**********************************************************
4089 //**********************************************************
4090 // We should now do a sync with Evernote
4091 private void syncTimer() {
4092 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
4093 syncRunner.syncNeeded = true;
4094 syncRunner.disableUploads = Global.disableUploads;
4096 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
4098 private void syncStart() {
4099 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
4101 if (!syncRunning && Global.isConnected) {
4102 syncRunner.setConnected(true);
4103 syncRunner.setKeepRunning(Global.keepRunning);
4104 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
4106 if (syncThreadsReady > 0) {
4107 saveNoteIndexWidth();
4108 if (syncRunner.addWork("SYNC")) {
4110 syncRunner.syncNeeded = true;
4115 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
4117 @SuppressWarnings("unused")
4118 private void syncThreadComplete(Boolean refreshNeeded) {
4119 setMessage("Finalizing Synchronization");
4121 syncRunning = false;
4122 syncRunner.syncNeeded = false;
4123 synchronizeAnimationTimer.stop();
4124 noteIndexUpdated(true);
4125 synchronizeButton.setIcon(synchronizeAnimation.get(0));
4127 // noteTableView.selectionModel().selectionChanged.disconnect(this, "noteTableSelection()");
4128 noteTableView.selectionModel().blockSignals(true);
4129 scrollToGuid(currentNoteGuid);
4130 noteTableView.selectionModel().blockSignals(false);
4131 // noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
4132 // indexRunner.setKeepRunning(Global.keepRunning);
4134 // Reload the unindexed table If the dbthread is dead, we are probably shutting down.
4135 if (!dbThread.isAlive())
4137 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
4138 for (int i=0; i<noteTableView.model.rowCount(); i++) {
4139 QModelIndex modelIndex = noteTableView.model.index(i, Global.noteTableGuidPosition);
4140 if (modelIndex != null) {
4141 SortedMap<Integer, Object> ix = noteTableView.model.itemData(modelIndex);
4142 String tableGuid = (String)ix.values().toArray()[0];
4143 String synch = "true";
4144 for (int j=0; j<listManager.getUnsynchronizedNotes().size(); j++) {
4145 if (listManager.getUnsynchronizedNotes().get(j).equalsIgnoreCase(tableGuid)) {
4147 j = listManager.getUnsynchronizedNotes().size();
4150 noteTableView.model.setData(i, Global.noteTableSynchronizedPosition, synch);
4153 refreshEvernoteNote(false);
4154 scrollToGuid(currentNoteGuid);
4155 setMessage("Synchronization Complete");
4156 logger.log(logger.MEDIUM, "Sync complete.");
4158 // public void setSequenceDate(long t) {
4159 // Global.setSequenceDate(t);
4161 public void saveUploadAmount(long t) {
4162 Global.saveUploadAmount(t);
4164 // public void setUpdateSequenceNumber(int t) {
4165 // Global.setUpdateSequenceNumber(t);
4167 public void saveUserInformation(User user) {
4168 Global.saveUserInformation(user);
4170 public void saveEvernoteUpdateCount(int i) {
4171 Global.saveEvernoteUpdateCount(i);
4173 public void refreshLists() {
4174 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
4176 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
4177 tagIndexUpdated(true);
4178 notebookIndexUpdated();
4179 savedSearchIndexUpdated();
4180 listManager.loadNotesIndex();
4182 noteTableView.selectionModel().blockSignals(true);
4183 noteIndexUpdated(true);
4184 noteTableView.selectionModel().blockSignals(false);
4185 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
4189 @SuppressWarnings("unused")
4190 private void authTimer() {
4191 Calendar cal = Calendar.getInstance();
4193 // If we are not connected let's get out of here
4194 if (!Global.isConnected)
4197 // If this is the first time through, then we need to set this
4198 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
4199 // syncRunner.authRefreshTime = cal.getTimeInMillis();
4201 // long now = new Date().getTime();
4202 // if (now > Global.authRefreshTime && Global.isConnected) {
4203 syncRunner.authRefreshNeeded = true;
4207 @SuppressWarnings("unused")
4208 private void authRefreshComplete(boolean goodSync) {
4209 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
4210 Global.isConnected = syncRunner.isConnected;
4212 // authTimer.start((int)syncRunner.authTimeRemaining/4);
4213 authTimer.start(1000*60*15);
4214 logger.log(logger.LOW, "Authentication token has been renewed");
4215 // setMessage("Authentication token has been renewed.");
4217 authTimer.start(1000*60*5);
4218 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
4219 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
4221 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
4225 @SuppressWarnings("unused")
4226 private synchronized void indexTimer() {
4227 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
4230 // Look for any unindexed notes. We only refresh occasionally
4231 // and do one at a time to keep overhead down.
4232 if (!indexDisabled && indexRunner.getWorkQueueSize() == 0) {
4233 List<String> notes = conn.getNoteTable().getNextUnindexed(1);
4234 String unindexedNote = null;
4235 if (notes.size() > 0)
4236 unindexedNote = notes.get(0);
4237 if (unindexedNote != null && Global.keepRunning) {
4238 indexNoteContent(unindexedNote);
4240 if (notes.size()>0) {
4241 indexTimer.setInterval(100);
4244 List<String> unindexedResources = conn.getNoteTable().noteResourceTable.getNextUnindexed(1);
4245 if (unindexedResources.size() > 0 && indexRunner.getWorkQueueSize() == 0) {
4246 String unindexedResource = unindexedResources.get(0);
4247 if (unindexedResource != null && Global.keepRunning) {
4248 indexNoteResource(unindexedResource);
4251 if (unindexedResources.size() > 0) {
4252 indexTimer.setInterval(100);
4255 indexTimer.setInterval(indexTime);
4258 setMessage("Index completed.");
4259 logger.log(logger.LOW, "Indexing has completed.");
4260 indexRunning = false;
4261 indexTimer.setInterval(indexTime);
4264 logger.log(logger.EXTREME, "Leaving neverNote index timer");
4266 private synchronized void indexNoteContent(String unindexedNote) {
4267 logger.log(logger.EXTREME, "Entering NeverNote.indexNoteContent()");
4268 logger.log(logger.MEDIUM, "Unindexed Note found: "+unindexedNote);
4269 indexRunner.setIndexType(indexRunner.CONTENT);
4270 indexRunner.addWork("CONTENT "+unindexedNote);
4271 if (!indexRunning) {
4272 setMessage("Indexing notes.");
4273 logger.log(logger.LOW, "Beginning to index note contents.");
4274 indexRunning = true;
4276 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteContent()");
4278 private synchronized void indexNoteResource(String unindexedResource) {
4279 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4280 indexRunner.addWork(new String("RESOURCE "+unindexedResource));
4281 if (!indexRunning) {
4282 setMessage("Indexing notes.");
4283 indexRunning = true;
4285 logger.log(logger.EXTREME, "Leaving NeverNote.indexNoteResource()");
4287 @SuppressWarnings("unused")
4288 private void indexThreadComplete(String guid) {
4289 logger.log(logger.MEDIUM, "Index complete for "+guid);
4291 @SuppressWarnings("unused")
4292 private synchronized void toggleNoteIndexing() {
4293 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
4294 indexDisabled = !indexDisabled;
4296 setMessage("Indexing is now enabled.");
4298 setMessage("Indexing is now disabled.");
4299 menuBar.disableIndexing.setChecked(indexDisabled);
4300 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
4303 @SuppressWarnings("unused")
4304 private void threadMonitorCheck() {
4309 alive = listManager.threadCheck(Global.tagCounterThreadId);
4312 if (tagDeadCount > MAX)
4313 QMessageBox.information(this, "A thread his died.", "It appears as the tag counter thread has died. I recommend "+
4314 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry.");
4318 alive = listManager.threadCheck(Global.notebookCounterThreadId);
4320 notebookThreadDeadCount++;
4321 QMessageBox.information(this, "A thread his died.", "It appears as the notebook counter thread has died. I recommend "+
4322 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry.");
4324 notebookThreadDeadCount=0;
4326 alive = listManager.threadCheck(Global.trashCounterThreadId);
4329 QMessageBox.information(this, "A thread his died.", "It appears as the trash counter thread has died. I recommend "+
4330 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry.");
4334 alive = listManager.threadCheck(Global.saveThreadId);
4336 saveThreadDeadCount++;
4337 QMessageBox.information(this, "A thread his died.", "It appears as the note saver thread has died. I recommend "+
4338 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry.");
4340 saveThreadDeadCount=0;
4342 if (!dbThread.isAlive()) {
4343 dbThreadDeadCount++;
4344 QMessageBox.information(this, "A thread his died.", "It appears as the database thread has died. I recommend "+
4345 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry.");
4347 dbThreadDeadCount=0;
4349 if (!syncThread.isAlive()) {
4350 syncThreadDeadCount++;
4351 QMessageBox.information(this, "A thread his died.", "It appears as the synchronization thread has died. I recommend "+
4352 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry.");
4354 syncThreadDeadCount=0;
4356 if (!indexThread.isAlive()) {
4357 indexThreadDeadCount++;
4358 QMessageBox.information(this, "A thread his died.", "It appears as the index thread has died. I recommend "+
4359 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry.");
4361 indexThreadDeadCount=0;
4368 //**************************************************
4369 //* Backup & Restore
4370 //**************************************************
4371 @SuppressWarnings("unused")
4372 private void databaseBackup() {
4373 QFileDialog fd = new QFileDialog(this);
4374 fd.setFileMode(FileMode.AnyFile);
4375 fd.setConfirmOverwrite(true);
4376 fd.setWindowTitle("Backup Database");
4377 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4378 fd.setAcceptMode(AcceptMode.AcceptSave);
4379 fd.setDirectory(System.getProperty("user.home"));
4380 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4386 setMessage("Backing up database");
4388 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
4390 ExportData noteWriter = new ExportData(conn, true);
4391 String fileName = fd.selectedFiles().get(0);
4393 if (!fileName.endsWith(".nnex"))
4394 fileName = fileName +".nnex";
4395 noteWriter.exportData(fileName);
4396 setMessage("Database backup completed.");
4401 @SuppressWarnings("unused")
4402 private void databaseRestore() {
4403 if (QMessageBox.question(this, "Confirmation",
4404 "This is used to restore a database from backups.\n" +
4405 "It is HIGHLY recommened that this only be used to populate\n" +
4406 "an empty database. Restoring into a database that\n already has data" +
4407 " can cause problems.\n\nAre you sure you want to continue?",
4408 QMessageBox.StandardButton.Yes,
4409 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4414 QFileDialog fd = new QFileDialog(this);
4415 fd.setFileMode(FileMode.ExistingFile);
4416 fd.setConfirmOverwrite(true);
4417 fd.setWindowTitle("Restore Database");
4418 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4419 fd.setAcceptMode(AcceptMode.AcceptOpen);
4420 fd.setDirectory(System.getProperty("user.home"));
4421 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4427 setMessage("Restoring database");
4428 ImportData noteReader = new ImportData(conn, true);
4429 noteReader.importData(fd.selectedFiles().get(0));
4431 if (noteReader.lastError != 0) {
4432 setMessage(noteReader.getErrorMessage());
4433 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
4438 listManager.loadNoteTitleColors();
4440 refreshEvernoteNote(true);
4441 setMessage("Database has been restored.");
4444 @SuppressWarnings("unused")
4445 private void exportNotes() {
4446 QFileDialog fd = new QFileDialog(this);
4447 fd.setFileMode(FileMode.AnyFile);
4448 fd.setConfirmOverwrite(true);
4449 fd.setWindowTitle("Backup Database");
4450 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4451 fd.setAcceptMode(AcceptMode.AcceptSave);
4452 fd.setDirectory(System.getProperty("user.home"));
4453 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4459 setMessage("Exporting Notes");
4462 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4463 selectedNoteGUIDs.add(currentNoteGuid);
4465 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
4466 String fileName = fd.selectedFiles().get(0);
4468 if (!fileName.endsWith(".nnex"))
4469 fileName = fileName +".nnex";
4470 noteWriter.exportData(fileName);
4471 setMessage("Export completed.");
4477 @SuppressWarnings("unused")
4478 private void importNotes() {
4479 QFileDialog fd = new QFileDialog(this);
4480 fd.setFileMode(FileMode.ExistingFile);
4481 fd.setConfirmOverwrite(true);
4482 fd.setWindowTitle("Import Notes");
4483 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
4484 fd.setAcceptMode(AcceptMode.AcceptOpen);
4485 fd.setDirectory(System.getProperty("user.home"));
4486 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
4492 setMessage("Importing Notes");
4495 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4496 selectedNoteGUIDs.add(currentNoteGuid);
4498 ImportData noteReader = new ImportData(conn, false);
4499 String fileName = fd.selectedFiles().get(0);
4501 if (!fileName.endsWith(".nnex"))
4502 fileName = fileName +".nnex";
4503 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
4504 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
4506 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
4508 noteReader.importData(fileName);
4510 if (noteReader.lastError != 0) {
4511 setMessage(noteReader.getErrorMessage());
4512 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
4517 listManager.loadNoteTitleColors();
4519 refreshEvernoteNote(false);
4520 setMessage("Notes have been imported.");
4523 setMessage("Import completed.");
4530 //**************************************************
4531 //* Duplicate a note
4532 //**************************************************
4533 @SuppressWarnings("unused")
4534 private void duplicateNote() {
4536 duplicateNote(currentNoteGuid);
4541 //**************************************************
4543 //**************************************************
4544 public void setupFolderImports() {
4545 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
4547 if (importKeepWatcher == null)
4548 importKeepWatcher = new QFileSystemWatcher();
4549 if (importDeleteWatcher == null) {
4550 importDeleteWatcher = new QFileSystemWatcher();
4551 for (int i=0; i<records.size(); i++) {
4552 if (!records.get(i).keep)
4553 folderImportDelete(records.get(i).folder);
4559 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
4560 for (int i=0; i<records.size(); i++) {
4561 if (records.get(i).keep)
4562 importKeepWatcher.addPath(records.get(i).folder);
4564 importDeleteWatcher.addPath(records.get(i).folder);
4567 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
4568 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
4570 // Look at the files already there so we don't import them again if a new file is created
4571 if (importedFiles == null) {
4572 importedFiles = new ArrayList<String>();
4573 for (int j=0; j<records.size(); j++) {
4574 QDir dir = new QDir(records.get(j).folder);
4575 List<QFileInfo> list = dir.entryInfoList();
4576 for (int k=0; k<list.size(); k++) {
4577 if (list.get(k).isFile())
4578 importedFiles.add(list.get(k).absoluteFilePath());
4583 public void folderImport() {
4584 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
4585 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
4587 if (!dialog.okClicked())
4590 // We have some sort of update.
4591 if (importKeepWatcher.directories().size() > 0)
4592 importKeepWatcher.removePaths(importKeepWatcher.directories());
4593 if (importDeleteWatcher.directories().size() > 0)
4594 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
4596 conn.getWatchFolderTable().expungeAll();
4597 // Start building from the table
4598 for (int i=0; i<dialog.table.rowCount(); i++) {
4599 QTableWidgetItem item = dialog.table.item(i, 0);
4600 String dir = item.text();
4601 item = dialog.table.item(i, 1);
4602 String notebook = item.text();
4603 item = dialog.table.item(i, 2);
4605 if (item.text().equalsIgnoreCase("Keep"))
4610 String guid = conn.getNotebookTable().findNotebookByName(notebook);
4611 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
4613 setupFolderImports();
4616 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
4618 String whichOS = System.getProperty("os.name");
4619 if (whichOS.contains("Windows"))
4620 dirName = dirName.replace('/','\\');
4622 FileImporter importer = new FileImporter(logger, conn);
4624 QDir dir = new QDir(dirName);
4625 List<QFileInfo> list = dir.entryInfoList();
4626 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4628 for (int i=0; i<list.size(); i++){
4630 boolean redundant = false;
4631 // Check if we've already imported this one or if it existed before
4632 for (int j=0; j<importedFiles.size(); j++) {
4633 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
4638 importer.setFileInfo(list.get(i));
4639 importer.setFileName(list.get(i).absoluteFilePath());
4642 if (list.get(i).isFile() && importer.isValidType()) {
4644 if (!importer.importFile()) {
4645 // If we can't get to the file, it is probably locked. We'll try again later.
4646 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4647 importFilesKeep.add(list.get(i).absoluteFilePath());
4651 Note newNote = importer.getNote();
4652 newNote.setNotebookGuid(notebook);
4653 newNote.setTitle(dir.at(i));
4654 listManager.addNote(newNote);
4655 conn.getNoteTable().addNote(newNote, true);
4656 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4657 noteTableView.insertRow(listManager, newNote, true, -1);
4658 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4659 listManager.countNotebookResults(listManager.getNoteIndex());
4660 importedFiles.add(list.get(i).absoluteFilePath());
4668 public void folderImportDelete(String dirName) {
4670 String whichOS = System.getProperty("os.name");
4671 if (whichOS.contains("Windows"))
4672 dirName = dirName.replace('/','\\');
4674 FileImporter importer = new FileImporter(logger, conn);
4675 QDir dir = new QDir(dirName);
4676 List<QFileInfo> list = dir.entryInfoList();
4677 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
4679 for (int i=0; i<list.size(); i++){
4680 importer.setFileInfo(list.get(i));
4681 importer.setFileName(list.get(i).absoluteFilePath());
4683 if (list.get(i).isFile() && importer.isValidType()) {
4685 if (!importer.importFile()) {
4686 // If we can't get to the file, it is probably locked. We'll try again later.
4687 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4688 importFilesKeep.add(list.get(i).absoluteFilePath());
4692 Note newNote = importer.getNote();
4693 newNote.setNotebookGuid(notebook);
4694 newNote.setTitle(dir.at(i));
4695 listManager.addNote(newNote);
4696 conn.getNoteTable().addNote(newNote, true);
4697 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4698 noteTableView.insertRow(listManager, newNote, true, -1);
4699 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
4700 listManager.countNotebookResults(listManager.getNoteIndex());
4701 dir.remove(dir.at(i));
4707 //**************************************************
4709 //**************************************************
4710 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
4711 logger.log(logger.HIGH, "Entering exernalFileEdited");
4713 String dPath = Global.getDirectoryPath() + "res/";
4714 dPath = dPath.replace('\\', '/');
4715 String name = fileName.replace(dPath, "");
4716 int pos = name.lastIndexOf('.');
4719 guid = guid.substring(0,pos);
4721 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
4723 guid = name.substring(0, pos);
4726 QFile file = new QFile(fileName);
4727 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
4728 // If we can't get to the file, it is probably locked. We'll try again later.
4729 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4730 externalFiles.add(fileName);
4733 QByteArray binData = file.readAll();
4735 if (binData.size() == 0) {
4736 // If we can't get to the file, it is probably locked. We'll try again later.
4737 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
4738 externalFiles.add(fileName);
4742 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
4744 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
4745 if (r == null || r.getData() == null || r.getData().getBody() == null)
4747 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
4748 MessageDigest md = MessageDigest.getInstance("MD5");
4749 md.update(binData.toByteArray());
4750 byte[] hash = md.digest();
4751 String newHash = Global.byteArrayToHexString(hash);
4752 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
4753 updateResourceContentHash(r.getGuid(), oldHash, newHash);
4755 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
4756 Data data = r.getData();
4757 data.setBody(binData.toByteArray());
4758 data.setBodyHash(hash);
4759 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
4761 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
4763 if (r.getNoteGuid().equals(currentNoteGuid)) {
4764 QWebSettings.setMaximumPagesInCache(0);
4765 QWebSettings.setObjectCacheCapacities(0, 0, 0);
4766 refreshEvernoteNote(true);
4767 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
4770 logger.log(logger.HIGH, "Exiting externalFielEdited");
4772 // This is a timer event that tries to save any external files that were edited. This
4773 // is only needed if we couldn't save a file earlier.
4774 public void externalFileEditedSaver() {
4775 for (int i=externalFiles.size()-1; i>=0; i--) {
4777 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
4778 externalFileEdited(externalFiles.get(i));
4779 externalFiles.remove(i);
4780 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4782 for (int i=0; i<importFilesKeep.size(); i++) {
4784 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
4785 folderImportKeep(importFilesKeep.get(i));
4786 importFilesKeep.remove(i);
4787 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
4789 for (int i=0; i<importFilesDelete.size(); i++) {
4790 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
4791 folderImportDelete(importFilesDelete.get(i));
4792 importFilesDelete.remove(i);
4799 // If an attachment on the current note was edited, we need to update the current notes's hash
4800 // Update a note content's hash. This happens if a resource is edited outside of NN
4801 public void updateResourceContentHash(String guid, String oldHash, String newHash) {
4802 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
4804 for (;position>-1;) {
4805 endPos = browserWindow.getContent().indexOf(">", position+1);
4806 String oldSegment = browserWindow.getContent().substring(position,endPos);
4807 int hashPos = oldSegment.indexOf("hash=\"");
4808 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
4809 String hash = oldSegment.substring(hashPos+6, hashEnd);
4810 if (hash.equalsIgnoreCase(oldHash)) {
4811 String newSegment = oldSegment.replace(oldHash, newHash);
4812 String content = browserWindow.getContent().substring(0,position) +
4814 browserWindow.getContent().substring(endPos);
4815 browserWindow.getBrowser().setContent(new QByteArray(content));;
4818 position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
4825 //*************************************************
4826 //* Check database userid & passwords
4827 //*************************************************
4828 public boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
4829 Connection connection;
4832 Class.forName("org.h2.Driver");
4833 } catch (ClassNotFoundException e1) {
4834 e1.printStackTrace();
4839 String passwordString = null;
4840 if (cypherPassword==null || cypherPassword.trim().equals(""))
4841 passwordString = userPassword;
4843 passwordString = cypherPassword+" "+userPassword;
4844 connection = DriverManager.getConnection(url,userid,passwordString);
4845 } catch (SQLException e) {
4850 } catch (SQLException e) {
4851 e.printStackTrace();