2 * This file is part of NeverNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QModelIndex;
79 import com.trolltech.qt.core.QSize;
80 import com.trolltech.qt.core.QTemporaryFile;
81 import com.trolltech.qt.core.QTextCodec;
82 import com.trolltech.qt.core.QThreadPool;
83 import com.trolltech.qt.core.QTimer;
84 import com.trolltech.qt.core.QTranslator;
85 import com.trolltech.qt.core.QUrl;
86 import com.trolltech.qt.core.Qt;
87 import com.trolltech.qt.core.Qt.BGMode;
88 import com.trolltech.qt.core.Qt.ItemDataRole;
89 import com.trolltech.qt.core.Qt.SortOrder;
90 import com.trolltech.qt.core.Qt.WidgetAttribute;
91 import com.trolltech.qt.gui.QAbstractItemView;
92 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
93 import com.trolltech.qt.gui.QAction;
94 import com.trolltech.qt.gui.QApplication;
95 import com.trolltech.qt.gui.QCloseEvent;
96 import com.trolltech.qt.gui.QColor;
97 import com.trolltech.qt.gui.QComboBox;
98 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
99 import com.trolltech.qt.gui.QCursor;
100 import com.trolltech.qt.gui.QDesktopServices;
101 import com.trolltech.qt.gui.QDialog;
102 import com.trolltech.qt.gui.QFileDialog;
103 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
104 import com.trolltech.qt.gui.QFileDialog.FileMode;
105 import com.trolltech.qt.gui.QGridLayout;
106 import com.trolltech.qt.gui.QHBoxLayout;
107 import com.trolltech.qt.gui.QIcon;
108 import com.trolltech.qt.gui.QImage;
109 import com.trolltech.qt.gui.QLabel;
110 import com.trolltech.qt.gui.QListWidget;
111 import com.trolltech.qt.gui.QMainWindow;
112 import com.trolltech.qt.gui.QMenu;
113 import com.trolltech.qt.gui.QMessageBox;
114 import com.trolltech.qt.gui.QMessageBox.StandardButton;
115 import com.trolltech.qt.gui.QPainter;
116 import com.trolltech.qt.gui.QPalette.ColorRole;
117 import com.trolltech.qt.gui.QPixmap;
118 import com.trolltech.qt.gui.QPrintDialog;
119 import com.trolltech.qt.gui.QPrinter;
120 import com.trolltech.qt.gui.QSizePolicy;
121 import com.trolltech.qt.gui.QSizePolicy.Policy;
122 import com.trolltech.qt.gui.QSpinBox;
123 import com.trolltech.qt.gui.QSplashScreen;
124 import com.trolltech.qt.gui.QSplitter;
125 import com.trolltech.qt.gui.QStatusBar;
126 import com.trolltech.qt.gui.QSystemTrayIcon;
127 import com.trolltech.qt.gui.QTableWidgetItem;
128 import com.trolltech.qt.gui.QTextEdit;
129 import com.trolltech.qt.gui.QToolBar;
130 import com.trolltech.qt.gui.QTreeWidgetItem;
131 import com.trolltech.qt.network.QNetworkAccessManager;
132 import com.trolltech.qt.network.QNetworkReply;
133 import com.trolltech.qt.network.QNetworkRequest;
134 import com.trolltech.qt.webkit.QWebPage.WebAction;
135 import com.trolltech.qt.webkit.QWebSettings;
137 import cx.fbn.nevernote.config.InitializationException;
138 import cx.fbn.nevernote.config.StartupConfig;
139 import cx.fbn.nevernote.dialog.AccountDialog;
140 import cx.fbn.nevernote.dialog.ConfigDialog;
141 import cx.fbn.nevernote.dialog.DBEncryptDialog;
142 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
143 import cx.fbn.nevernote.dialog.DatabaseStatus;
144 import cx.fbn.nevernote.dialog.FindDialog;
145 import cx.fbn.nevernote.dialog.IgnoreSync;
146 import cx.fbn.nevernote.dialog.LoginDialog;
147 import cx.fbn.nevernote.dialog.NotebookArchive;
148 import cx.fbn.nevernote.dialog.NotebookEdit;
149 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
150 import cx.fbn.nevernote.dialog.PublishNotebook;
151 import cx.fbn.nevernote.dialog.SavedSearchEdit;
152 import cx.fbn.nevernote.dialog.SetIcon;
153 import cx.fbn.nevernote.dialog.ShareNotebook;
154 import cx.fbn.nevernote.dialog.StackNotebook;
155 import cx.fbn.nevernote.dialog.TagEdit;
156 import cx.fbn.nevernote.dialog.ThumbnailViewer;
157 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
158 import cx.fbn.nevernote.dialog.WatchFolder;
159 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
160 import cx.fbn.nevernote.filters.FilterEditorTags;
161 import cx.fbn.nevernote.gui.AttributeTreeWidget;
162 import cx.fbn.nevernote.gui.BrowserWindow;
163 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
164 import cx.fbn.nevernote.gui.ExternalBrowse;
165 import cx.fbn.nevernote.gui.MainMenuBar;
166 import cx.fbn.nevernote.gui.NotebookTreeWidget;
167 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
168 import cx.fbn.nevernote.gui.TableView;
169 import cx.fbn.nevernote.gui.TagTreeWidget;
170 import cx.fbn.nevernote.gui.Thumbnailer;
171 import cx.fbn.nevernote.gui.TrashTreeWidget;
172 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
173 import cx.fbn.nevernote.sql.DatabaseConnection;
174 import cx.fbn.nevernote.sql.WatchFolderRecord;
175 import cx.fbn.nevernote.threads.IndexRunner;
176 import cx.fbn.nevernote.threads.SyncRunner;
177 import cx.fbn.nevernote.threads.ThumbnailRunner;
178 import cx.fbn.nevernote.utilities.AESEncrypter;
179 import cx.fbn.nevernote.utilities.ApplicationLogger;
180 import cx.fbn.nevernote.utilities.FileImporter;
181 import cx.fbn.nevernote.utilities.FileUtils;
182 import cx.fbn.nevernote.utilities.ListManager;
183 import cx.fbn.nevernote.utilities.SyncTimes;
184 import cx.fbn.nevernote.xml.ExportData;
185 import cx.fbn.nevernote.xml.ImportData;
186 import cx.fbn.nevernote.xml.NoteFormatter;
189 public class NeverNote extends QMainWindow{
191 QStatusBar statusBar; // Application status bar
193 DatabaseConnection conn;
195 MainMenuBar menuBar; // Main menu bar
196 FindDialog find; // Text search in note dialog
197 List<String> emitLog; // Messages displayed in the status bar;
198 QSystemTrayIcon trayIcon; // little tray icon
199 QMenu trayMenu; // System tray menu
200 QAction trayExitAction; // Exit the application
201 QAction trayShowAction; // toggle the show/hide action
202 QAction trayAddNoteAction; // Add a note from the system tray
203 QNetworkAccessManager versionChecker; // Used when checking for new versions
205 NotebookTreeWidget notebookTree; // List of notebooks
206 AttributeTreeWidget attributeTree; // List of note attributes
207 TagTreeWidget tagTree; // list of user created tags
208 SavedSearchTreeWidget savedSearchTree; // list of saved searches
209 TrashTreeWidget trashTree; // Trashcan
210 TableView noteTableView; // List of notes (the widget).
212 public BrowserWindow browserWindow; // Window containing browser & labels
213 public QToolBar toolBar; // The tool bar under the menu
214 QComboBox searchField; // search filter bar on the toolbar;
215 boolean searchPerformed = false; // Search was done?
216 QuotaProgressBar quotaBar; // The current quota usage
218 ApplicationLogger logger;
219 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
220 List<String> selectedTagGUIDs; // List of selected tag GUIDs
221 List<String> selectedNoteGUIDs; // List of selected notes
222 String selectedSavedSearchGUID; // Currently selected saved searches
223 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
225 NoteFilter filter; // Note filter
226 String currentNoteGuid; // GUID of the current note
227 Note currentNote; // The currently viewed note
228 boolean noteDirty; // Has the note been changed?
229 boolean inkNote; // if this is an ink note, it is read only
230 boolean readOnly; // Is this note read-only?
233 ListManager listManager; // DB runnable task
235 List<QTemporaryFile> tempFiles; // Array of temporary files;
237 QTimer indexTimer; // timer to start the index thread
238 IndexRunner indexRunner; // thread to index notes
241 QTimer syncTimer; // Sync on an interval
242 QTimer syncDelayTimer; // Sync delay to free up database
243 SyncRunner syncRunner; // thread to do a sync.
244 QThread syncThread; // Thread which talks to evernote
245 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
246 QThread thumbnailThread; // Thread that generates pretty pictures
247 QTimer saveTimer; // Timer to save note contents
249 QTimer authTimer; // Refresh authentication
250 QTimer externalFileSaveTimer; // Save files altered externally
251 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
252 List<String> externalFiles; // External files to save later
253 List<String> importFilesKeep; // Auto-import files to save later
254 List<String> importFilesDelete; // Auto-import files to save later
256 int indexTime; // how often to try and index
257 boolean indexRunning; // Is indexing running?
258 boolean indexDisabled; // Is indexing disabled?
260 int syncThreadsReady; // number of sync threads that are free
261 int syncTime; // Sync interval
262 boolean syncRunning; // Is sync running?
263 boolean automaticSync; // do sync automatically?
264 QTreeWidgetItem attributeTreeSelected;
266 QAction prevButton; // Go to the previous item viewed
267 QAction nextButton; // Go to the next item in the history
268 QAction downButton; // Go to the next item in the list
269 QAction upButton; // Go to the prev. item in the list;
270 QAction synchronizeButton; // Synchronize with Evernote
271 QAction allNotesButton; // Reset & view all notes
272 QTimer synchronizeAnimationTimer; // Timer to change animation button
273 int synchronizeIconAngle; // Used to rotate sync icon
274 QAction printButton; // Print Button
275 QAction tagButton; // Tag edit button
276 QAction attributeButton; // Attribute information button
277 QAction emailButton; // Email button
278 QAction deleteButton; // Delete button
279 QAction newButton; // new Note Button;
280 QSpinBox zoomSpinner; // Zoom zoom
281 QAction searchClearButton; // Clear the search field
283 QSplitter mainLeftRightSplitter; // main splitter for left/right side
284 QSplitter leftSplitter1; // first left hand splitter
285 QSplitter browserIndexSplitter; // splitter between note index & note text
287 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
288 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
289 List<String> importedFiles; // History of imported files (so we don't import twice)
291 OnlineNoteHistory historyWindow; // online history window
292 List<NoteVersionId> versions; // history versions
294 QTimer threadMonitorTimer; // Timer to watch threads.
295 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
296 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
297 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
298 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
299 int tagDeadCount=0; // number of consecutive dead times for the tag thread
300 int trashDeadCount=0; // number of consecutive dead times for the trash thread
301 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
303 HashMap<String, String> noteCache; // Cash of note content
304 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
305 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
306 List<String> historyGuids; // GUIDs of previously viewed items
307 int historyPosition; // Position within the viewed items
308 boolean fromHistory; // Is this from the history queue?
309 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
310 List<Thumbnailer> thumbGenerators; // generate preview image
311 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
312 boolean encryptOnShutdown; // should I encrypt when I close?
313 boolean decryptOnShutdown; // should I decrypt on shutdown;
314 String encryptCipher; // What cipher should I use?
315 Signal0 minimizeToTray;
316 boolean windowMaximized = false; // Keep track of the window state for restores
317 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
318 List<QPixmap> syncIcons; // Array of icons used in sync animation
319 private boolean closeAction = false; // Used to say when to close or when to minimize
320 private static Logger log = Logger.getLogger(NeverNote.class);
323 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
326 //***************************************************************
327 //***************************************************************
328 //** Constructor & main entry point
329 //***************************************************************
330 //***************************************************************
331 // Application Constructor
332 @SuppressWarnings("static-access")
333 public NeverNote(DatabaseConnection dbConn) {
335 if (conn.getConnection() == null) {
336 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
337 "is accessing the database or NeverNote is already running.\n\n" +
338 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
340 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
344 thread().setPriority(Thread.MAX_PRIORITY);
346 logger = new ApplicationLogger("nevernote.log");
347 logger.log(logger.HIGH, "Starting Application");
349 decryptOnShutdown = false;
350 encryptOnShutdown = false;
351 conn.checkDatabaseVersion();
355 // Start building the invalid XML tables
356 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
357 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
359 for (int i=0; i<elements.size(); i++) {
360 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
363 logger.log(logger.EXTREME, "Starting GUI build");
365 QTranslator nevernoteTranslator = new QTranslator();
366 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
367 QApplication.instance().installTranslator(nevernoteTranslator);
369 Global.originalPalette = QApplication.palette();
370 QApplication.setStyle(Global.getStyle());
371 if (Global.useStandardPalette())
372 QApplication.setPalette(QApplication.style().standardPalette());
373 setWindowTitle("NeverNote");
375 mainLeftRightSplitter = new QSplitter();
376 setCentralWidget(mainLeftRightSplitter);
377 leftSplitter1 = new QSplitter();
378 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
380 browserIndexSplitter = new QSplitter();
381 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
383 //* Setup threads & thread timers
384 int indexRunnerCount = Global.getIndexThreads();
385 indexRunnerCount = 1;
386 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
388 logger.log(logger.EXTREME, "Building list manager");
389 listManager = new ListManager(conn, logger);
391 logger.log(logger.EXTREME, "Building index runners & timers");
392 indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
393 indexThread = new QThread(indexRunner, "Index Thread");
394 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
397 synchronizeAnimationTimer = new QTimer();
398 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
400 indexTimer = new QTimer();
401 indexTime = 1000*Global.getIndexThreadSleepInterval();
402 indexTimer.start(indexTime); // Start indexing timer
403 indexTimer.timeout.connect(this, "indexTimer()");
404 indexDisabled = false;
405 indexRunning = false;
407 logger.log(logger.EXTREME, "Setting sync thread & timers");
409 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
410 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
411 syncTimer = new QTimer();
412 syncTimer.timeout.connect(this, "syncTimer()");
413 syncRunner.status.message.connect(this, "setMessage(String)");
414 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
415 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
418 automaticSync = true;
419 syncTimer.start(syncTime*60*1000);
421 automaticSync = false;
424 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
425 syncThread = new QThread(syncRunner, "Synchronization Thread");
429 logger.log(logger.EXTREME, "Starting thumnail thread");
430 pdfReadyQueue = new ArrayList<String>();
431 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
432 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
433 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
434 thumbnailThread.start();
435 thumbGenerators = new ArrayList<Thumbnailer>();
436 thumbnailTimer = new QTimer();
437 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
439 thumbnailTimer.setInterval(60*1000); // Thumbnail every minute
440 thumbnailTimer.start();
442 logger.log(logger.EXTREME, "Starting authentication timer");
443 authTimer = new QTimer();
444 authTimer.timeout.connect(this, "authTimer()");
445 authTimer.start(1000*60*15);
446 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
448 logger.log(logger.EXTREME, "Setting save note timer");
449 saveTimer = new QTimer();
450 saveTimer.timeout.connect(this, "saveNote()");
451 if (Global.getAutoSaveInterval() > 0) {
452 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
455 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
457 logger.log(logger.EXTREME, "Starting external file monitor timer");
458 externalFileSaveTimer = new QTimer();
459 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
460 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
461 externalFiles = new ArrayList<String>();
462 importFilesDelete = new ArrayList<String>();
463 importFilesKeep = new ArrayList<String>();
464 externalFileSaveTimer.start();
466 notebookTree = new NotebookTreeWidget(conn);
467 attributeTree = new AttributeTreeWidget();
468 tagTree = new TagTreeWidget(conn);
469 savedSearchTree = new SavedSearchTreeWidget();
470 trashTree = new TrashTreeWidget();
471 noteTableView = new TableView(logger, listManager);
473 QGridLayout leftGrid = new QGridLayout();
474 leftSplitter1.setLayout(leftGrid);
475 leftGrid.addWidget(notebookTree, 1, 1);
476 leftGrid.addWidget(tagTree,2,1);
477 leftGrid.addWidget(attributeTree,3,1);
478 leftGrid.addWidget(savedSearchTree,4,1);
479 leftGrid.addWidget(trashTree, 5, 1);
481 // Setup the browser window
482 noteCache = new HashMap<String,String>();
483 readOnlyCache = new HashMap<String, Boolean>();
484 inkNoteCache = new HashMap<String, Boolean>();
485 browserWindow = new BrowserWindow(conn);
487 mainLeftRightSplitter.addWidget(leftSplitter1);
488 mainLeftRightSplitter.addWidget(browserIndexSplitter);
490 if (Global.getListView() == Global.View_List_Wide) {
491 browserIndexSplitter.addWidget(noteTableView);
492 browserIndexSplitter.addWidget(browserWindow);
494 mainLeftRightSplitter.addWidget(noteTableView);
495 mainLeftRightSplitter.addWidget(browserWindow);
498 searchField = new QComboBox();
499 searchField.setEditable(true);
500 searchField.activatedIndex.connect(this, "searchFieldChanged()");
501 searchField.setDuplicatesEnabled(false);
502 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
504 quotaBar = new QuotaProgressBar();
506 // Setup the thumbnail viewer
507 thumbnailViewer = new ThumbnailViewer();
508 thumbnailViewer.upArrow.connect(this, "upAction()");
509 thumbnailViewer.downArrow.connect(this, "downAction()");
510 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
511 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
513 //Setup external browser manager
514 externalWindows = new HashMap<String, ExternalBrowse>();
516 listManager.loadNotesIndex();
517 initializeNotebookTree();
519 initializeSavedSearchTree();
520 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
521 attributeTreeSelected = null;
522 initializeNoteTable();
524 selectedNoteGUIDs = new ArrayList<String>();
525 statusBar = new QStatusBar();
526 setStatusBar(statusBar);
527 menuBar = new MainMenuBar(this);
528 emitLog = new ArrayList<String>();
530 tagTree.setDeleteAction(menuBar.tagDeleteAction);
531 tagTree.setEditAction(menuBar.tagEditAction);
532 tagTree.setAddAction(menuBar.tagAddAction);
533 tagTree.setIconAction(menuBar.tagIconAction);
534 tagTree.setVisible(Global.isWindowVisible("tagTree"));
535 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
536 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
537 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
539 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
540 notebookTree.setEditAction(menuBar.notebookEditAction);
541 notebookTree.setAddAction(menuBar.notebookAddAction);
542 notebookTree.setIconAction(menuBar.notebookIconAction);
543 notebookTree.setStackAction(menuBar.notebookStackAction);
544 notebookTree.setPublishAction(menuBar.notebookPublishAction);
545 notebookTree.setShareAction(menuBar.notebookShareAction);
546 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
547 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
548 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
549 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
550 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
552 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
553 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
554 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
555 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
556 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
557 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
558 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
560 noteTableView.setAddAction(menuBar.noteAdd);
561 noteTableView.setDeleteAction(menuBar.noteDelete);
562 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
563 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
564 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
565 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
566 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
567 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
568 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
569 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
570 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
572 quotaBar.setMouseClickAction(menuBar.accountAction);
575 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
576 trashTree.setEmptyAction(menuBar.emptyTrashAction);
577 trashTree.setVisible(Global.isWindowVisible("trashTree"));
578 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
579 trashTree.updateCounts(listManager.getTrashCount());
580 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
581 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
583 noteTableView.setVisible(Global.isWindowVisible("noteList"));
584 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
586 if (!Global.isWindowVisible("editorButtonBar"))
587 toggleEditorButtonBar();
588 if (!Global.isWindowVisible("leftPanel"))
589 menuBar.hideLeftSide.setChecked(true);
590 if (Global.isWindowVisible("noteInformation"))
591 toggleNoteInformation();
595 find = new FindDialog();
596 find.getOkButton().clicked.connect(this, "doFindText()");
598 // Setup the tray icon menu bar
599 trayShowAction = new QAction("Show/Hide", this);
600 trayExitAction = new QAction("Exit", this);
601 trayAddNoteAction = new QAction("Add Note", this);
603 trayExitAction.triggered.connect(this, "closeNeverNote()");
604 trayAddNoteAction.triggered.connect(this, "addNote()");
605 trayShowAction.triggered.connect(this, "trayToggleVisible()");
607 trayMenu = new QMenu(this);
608 trayMenu.addAction(trayAddNoteAction);
609 trayMenu.addAction(trayShowAction);
610 trayMenu.addAction(trayExitAction);
613 trayIcon = new QSystemTrayIcon(this);
614 trayIcon.setToolTip("NeverNote");
615 trayIcon.setContextMenu(trayMenu);
616 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
619 currentNoteGuid = Global.getLastViewedNoteGuid();
620 historyGuids = new ArrayList<String>();
624 if (!currentNoteGuid.trim().equals("")) {
625 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
628 noteIndexUpdated(true);
630 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
631 if (menuBar.showEditorBar.isChecked())
632 showEditorButtons(browserWindow);
633 tagIndexUpdated(true);
634 savedSearchIndexUpdated();
635 notebookIndexUpdated();
637 setupSyncSignalListeners();
638 setupBrowserSignalListeners();
639 setupIndexListeners();
642 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
643 tagTree.showAllTags(true);
645 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
646 setWindowIcon(appIcon);
647 trayIcon.setIcon(appIcon);
648 if (Global.showTrayIcon())
653 scrollToGuid(currentNoteGuid);
654 if (Global.automaticLogin()) {
656 if (Global.isConnected)
659 setupFolderImports();
662 restoreWindowState(true);
664 if (Global.mimicEvernoteInterface) {
665 notebookTree.selectGuid("");
668 threadMonitorTimer = new QTimer();
669 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
670 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
672 historyGuids.add(currentNoteGuid);
675 menuBar.blockSignals(true);
676 menuBar.narrowListView.blockSignals(true);
677 menuBar.wideListView.blockSignals(true);
678 if (Global.getListView() == Global.View_List_Narrow) {
679 menuBar.narrowListView.setChecked(true);
682 menuBar.wideListView.setChecked(true);
684 menuBar.blockSignals(false);
685 menuBar.narrowListView.blockSignals(false);
686 menuBar.wideListView.blockSignals(false);
688 if (Global.getListView() == Global.View_List_Wide) {
689 browserIndexSplitter.addWidget(noteTableView);
690 browserIndexSplitter.addWidget(browserWindow);
692 mainLeftRightSplitter.addWidget(noteTableView);
693 mainLeftRightSplitter.addWidget(browserWindow);
696 int sortCol = Global.getSortColumn();
697 int sortOrder = Global.getSortOrder();
698 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
699 if (Global.checkVersionUpgrade())
704 public static void main(String[] args) {
705 log.setLevel(Level.FATAL);
706 QApplication.initialize(args);
707 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
708 QSplashScreen splash = new QSplashScreen(pixmap);
711 DatabaseConnection dbConn;
714 initializeGlobalSettings(args);
716 showSplash = Global.isWindowVisible("SplashScreen");
720 dbConn = setupDatabaseConnection();
722 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
723 Global.getFileManager().purgeResDirectory(true);
725 } catch (InitializationException e) {
728 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
732 NeverNote application = new NeverNote(dbConn);
734 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
735 if (Global.startMinimized())
736 application.showMinimized();
738 if (Global.wasWindowMaximized())
739 application.showMaximized();
745 splash.finish(application);
747 System.out.println("Goodbye.");
752 * Open the internal database, or create if not present
754 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
756 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
757 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
759 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
760 boolean dbExists = f.exists();
762 Global.setDatabaseUrl("");
764 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
765 boolean goodCheck = false;
767 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
769 if (!dialog.okPressed())
771 Global.cipherPassword = dialog.getPassword();
772 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
773 Global.getDatabaseUserPassword(), Global.cipherPassword);
776 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
780 // Encrypt the database upon shutdown
781 private void encryptOnShutdown() {
782 String dbPath= Global.getFileManager().getDbDirPath("");
783 String dbName = "NeverNote";
785 Statement st = conn.getConnection().createStatement();
786 st.execute("shutdown");
787 if (QMessageBox.question(this, "Are you sure",
788 "Are you sure you wish to encrypt the database?",
789 QMessageBox.StandardButton.Yes,
790 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
791 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
792 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
793 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
795 } catch (SQLException e) {
800 // Decrypt the database upon shutdown
801 private void decryptOnShutdown() {
802 String dbPath= Global.getFileManager().getDbDirPath("");
803 String dbName = "NeverNote";
805 Statement st = conn.getConnection().createStatement();
806 st.execute("shutdown");
807 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
808 encryptCipher = "AES";
810 encryptCipher = "XTEA";
811 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
812 "Are you sure you wish to decrypt the database?"),
813 QMessageBox.StandardButton.Yes,
814 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
816 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
817 Global.setDatabaseUrl("");
818 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
820 } catch (SQLException e) {
825 * Encrypt/Decrypt the local database
827 public void doDatabaseEncrypt() {
828 // The database is not currently encrypted
829 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
830 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
831 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
832 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
833 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
834 "Do you wish to proceed?"),
835 QMessageBox.StandardButton.Yes,
836 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
839 DBEncryptDialog dialog = new DBEncryptDialog();
841 if (dialog.okPressed()) {
842 Global.cipherPassword = dialog.getPassword();
843 encryptOnShutdown = true;
844 encryptCipher = dialog.getEncryptionMethod();
847 DBEncryptDialog dialog = new DBEncryptDialog();
848 dialog.setWindowTitle("Database Decryption");
849 dialog.hideEncryption();
851 if (dialog.okPressed()) {
852 if (!dialog.getPassword().equals(Global.cipherPassword)) {
853 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
856 decryptOnShutdown = true;
863 private static void initializeGlobalSettings(String[] args) throws InitializationException {
864 StartupConfig startupConfig = new StartupConfig();
866 for (String arg : args) {
867 String lower = arg.toLowerCase();
868 if (lower.startsWith("--name="))
869 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
870 if (lower.startsWith("--home="))
871 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
872 if (lower.startsWith("--disable-viewing"))
873 startupConfig.setDisableViewing(true);
875 Global.setup(startupConfig);
880 public void closeEvent(QCloseEvent event) {
881 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
886 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
889 if (currentNote!= null & browserWindow!=null) {
890 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
891 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
894 setMessage(tr("Beginning shutdown."));
896 // Close down external windows
897 Collection<ExternalBrowse> windows = externalWindows.values();
898 Iterator<ExternalBrowse> iterator = windows.iterator();
899 while (iterator.hasNext()) {
900 ExternalBrowse browser = iterator.next();
901 browser.windowClosing.disconnect();
906 externalFileEditedSaver();
907 if (Global.isConnected && Global.synchronizeOnClose()) {
908 setMessage(tr("Performing synchronization before closing."));
909 syncRunner.addWork("SYNC");
911 setMessage("Closing Program.");
912 threadMonitorTimer.stop();
914 syncRunner.addWork("STOP");
915 syncRunner.keepRunning = false;
916 thumbnailRunner.addWork("STOP");
917 syncRunner.keepRunning = false;
918 indexRunner.addWork("STOP");
919 syncRunner.keepRunning = false;
924 if (tempFiles != null)
927 browserWindow.noteSignal.tagsChanged.disconnect();
928 browserWindow.noteSignal.titleChanged.disconnect();
929 browserWindow.noteSignal.noteChanged.disconnect();
930 browserWindow.noteSignal.notebookChanged.disconnect();
931 browserWindow.noteSignal.createdDateChanged.disconnect();
932 browserWindow.noteSignal.alteredDateChanged.disconnect();
933 syncRunner.searchSignal.listChanged.disconnect();
934 syncRunner.tagSignal.listChanged.disconnect();
935 syncRunner.notebookSignal.listChanged.disconnect();
936 syncRunner.noteIndexSignal.listChanged.disconnect();
939 Global.saveWindowVisible("toolBar", toolBar.isVisible());
940 saveNoteColumnPositions();
941 saveNoteIndexWidth();
943 int width = notebookTree.columnWidth(0);
944 Global.setColumnWidth("notebookTreeName", width);
945 width = tagTree.columnWidth(0);
946 Global.setColumnWidth("tagTreeName", width);
948 Global.saveWindowMaximized(isMaximized());
949 Global.saveCurrentNoteGuid(currentNoteGuid);
951 int sortCol = noteTableView.proxyModel.sortColumn();
952 int sortOrder = noteTableView.proxyModel.sortOrder().value();
953 Global.setSortColumn(sortCol);
954 Global.setSortOrder(sortOrder);
958 Global.keepRunning = false;
960 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
961 if (indexRunner.thread().isAlive())
962 indexRunner.thread().join(50);
963 if (!indexRunner.thread().isAlive())
964 logger.log(logger.MEDIUM, "Index thread has stopped");
966 logger.log(logger.MEDIUM, "Index thread still running - bypassing");
967 } catch (InterruptedException e1) {
968 e1.printStackTrace();
970 if (!syncRunner.isIdle()) {
972 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
974 logger.log(logger.MEDIUM, "Sync thread has stopped");
975 } catch (InterruptedException e1) {
976 e1.printStackTrace();
980 if (encryptOnShutdown) {
983 if (decryptOnShutdown) {
986 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
989 @SuppressWarnings("unused")
990 private void closeNeverNote() {
994 public void setMessage(String s) {
995 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
996 logger.log(logger.HIGH, "Message: " +s);
997 statusBar.showMessage(s);
999 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1002 private void waitCursor(boolean wait) {
1004 if (QApplication.overrideCursor() == null)
1005 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1008 while (QApplication.overrideCursor() != null)
1009 QApplication.restoreOverrideCursor();
1013 private void setupIndexListeners() {
1014 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1015 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1016 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1017 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1019 private void setupSyncSignalListeners() {
1020 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1021 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1022 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1023 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1024 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1026 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1027 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1028 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1030 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1031 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1032 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1033 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1035 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1038 private void setupBrowserSignalListeners() {
1039 setupBrowserWindowListeners(browserWindow, true);
1042 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1043 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1044 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1045 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1046 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1047 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1048 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1049 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1050 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1051 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1052 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1053 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1054 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1055 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1056 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1057 if (master) browser.focusLost.connect(this, "saveNote()");
1058 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1061 //***************************************************************
1062 //***************************************************************
1063 //* Settings and look & feel
1064 //***************************************************************
1065 //***************************************************************
1066 @SuppressWarnings("unused")
1067 private void settings() {
1068 logger.log(logger.HIGH, "Entering NeverNote.settings");
1069 saveNoteColumnPositions();
1070 saveNoteIndexWidth();
1072 ConfigDialog settings = new ConfigDialog(this);
1073 String dateFormat = Global.getDateFormat();
1074 String timeFormat = Global.getTimeFormat();
1076 indexTime = 1000*Global.getIndexThreadSleepInterval();
1077 indexTimer.start(indexTime); // reset indexing timer
1080 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1081 if (Global.showTrayIcon())
1086 if (menuBar.showEditorBar.isChecked())
1087 showEditorButtons(browserWindow);
1089 // Reset the save timer
1090 if (Global.getAutoSaveInterval() > 0)
1091 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1095 // This is a hack to force a reload of the index in case the date or time changed.
1096 // if (!dateFormat.equals(Global.getDateFormat()) ||
1097 // !timeFormat.equals(Global.getTimeFormat())) {
1099 readOnlyCache.clear();
1100 inkNoteCache.clear();
1101 noteIndexUpdated(true);
1104 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1106 // Restore things to the way they were
1107 private void restoreWindowState(boolean mainWindow) {
1108 // We need to name things or this doesn't work.
1109 setObjectName("NeverNote");
1110 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1111 browserIndexSplitter.setObjectName("browserIndexSplitter");
1112 leftSplitter1.setObjectName("leftSplitter1");
1114 // Restore the actual positions.
1116 restoreGeometry(Global.restoreGeometry(objectName()));
1117 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1118 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1119 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1122 // Save window positions for the next start
1123 private void saveWindowState() {
1124 Global.saveGeometry(objectName(), saveGeometry());
1125 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1126 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1127 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1129 // Load the style sheet
1130 private void loadStyleSheet() {
1131 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1132 fileName = Global.getFileManager().getQssDirPath("default.qss");
1133 QFile file = new QFile(fileName);
1135 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1136 if (!file.exists()) {
1137 fileName = Global.getFileManager().getQssDirPath("default.qss");
1138 file = new QFile(fileName);
1140 file.open(OpenModeFlag.ReadOnly);
1141 String styleSheet = file.readAll().toString();
1143 setStyleSheet(styleSheet);
1145 // Save column positions for the next time
1146 private void saveNoteColumnPositions() {
1147 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1148 Global.setColumnPosition("noteTableCreationPosition", position);
1149 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1150 Global.setColumnPosition("noteTableTagPosition", position);
1151 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1152 Global.setColumnPosition("noteTableNotebookPosition", position);
1153 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1154 Global.setColumnPosition("noteTableChangedPosition", position);
1155 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1156 Global.setColumnPosition("noteTableAuthorPosition", position);
1157 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1158 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1159 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1160 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1161 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1162 Global.setColumnPosition("noteTableTitlePosition", position);
1163 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1164 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1165 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1166 Global.setColumnPosition("noteTableGuidPosition", position);
1167 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1168 Global.setColumnPosition("noteTableThumbnailPosition", position);
1171 // Save column widths for the next time
1172 private void saveNoteIndexWidth() {
1174 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1175 Global.setColumnWidth("noteTableCreationPosition", width);
1176 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1177 Global.setColumnWidth("noteTableChangedPosition", width);
1178 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1179 Global.setColumnWidth("noteTableGuidPosition", width);
1180 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1181 Global.setColumnWidth("noteTableNotebookPosition", width);
1182 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1183 Global.setColumnWidth("noteTableTagPosition", width);
1184 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1185 Global.setColumnWidth("noteTableTitlePosition", width);
1186 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1187 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1188 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1189 Global.setColumnWidth("noteTableAuthorPosition", width);
1190 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1191 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1192 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1193 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1194 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1195 Global.setColumnWidth("noteTableThumbnailPosition", width);
1196 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1197 Global.setColumnWidth("noteTableGuidPosition", width);
1201 //***************************************************************
1202 //***************************************************************
1203 //** These functions deal with Notebook menu items
1204 //***************************************************************
1205 //***************************************************************
1206 // Setup the tree containing the user's notebooks.
1207 private void initializeNotebookTree() {
1208 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1209 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1210 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1211 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1212 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1214 // Listener when a notebook is selected
1215 private void notebookTreeSelection() {
1216 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1219 clearAttributeFilter();
1220 clearSavedSearchFilter();
1221 if (Global.mimicEvernoteInterface) {
1223 searchField.clear();
1225 menuBar.noteRestoreAction.setVisible(false);
1226 menuBar.notebookEditAction.setEnabled(true);
1227 menuBar.notebookDeleteAction.setEnabled(true);
1228 menuBar.notebookPublishAction.setEnabled(true);
1229 menuBar.notebookShareAction.setEnabled(true);
1230 menuBar.notebookIconAction.setEnabled(true);
1231 menuBar.notebookStackAction.setEnabled(true);
1232 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1233 selectedNotebookGUIDs.clear();
1235 String stackName = "";
1236 if (selections.size() > 0) {
1237 guid = (selections.get(0).text(2));
1238 stackName = selections.get(0).text(0);
1240 if (!Global.mimicEvernoteInterface) {
1241 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1242 if (selections.size()==0) {
1243 selectedNotebookGUIDs.clear();
1244 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1245 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1247 menuBar.notebookEditAction.setEnabled(false);
1248 menuBar.notebookDeleteAction.setEnabled(false);
1249 menuBar.notebookStackAction.setEnabled(false);
1250 menuBar.notebookIconAction.setEnabled(false);
1253 if (!guid.equals("") && !guid.equals("STACK")) {
1254 selectedNotebookGUIDs.add(guid);
1255 menuBar.notebookIconAction.setEnabled(true);
1257 menuBar.notebookIconAction.setEnabled(true);
1258 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1259 Notebook book = listManager.getNotebookIndex().get(j);
1260 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1261 selectedNotebookGUIDs.add(book.getGuid());
1264 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1265 listManager.loadNotesIndex();
1266 noteIndexUpdated(false);
1267 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1270 private void clearNotebookFilter() {
1271 notebookTree.blockSignals(true);
1272 notebookTree.clearSelection();
1273 menuBar.noteRestoreAction.setVisible(false);
1274 menuBar.notebookEditAction.setEnabled(false);
1275 menuBar.notebookDeleteAction.setEnabled(false);
1276 selectedNotebookGUIDs.clear();
1277 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1278 notebookTree.blockSignals(false);
1280 // Triggered when the notebook DB has been updated
1281 private void notebookIndexUpdated() {
1282 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1284 // Get the possible icons
1285 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1286 notebookTree.setIcons(icons);
1288 if (selectedNotebookGUIDs == null)
1289 selectedNotebookGUIDs = new ArrayList<String>();
1290 List<Notebook> books = conn.getNotebookTable().getAll();
1291 for (int i=books.size()-1; i>=0; i--) {
1292 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1293 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1295 j=listManager.getArchiveNotebookIndex().size();
1301 listManager.countNotebookResults(listManager.getNoteIndex());
1302 notebookTree.blockSignals(true);
1303 notebookTree.load(books, listManager.getLocalNotebooks());
1304 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1305 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1307 selectedNotebookGUIDs.remove(i);
1309 notebookTree.blockSignals(false);
1311 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1313 // Show/Hide note information
1314 private void toggleNotebookWindow() {
1315 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1316 if (notebookTree.isVisible())
1317 notebookTree.hide();
1319 notebookTree.show();
1320 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1321 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1322 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1324 // Add a new notebook
1325 @SuppressWarnings("unused")
1326 private void addNotebook() {
1327 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1328 NotebookEdit edit = new NotebookEdit();
1329 edit.setNotebooks(listManager.getNotebookIndex());
1332 if (!edit.okPressed())
1335 Calendar currentTime = new GregorianCalendar();
1336 Long l = new Long(currentTime.getTimeInMillis());
1337 String randint = new String(Long.toString(l));
1339 Notebook newBook = new Notebook();
1340 newBook.setUpdateSequenceNum(0);
1341 newBook.setGuid(randint);
1342 newBook.setName(edit.getNotebook());
1343 newBook.setServiceCreated(new Date().getTime());
1344 newBook.setServiceUpdated(new Date().getTime());
1345 newBook.setDefaultNotebook(false);
1346 newBook.setPublished(false);
1348 listManager.getNotebookIndex().add(newBook);
1350 listManager.getLocalNotebooks().add(newBook.getGuid());
1351 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1352 notebookIndexUpdated();
1353 listManager.countNotebookResults(listManager.getNoteIndex());
1354 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1355 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1357 // Edit an existing notebook
1358 @SuppressWarnings("unused")
1359 private void stackNotebook() {
1360 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1361 StackNotebook edit = new StackNotebook();
1363 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1364 QTreeWidgetItem currentSelection;
1365 for (int i=0; i<selections.size(); i++) {
1366 currentSelection = selections.get(0);
1367 String guid = currentSelection.text(2);
1368 if (guid.equalsIgnoreCase("")) {
1369 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1372 if (guid.equalsIgnoreCase("STACK")) {
1373 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1378 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1383 if (!edit.okPressed())
1386 String stack = edit.getStackName();
1388 for (int i=0; i<selections.size(); i++) {
1389 currentSelection = selections.get(i);
1390 String guid = currentSelection.text(2);
1391 listManager.updateNotebookStack(guid, stack);
1393 notebookIndexUpdated();
1394 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1396 // Edit an existing notebook
1397 @SuppressWarnings("unused")
1398 private void editNotebook() {
1399 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1400 NotebookEdit edit = new NotebookEdit();
1402 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1403 QTreeWidgetItem currentSelection;
1404 currentSelection = selections.get(0);
1405 edit.setNotebook(currentSelection.text(0));
1407 String guid = currentSelection.text(2);
1408 if (!guid.equalsIgnoreCase("STACK")) {
1409 edit.setTitle(tr("Edit Notebook"));
1410 edit.setNotebooks(listManager.getNotebookIndex());
1411 edit.setLocalCheckboxEnabled(false);
1412 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1413 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1414 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1415 i=listManager.getNotebookIndex().size();
1419 edit.setTitle(tr("Edit Stack"));
1420 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1421 edit.hideLocalCheckbox();
1422 edit.hideDefaultCheckbox();
1427 if (!edit.okPressed())
1431 if (guid.equalsIgnoreCase("STACK")) {
1432 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1433 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1434 if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1435 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1437 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1438 currentSelection.setText(0, edit.getNotebook());
1442 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1443 currentSelection.setText(0, edit.getNotebook());
1445 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1446 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1447 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1448 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1449 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1450 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1451 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1452 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1454 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1455 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1456 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1457 linkedNotebook.setShareName(edit.getNotebook());
1458 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1460 i=listManager.getNotebookIndex().size();
1464 // Build a list of non-closed notebooks
1465 List<Notebook> nbooks = new ArrayList<Notebook>();
1466 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1467 boolean found=false;
1468 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1469 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1473 nbooks.add(listManager.getNotebookIndex().get(i));
1477 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1478 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1479 browserWindow.setNotebookList(filteredBooks);
1480 Iterator<String> set = externalWindows.keySet().iterator();
1481 while(set.hasNext())
1482 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1483 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1485 // Publish a notebook
1486 @SuppressWarnings("unused")
1487 private void publishNotebook() {
1488 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1489 QTreeWidgetItem currentSelection;
1490 currentSelection = selections.get(0);
1491 String guid = currentSelection.text(2);
1493 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1498 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1499 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1500 n = listManager.getNotebookIndex().get(i);
1502 i = listManager.getNotebookIndex().size();
1508 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1511 if (!publish.okClicked())
1514 Publishing p = publish.getPublishing();
1515 boolean isPublished = !publish.isStopPressed();
1516 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1517 n.setPublished(isPublished);
1519 listManager.getNotebookIndex().set(position, n);
1520 notebookIndexUpdated();
1522 // Publish a notebook
1523 @SuppressWarnings("unused")
1524 private void shareNotebook() {
1525 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1526 QTreeWidgetItem currentSelection;
1527 currentSelection = selections.get(0);
1528 String guid = currentSelection.text(2);
1530 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1534 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1535 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1536 n = listManager.getNotebookIndex().get(i);
1537 i = listManager.getNotebookIndex().size();
1541 String authToken = null;
1542 if (syncRunner.isConnected)
1543 authToken = syncRunner.authToken;
1544 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1549 // Delete an existing notebook
1550 @SuppressWarnings("unused")
1551 private void deleteNotebook() {
1552 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1553 boolean stacksFound = false;
1554 boolean notebooksFound = false;
1555 boolean assigned = false;
1556 // Check if any notes have this notebook
1557 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1558 for (int i=0; i<selections.size(); i++) {
1559 QTreeWidgetItem currentSelection;
1560 currentSelection = selections.get(i);
1561 String guid = currentSelection.text(2);
1562 if (!guid.equalsIgnoreCase("STACK")) {
1563 notebooksFound = true;
1564 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1565 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1566 if (noteGuid.equals(guid)) {
1568 j=listManager.getNoteIndex().size();
1569 i=selections.size();
1577 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1578 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1582 if (conn.getNotebookTable().getAll().size() == 1) {
1583 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1587 // If all notebooks are clear, verify the delete
1588 String msg1 = new String(tr("Delete selected notebooks?"));
1589 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1590 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1591 " not deleted unless selected?"));
1593 if (stacksFound && notebooksFound)
1595 if (!stacksFound && notebooksFound)
1597 if (stacksFound && !notebooksFound)
1599 if (QMessageBox.question(this, tr("Confirmation"), msg,
1600 QMessageBox.StandardButton.Yes,
1601 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1605 // If confirmed, delete the notebook
1606 for (int i=selections.size()-1; i>=0; i--) {
1607 QTreeWidgetItem currentSelection;
1608 currentSelection = selections.get(i);
1609 String guid = currentSelection.text(2);
1610 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1611 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1612 listManager.renameStack(currentSelection.text(0), "");
1614 conn.getNotebookTable().expungeNotebook(guid, true);
1615 listManager.deleteNotebook(guid);
1619 notebookIndexUpdated();
1620 // notebookTreeSelection();
1621 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1622 // listManager.countNotebookResults(listManager.getNoteIndex());
1623 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1625 // A note's notebook has been updated
1626 @SuppressWarnings("unused")
1627 private void updateNoteNotebook(String guid, String notebookGuid) {
1629 // Update the list manager
1630 listManager.updateNoteNotebook(guid, notebookGuid);
1631 listManager.countNotebookResults(listManager.getNoteIndex());
1632 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1634 // Find the name of the notebook
1635 String notebookName = null;
1636 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1637 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1638 notebookName = listManager.getNotebookIndex().get(i).getName();
1643 // If we found the name, update the browser window
1644 if (notebookName != null) {
1645 updateListNoteNotebook(guid, notebookName);
1646 if (guid.equals(currentNoteGuid)) {
1647 int pos = browserWindow.notebookBox.findText(notebookName);
1649 browserWindow.notebookBox.setCurrentIndex(pos);
1653 // If we're dealing with the current note, then we need to be sure and update the notebook there
1654 if (guid.equals(currentNoteGuid)) {
1655 if (currentNote != null) {
1656 currentNote.setNotebookGuid(notebookGuid);
1660 // Open/close notebooks
1661 @SuppressWarnings("unused")
1662 private void closeNotebooks() {
1663 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1665 if (!na.okClicked())
1669 listManager.getArchiveNotebookIndex().clear();
1671 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1672 String text = na.getClosedBookList().takeItem(i).text();
1673 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1674 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1675 Notebook n = listManager.getNotebookIndex().get(j);
1676 conn.getNotebookTable().setArchived(n.getGuid(),true);
1677 listManager.getArchiveNotebookIndex().add(n);
1678 j=listManager.getNotebookIndex().size();
1683 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1684 String text = na.getOpenBookList().takeItem(i).text();
1685 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1686 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1687 Notebook n = listManager.getNotebookIndex().get(j);
1688 conn.getNotebookTable().setArchived(n.getGuid(),false);
1689 j=listManager.getNotebookIndex().size();
1693 notebookTreeSelection();
1694 listManager.loadNotesIndex();
1695 notebookIndexUpdated();
1696 noteIndexUpdated(false);
1697 reloadTagTree(true);
1698 // noteIndexUpdated(false);
1700 // Build a list of non-closed notebooks
1701 List<Notebook> nbooks = new ArrayList<Notebook>();
1702 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1703 boolean found=false;
1704 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1705 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1709 nbooks.add(listManager.getNotebookIndex().get(i));
1712 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1713 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1714 browserWindow.setNotebookList(filteredBooks);
1716 // Update any external windows
1717 Iterator<String> set = externalWindows.keySet().iterator();
1718 while(set.hasNext())
1719 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1723 // Change the notebook's icon
1724 @SuppressWarnings("unused")
1725 private void setNotebookIcon() {
1726 boolean stackSelected = false;
1727 boolean allNotebookSelected = false;
1729 QTreeWidgetItem currentSelection;
1730 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1731 if (selections.size() == 0)
1734 currentSelection = selections.get(0);
1735 String guid = currentSelection.text(2);
1736 if (guid.equalsIgnoreCase(""))
1737 allNotebookSelected = true;
1738 if (guid.equalsIgnoreCase("STACK"))
1739 stackSelected = true;
1741 QIcon currentIcon = currentSelection.icon(0);
1745 if (!stackSelected && !allNotebookSelected) {
1746 icon = conn.getNotebookTable().getIcon(guid);
1748 dialog = new SetIcon(currentIcon);
1749 dialog.setUseDefaultIcon(true);
1751 dialog = new SetIcon(icon);
1752 dialog.setUseDefaultIcon(false);
1755 if (stackSelected) {
1756 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1758 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1761 dialog = new SetIcon(currentIcon);
1762 dialog.setUseDefaultIcon(true);
1764 dialog = new SetIcon(icon);
1765 dialog.setUseDefaultIcon(false);
1769 if (dialog.okPressed()) {
1770 QIcon newIcon = dialog.getIcon();
1771 if (stackSelected) {
1772 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1773 if (newIcon == null) {
1774 newIcon = new QIcon(iconPath+"books2.png");
1776 currentSelection.setIcon(0,newIcon);
1779 if (allNotebookSelected) {
1780 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1781 if (newIcon == null) {
1782 newIcon = new QIcon(iconPath+"notebook-green.png");
1784 currentSelection.setIcon(0,newIcon);
1787 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1788 if (newIcon == null) {
1789 boolean isPublished = false;;
1790 boolean found = false;
1791 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1792 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1793 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1797 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1799 currentSelection.setIcon(0, newIcon);
1805 //***************************************************************
1806 //***************************************************************
1807 //** These functions deal with Tag menu items
1808 //***************************************************************
1809 //***************************************************************
1810 // Add a new notebook
1811 @SuppressWarnings("unused")
1812 private void addTag() {
1813 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1814 TagEdit edit = new TagEdit();
1815 edit.setTagList(listManager.getTagIndex());
1818 if (!edit.okPressed())
1821 Calendar currentTime = new GregorianCalendar();
1822 Long l = new Long(currentTime.getTimeInMillis());
1823 String randint = new String(Long.toString(l));
1825 Tag newTag = new Tag();
1826 newTag.setUpdateSequenceNum(0);
1827 newTag.setGuid(randint);
1828 newTag.setName(edit.getTag());
1829 conn.getTagTable().addTag(newTag, true);
1830 listManager.getTagIndex().add(newTag);
1831 reloadTagTree(true);
1833 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1835 @SuppressWarnings("unused")
1836 private void reloadTagTree() {
1837 reloadTagTree(false);
1839 private void reloadTagTree(boolean reload) {
1840 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1841 tagIndexUpdated(reload);
1842 boolean filter = false;
1843 listManager.countTagResults(listManager.getNoteIndex());
1844 if (notebookTree.selectedItems().size() > 0
1845 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1847 if (tagTree.selectedItems().size() > 0)
1849 tagTree.showAllTags(!filter);
1850 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1852 // Edit an existing tag
1853 @SuppressWarnings("unused")
1854 private void editTag() {
1855 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1856 TagEdit edit = new TagEdit();
1857 edit.setTitle("Edit Tag");
1858 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1859 QTreeWidgetItem currentSelection;
1860 currentSelection = selections.get(0);
1861 edit.setTag(currentSelection.text(0));
1862 edit.setTagList(listManager.getTagIndex());
1865 if (!edit.okPressed())
1868 String guid = currentSelection.text(2);
1869 currentSelection.setText(0,edit.getTag());
1871 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1872 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1873 listManager.getTagIndex().get(i).setName(edit.getTag());
1874 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1875 updateListTagName(guid);
1876 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1877 browserWindow.setTag(getTagNamesForNote(currentNote));
1878 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1882 browserWindow.setTag(getTagNamesForNote(currentNote));
1883 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1885 // Delete an existing tag
1886 @SuppressWarnings("unused")
1887 private void deleteTag() {
1888 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1890 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1891 QMessageBox.StandardButton.Yes,
1892 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1896 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1897 for (int i=selections.size()-1; i>=0; i--) {
1898 QTreeWidgetItem currentSelection;
1899 currentSelection = selections.get(i);
1900 removeTagItem(currentSelection.text(2));
1902 tagIndexUpdated(true);
1904 listManager.countTagResults(listManager.getNoteIndex());
1905 // tagTree.updateCounts(listManager.getTagCounter());
1906 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1908 // Remove a tag tree item. Go recursively down & remove the children too
1909 private void removeTagItem(String guid) {
1910 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1911 String parent = listManager.getTagIndex().get(j).getParentGuid();
1912 if (parent != null && parent.equals(guid)) {
1913 //Remove this tag's children
1914 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1917 //Now, remove this tag
1918 removeListTagName(guid);
1919 conn.getTagTable().expungeTag(guid, true);
1920 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1921 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1922 listManager.getTagIndex().remove(a);
1927 // Setup the tree containing the user's tags
1928 private void initializeTagTree() {
1929 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1930 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1931 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
1932 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1933 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1934 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1936 // Listener when a tag is selected
1937 private void tagTreeSelection() {
1938 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1941 clearAttributeFilter();
1942 clearSavedSearchFilter();
1944 menuBar.noteRestoreAction.setVisible(false);
1946 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1947 QTreeWidgetItem currentSelection;
1948 selectedTagGUIDs.clear();
1949 for (int i=0; i<selections.size(); i++) {
1950 currentSelection = selections.get(i);
1951 selectedTagGUIDs.add(currentSelection.text(2));
1953 if (selections.size() > 0) {
1954 menuBar.tagEditAction.setEnabled(true);
1955 menuBar.tagDeleteAction.setEnabled(true);
1956 menuBar.tagIconAction.setEnabled(true);
1959 menuBar.tagEditAction.setEnabled(false);
1960 menuBar.tagDeleteAction.setEnabled(false);
1961 menuBar.tagIconAction.setEnabled(true);
1963 listManager.setSelectedTags(selectedTagGUIDs);
1964 listManager.loadNotesIndex();
1965 noteIndexUpdated(false);
1966 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1968 // trigger the tag index to be refreshed
1969 @SuppressWarnings("unused")
1970 private void tagIndexUpdated() {
1971 tagIndexUpdated(true);
1973 private void tagIndexUpdated(boolean reload) {
1974 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1975 if (selectedTagGUIDs == null)
1976 selectedTagGUIDs = new ArrayList<String>();
1978 listManager.reloadTagIndex();
1980 tagTree.blockSignals(true);
1982 tagTree.setIcons(conn.getTagTable().getAllIcons());
1983 tagTree.load(listManager.getTagIndex());
1985 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1986 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
1988 selectedTagGUIDs.remove(i);
1990 tagTree.blockSignals(false);
1992 browserWindow.setTag(getTagNamesForNote(currentNote));
1993 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
1995 // Show/Hide note information
1996 private void toggleTagWindow() {
1997 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
1998 if (tagTree.isVisible())
2002 menuBar.hideTags.setChecked(tagTree.isVisible());
2003 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2004 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2006 // A note's tags have been updated
2007 @SuppressWarnings("unused")
2008 private void updateNoteTags(String guid, List<String> tags) {
2009 // Save any new tags. We'll need them later.
2010 List<String> newTags = new ArrayList<String>();
2011 for (int i=0; i<tags.size(); i++) {
2012 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2013 newTags.add(tags.get(i));
2016 listManager.saveNoteTags(guid, tags);
2017 listManager.countTagResults(listManager.getNoteIndex());
2018 StringBuffer names = new StringBuffer("");
2019 for (int i=0; i<tags.size(); i++) {
2020 names = names.append(tags.get(i));
2021 if (i<tags.size()-1) {
2022 names.append(Global.tagDelimeter + " ");
2025 browserWindow.setTag(names.toString());
2028 // Now, we need to add any new tags to the tag tree
2029 for (int i=0; i<newTags.size(); i++)
2030 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2032 // Get a string containing all tag names for a note
2033 private String getTagNamesForNote(Note n) {
2034 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2035 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2037 StringBuffer buffer = new StringBuffer(100);
2038 Vector<String> v = new Vector<String>();
2039 List<String> guids = n.getTagGuids();
2044 for (int i=0; i<guids.size(); i++) {
2045 v.add(listManager.getTagNameByGuid(guids.get(i)));
2047 Comparator<String> comparator = Collections.reverseOrder();
2048 Collections.sort(v,comparator);
2049 Collections.reverse(v);
2051 for (int i = 0; i<v.size(); i++) {
2053 buffer.append(", ");
2054 buffer.append(v.get(i));
2057 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2058 return buffer.toString();
2060 // Tags were added via dropping notes from the note list
2061 @SuppressWarnings("unused")
2062 private void tagsAdded(String noteGuid, String tagGuid) {
2063 String tagName = null;
2064 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2065 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2066 tagName = listManager.getTagIndex().get(i).getName();
2067 i=listManager.getTagIndex().size();
2070 if (tagName == null)
2073 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2074 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2075 List<String> tagNames = new ArrayList<String>();
2076 tagNames.add(new String(tagName));
2077 Note n = listManager.getMasterNoteIndex().get(i);
2078 for (int j=0; j<n.getTagNames().size(); j++) {
2079 tagNames.add(new String(n.getTagNames().get(j)));
2081 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2082 if (n.getGuid().equals(currentNoteGuid)) {
2083 Collections.sort(tagNames);
2084 String display = "";
2085 for (int j=0; j<tagNames.size(); j++) {
2086 display = display+tagNames.get(j);
2087 if (j+2<tagNames.size())
2088 display = display+Global.tagDelimeter+" ";
2090 browserWindow.setTag(display);
2092 i=listManager.getMasterNoteIndex().size();
2097 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2099 private void clearTagFilter() {
2100 tagTree.blockSignals(true);
2101 tagTree.clearSelection();
2102 menuBar.noteRestoreAction.setVisible(false);
2103 menuBar.tagEditAction.setEnabled(false);
2104 menuBar.tagDeleteAction.setEnabled(false);
2105 menuBar.tagIconAction.setEnabled(false);
2106 selectedTagGUIDs.clear();
2107 listManager.setSelectedTags(selectedTagGUIDs);
2108 tagTree.blockSignals(false);
2110 // Change the icon for a tag
2111 @SuppressWarnings("unused")
2112 private void setTagIcon() {
2113 QTreeWidgetItem currentSelection;
2114 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2115 if (selections.size() == 0)
2118 currentSelection = selections.get(0);
2119 String guid = currentSelection.text(2);
2121 QIcon currentIcon = currentSelection.icon(0);
2122 QIcon icon = conn.getTagTable().getIcon(guid);
2125 dialog = new SetIcon(currentIcon);
2126 dialog.setUseDefaultIcon(true);
2128 dialog = new SetIcon(icon);
2129 dialog.setUseDefaultIcon(false);
2132 if (dialog.okPressed()) {
2133 QIcon newIcon = dialog.getIcon();
2134 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2135 if (newIcon == null)
2136 newIcon = new QIcon(iconPath+"tag.png");
2137 currentSelection.setIcon(0, newIcon);
2143 //***************************************************************
2144 //***************************************************************
2145 //** These functions deal with Saved Search menu items
2146 //***************************************************************
2147 //***************************************************************
2148 // Add a new notebook
2149 @SuppressWarnings("unused")
2150 private void addSavedSearch() {
2151 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2152 SavedSearchEdit edit = new SavedSearchEdit();
2153 edit.setSearchList(listManager.getSavedSearchIndex());
2156 if (!edit.okPressed())
2159 Calendar currentTime = new GregorianCalendar();
2160 Long l = new Long(currentTime.getTimeInMillis());
2161 String randint = new String(Long.toString(l));
2163 SavedSearch search = new SavedSearch();
2164 search.setUpdateSequenceNum(0);
2165 search.setGuid(randint);
2166 search.setName(edit.getName());
2167 search.setQuery(edit.getQuery());
2168 search.setFormat(QueryFormat.USER);
2169 listManager.getSavedSearchIndex().add(search);
2170 conn.getSavedSearchTable().addSavedSearch(search, true);
2171 savedSearchIndexUpdated();
2172 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2174 // Edit an existing tag
2175 @SuppressWarnings("unused")
2176 private void editSavedSearch() {
2177 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2178 SavedSearchEdit edit = new SavedSearchEdit();
2179 edit.setTitle(tr("Edit Search"));
2180 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2181 QTreeWidgetItem currentSelection;
2182 currentSelection = selections.get(0);
2183 String guid = currentSelection.text(1);
2184 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2185 edit.setName(currentSelection.text(0));
2186 edit.setQuery(s.getQuery());
2187 edit.setSearchList(listManager.getSavedSearchIndex());
2190 if (!edit.okPressed())
2193 List<SavedSearch> list = listManager.getSavedSearchIndex();
2194 SavedSearch search = null;
2195 boolean found = false;
2196 for (int i=0; i<list.size(); i++) {
2197 search = list.get(i);
2198 if (search.getGuid().equals(guid)) {
2205 search.setName(edit.getName());
2206 search.setQuery(edit.getQuery());
2207 conn.getSavedSearchTable().updateSavedSearch(search, true);
2208 savedSearchIndexUpdated();
2209 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2211 // Delete an existing tag
2212 @SuppressWarnings("unused")
2213 private void deleteSavedSearch() {
2214 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2216 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2217 QMessageBox.StandardButton.Yes,
2218 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2222 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2223 for (int i=selections.size()-1; i>=0; i--) {
2224 QTreeWidgetItem currentSelection;
2225 currentSelection = selections.get(i);
2226 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2227 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2228 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2229 listManager.getSavedSearchIndex().remove(j);
2230 j=listManager.getSavedSearchIndex().size()+1;
2233 selections.remove(i);
2235 savedSearchIndexUpdated();
2236 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2238 // Setup the tree containing the user's tags
2239 private void initializeSavedSearchTree() {
2240 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2241 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2242 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2244 // Listener when a tag is selected
2245 @SuppressWarnings("unused")
2246 private void savedSearchTreeSelection() {
2247 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2249 clearNotebookFilter();
2252 clearAttributeFilter();
2254 String currentGuid = selectedSavedSearchGUID;
2255 menuBar.savedSearchEditAction.setEnabled(true);
2256 menuBar.savedSearchDeleteAction.setEnabled(true);
2257 menuBar.savedSearchIconAction.setEnabled(true);
2258 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2259 QTreeWidgetItem currentSelection;
2260 selectedSavedSearchGUID = "";
2261 for (int i=0; i<selections.size(); i++) {
2262 currentSelection = selections.get(i);
2263 if (currentSelection.text(1).equals(currentGuid)) {
2264 currentSelection.setSelected(false);
2266 selectedSavedSearchGUID = currentSelection.text(1);
2268 // i = selections.size() +1;
2271 // There is the potential for no notebooks to be selected if this
2272 // happens then we make it look like all notebooks were selecetd.
2273 // If that happens, just select the "all notebooks"
2274 if (selections.size()==0) {
2275 clearSavedSearchFilter();
2277 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2279 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2281 private void clearSavedSearchFilter() {
2282 menuBar.savedSearchEditAction.setEnabled(false);
2283 menuBar.savedSearchDeleteAction.setEnabled(false);
2284 menuBar.savedSearchIconAction.setEnabled(false);
2285 savedSearchTree.blockSignals(true);
2286 savedSearchTree.clearSelection();
2287 savedSearchTree.blockSignals(false);
2288 selectedSavedSearchGUID = "";
2289 searchField.setEditText("");
2290 searchPerformed = false;
2291 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2293 // trigger the tag index to be refreshed
2294 private void savedSearchIndexUpdated() {
2295 if (selectedSavedSearchGUID == null)
2296 selectedSavedSearchGUID = new String();
2297 savedSearchTree.blockSignals(true);
2298 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2299 savedSearchTree.load(listManager.getSavedSearchIndex());
2300 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2301 savedSearchTree.blockSignals(false);
2303 // trigger when the saved search selection changes
2304 @SuppressWarnings("unused")
2305 private void updateSavedSearchSelection() {
2306 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2308 menuBar.savedSearchEditAction.setEnabled(true);
2309 menuBar.savedSearchDeleteAction.setEnabled(true);
2310 menuBar.savedSearchIconAction.setEnabled(true);
2311 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2313 if (selections.size() > 0) {
2314 menuBar.savedSearchEditAction.setEnabled(true);
2315 menuBar.savedSearchDeleteAction.setEnabled(true);
2316 menuBar.savedSearchIconAction.setEnabled(true);
2317 selectedSavedSearchGUID = selections.get(0).text(1);
2318 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2319 searchField.setEditText(s.getQuery());
2321 menuBar.savedSearchEditAction.setEnabled(false);
2322 menuBar.savedSearchDeleteAction.setEnabled(false);
2323 menuBar.savedSearchIconAction.setEnabled(false);
2324 selectedSavedSearchGUID = "";
2325 searchField.setEditText("");
2327 searchFieldChanged();
2329 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2333 // Show/Hide note information
2334 private void toggleSavedSearchWindow() {
2335 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2336 if (savedSearchTree.isVisible())
2337 savedSearchTree.hide();
2339 savedSearchTree.show();
2340 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2342 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2343 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2345 // Change the icon for a saved search
2346 @SuppressWarnings("unused")
2347 private void setSavedSearchIcon() {
2348 QTreeWidgetItem currentSelection;
2349 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2350 if (selections.size() == 0)
2353 currentSelection = selections.get(0);
2354 String guid = currentSelection.text(1);
2356 QIcon currentIcon = currentSelection.icon(0);
2357 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2360 dialog = new SetIcon(currentIcon);
2361 dialog.setUseDefaultIcon(true);
2363 dialog = new SetIcon(icon);
2364 dialog.setUseDefaultIcon(false);
2367 if (dialog.okPressed()) {
2368 QIcon newIcon = dialog.getIcon();
2369 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2370 if (newIcon == null)
2371 newIcon = new QIcon(iconPath+"search.png");
2372 currentSelection.setIcon(0, newIcon);
2380 //***************************************************************
2381 //***************************************************************
2382 //** These functions deal with Help menu & tool menu items
2383 //***************************************************************
2384 //***************************************************************
2385 // Show database status
2386 @SuppressWarnings("unused")
2387 private void databaseStatus() {
2389 int dirty = conn.getNoteTable().getDirtyCount();
2390 int unindexed = conn.getNoteTable().getUnindexedCount();
2391 DatabaseStatus status = new DatabaseStatus();
2392 status.setUnsynchronized(dirty);
2393 status.setUnindexed(unindexed);
2394 status.setNoteCount(conn.getNoteTable().getNoteCount());
2395 status.setNotebookCount(listManager.getNotebookIndex().size());
2396 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2397 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2398 status.setTagCount(listManager.getTagIndex().size());
2399 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2400 status.setWordCount(conn.getWordsTable().getWordCount());
2404 // Compact the database
2405 @SuppressWarnings("unused")
2406 private void compactDatabase() {
2407 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2408 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2409 "but please be aware that depending upon the size of your database this can be time consuming " +
2410 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2411 QMessageBox.StandardButton.Yes,
2412 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2415 setMessage("Compacting database.");
2417 listManager.compactDatabase();
2419 setMessage("Database compact is complete.");
2420 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2422 @SuppressWarnings("unused")
2423 private void accountInformation() {
2424 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2425 AccountDialog dialog = new AccountDialog();
2427 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2429 @SuppressWarnings("unused")
2430 private void releaseNotes() {
2431 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2432 QDialog dialog = new QDialog(this);
2433 QHBoxLayout layout = new QHBoxLayout();
2434 QTextEdit textBox = new QTextEdit();
2435 layout.addWidget(textBox);
2436 textBox.setReadOnly(true);
2437 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2438 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2439 QIODevice.OpenModeFlag.Text)))
2441 textBox.setText(file.readAll().toString());
2443 dialog.setWindowTitle(tr("Release Notes"));
2444 dialog.setLayout(layout);
2446 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2448 // Called when user picks Log from the help menu
2449 @SuppressWarnings("unused")
2450 private void logger() {
2451 logger.log(logger.HIGH, "Entering NeverNote.logger");
2452 QDialog dialog = new QDialog(this);
2453 QHBoxLayout layout = new QHBoxLayout();
2454 QListWidget textBox = new QListWidget();
2455 layout.addWidget(textBox);
2456 textBox.addItems(emitLog);
2458 dialog.setLayout(layout);
2459 dialog.setWindowTitle(tr("Mesasge Log"));
2461 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2463 // Menu option "help/about" was selected
2464 @SuppressWarnings("unused")
2465 private void about() {
2466 logger.log(logger.HIGH, "Entering NeverNote.about");
2467 QMessageBox.about(this,
2468 tr("About NeverNote"),
2469 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2471 +tr("<hr></center>Evernote"
2472 +"An Open Source Evernote Client.<br><br>"
2473 +"Licensed under GPL v2. <br><hr><br>"
2474 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2475 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2476 +"PDFRenderer is licened under the LGPL<br>"
2477 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2478 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2479 +"Jazzy is licened under the LGPL<br>"
2480 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2481 logger.log(logger.HIGH, "Leaving NeverNote.about");
2483 // Hide the entire left hand side
2484 @SuppressWarnings("unused")
2485 private void toggleLeftSide() {
2488 hidden = !menuBar.hideLeftSide.isChecked();
2489 menuBar.hideLeftSide.setChecked(!hidden);
2491 if (notebookTree.isVisible() != hidden)
2492 toggleNotebookWindow();
2493 if (savedSearchTree.isVisible() != hidden)
2494 toggleSavedSearchWindow();
2495 if (tagTree.isVisible() != hidden)
2497 if (attributeTree.isVisible() != hidden)
2498 toggleAttributesWindow();
2499 if (trashTree.isVisible() != hidden)
2500 toggleTrashWindow();
2502 Global.saveWindowVisible("leftPanel", hidden);
2505 public void checkForUpdates() {
2506 // Send off thread to check for a new version
2507 versionChecker = new QNetworkAccessManager(this);
2508 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2509 QNetworkRequest request = new QNetworkRequest();
2510 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2511 versionChecker.get(request);
2513 @SuppressWarnings("unused")
2514 private void upgradeFileRead(QNetworkReply reply) {
2515 if (!reply.isReadable())
2518 String winVersion = Global.version;
2519 String osxVersion = Global.version;
2520 String linuxVersion = Global.version;
2521 String linux64Version = Global.version;
2522 String version = Global.version;
2524 // Determine the versions available
2525 QByteArray data = reply.readLine();
2526 while (data != null && !reply.atEnd()) {
2527 String line = data.toString();
2529 if (line.contains(":"))
2530 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2533 if (line.toLowerCase().contains("windows"))
2534 winVersion = lineVersion;
2535 else if (line.toLowerCase().contains("os-x"))
2536 osxVersion = lineVersion;
2537 else if (line.toLowerCase().contains("linux amd64"))
2538 linux64Version = lineVersion;
2539 else if (line.toLowerCase().contains("linux i386"))
2540 linuxVersion = lineVersion;
2541 else if (line.toLowerCase().contains("default"))
2542 version = lineVersion;
2544 // Read the next line
2545 data = reply.readLine();
2548 // Now we need to determine what system we are on.
2549 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2550 version = winVersion;
2551 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2552 version = osxVersion;
2553 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2554 if (System.getProperty("os.arch").contains("amd64") ||
2555 System.getProperty("os.arch").contains("x86_64") ||
2556 System.getProperty("os.arch").contains("i686"))
2557 version = linux64Version;
2559 version = linuxVersion;
2563 if (Global.version.equals(version))
2566 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2568 if (dialog.remindMe())
2569 Global.setCheckVersionUpgrade(true);
2571 Global.setCheckVersionUpgrade(false);
2575 //***************************************************************
2576 //***************************************************************
2577 //** These functions deal with the Toolbar
2578 //***************************************************************
2579 //***************************************************************
2580 // Text in the search bar has been cleared
2581 private void searchFieldCleared() {
2584 // This is done because we want to force a reload of
2585 // images. Some images we may want to highlight the text.
2586 readOnlyCache.clear();
2587 inkNoteCache.clear();
2589 QWebSettings.setMaximumPagesInCache(0);
2590 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2592 searchField.setEditText("");
2593 saveNoteColumnPositions();
2594 saveNoteIndexWidth();
2595 noteIndexUpdated(true);
2596 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2597 currentNote = listManager.getNoteIndex().get(0);
2598 currentNoteGuid = currentNote.getGuid();
2600 if (currentNote != null)
2601 loadNoteBrowserInformation(browserWindow);
2603 // text in the search bar changed. We only use this to tell if it was cleared,
2604 // otherwise we trigger off searchFieldChanged.
2605 @SuppressWarnings("unused")
2606 private void searchFieldTextChanged(String text) {
2607 QWebSettings.setMaximumPagesInCache(0);
2608 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2610 if (text.trim().equals("")) {
2611 searchFieldCleared();
2612 if (searchPerformed) {
2614 // This is done because we want to force a reload of
2615 // images. Some images we may want to highlight the text.
2617 readOnlyCache.clear();
2618 inkNoteCache.clear();
2620 listManager.setEnSearch("");
2621 listManager.loadNotesIndex();
2622 refreshEvernoteNote(true);
2623 noteIndexUpdated(false);
2625 searchPerformed = false;
2628 // Text in the toolbar has changed
2629 private void searchFieldChanged() {
2630 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2632 readOnlyCache.clear();
2633 inkNoteCache.clear();
2634 saveNoteColumnPositions();
2635 saveNoteIndexWidth();
2636 String text = searchField.currentText();
2637 listManager.setEnSearch(text.trim());
2638 listManager.loadNotesIndex();
2639 //--->>> noteIndexUpdated(true);
2640 noteIndexUpdated(false);
2641 refreshEvernoteNote(true);
2642 searchPerformed = true;
2643 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2646 // Build the window tool bar
2647 private void setupToolBar() {
2648 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2649 toolBar = addToolBar(tr("Tool Bar"));
2650 menuBar.setupToolBarVisible();
2651 if (!Global.isWindowVisible("toolBar"))
2652 toolBar.setVisible(false);
2654 toolBar.setVisible(true);
2656 prevButton = toolBar.addAction("Previous");
2657 QIcon prevIcon = new QIcon(iconPath+"back.png");
2658 prevButton.setIcon(prevIcon);
2659 prevButton.triggered.connect(this, "previousViewedAction()");
2660 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2662 nextButton = toolBar.addAction("Next");
2663 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2664 nextButton.setIcon(nextIcon);
2665 nextButton.triggered.connect(this, "nextViewedAction()");
2666 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2668 upButton = toolBar.addAction("Up");
2669 QIcon upIcon = new QIcon(iconPath+"up.png");
2670 upButton.setIcon(upIcon);
2671 upButton.triggered.connect(this, "upAction()");
2672 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2675 downButton = toolBar.addAction("Down");
2676 QIcon downIcon = new QIcon(iconPath+"down.png");
2677 downButton.setIcon(downIcon);
2678 downButton.triggered.connect(this, "downAction()");
2679 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2681 synchronizeButton = toolBar.addAction("Synchronize");
2682 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2683 synchronizeIconAngle = 0;
2684 synchronizeButton.triggered.connect(this, "evernoteSync()");
2685 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2687 printButton = toolBar.addAction("Print");
2688 QIcon printIcon = new QIcon(iconPath+"print.png");
2689 printButton.setIcon(printIcon);
2690 printButton.triggered.connect(this, "printNote()");
2691 togglePrintButton(Global.isToolbarButtonVisible("print"));
2693 tagButton = toolBar.addAction("Tag");
2694 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2695 tagButton.setIcon(tagIcon);
2696 tagButton.triggered.connect(browserWindow, "modifyTags()");
2697 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2699 attributeButton = toolBar.addAction("Attributes");
2700 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2701 attributeButton.setIcon(attributeIcon);
2702 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2703 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2705 emailButton = toolBar.addAction("Email");
2706 QIcon emailIcon = new QIcon(iconPath+"email.png");
2707 emailButton.setIcon(emailIcon);
2708 emailButton.triggered.connect(this, "emailNote()");
2709 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2711 deleteButton = toolBar.addAction("Delete");
2712 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2713 deleteButton.setIcon(deleteIcon);
2714 deleteButton.triggered.connect(this, "deleteNote()");
2715 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2717 newButton = toolBar.addAction("New");
2718 QIcon newIcon = new QIcon(iconPath+"new.png");
2719 newButton.triggered.connect(this, "addNote()");
2720 newButton.setIcon(newIcon);
2721 toggleNewButton(Global.isToolbarButtonVisible("new"));
2723 allNotesButton = toolBar.addAction("All Notes");
2724 QIcon allIcon = new QIcon(iconPath+"books.png");
2725 allNotesButton.triggered.connect(this, "allNotes()");
2726 allNotesButton.setIcon(allIcon);
2727 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2729 toolBar.addSeparator();
2730 toolBar.addWidget(new QLabel(tr("Quota:")));
2731 toolBar.addWidget(quotaBar);
2732 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2734 toolBar.addSeparator();
2737 zoomSpinner = new QSpinBox();
2738 zoomSpinner.setMinimum(10);
2739 zoomSpinner.setMaximum(1000);
2740 zoomSpinner.setAccelerated(true);
2741 zoomSpinner.setSingleStep(10);
2742 zoomSpinner.setValue(100);
2743 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2744 toolBar.addWidget(new QLabel(tr("Zoom")));
2745 toolBar.addWidget(zoomSpinner);
2747 //toolBar.addWidget(new QLabel(" "));
2748 toolBar.addSeparator();
2749 toolBar.addWidget(new QLabel(tr(" Search:")));
2750 toolBar.addWidget(searchField);
2751 QSizePolicy sizePolicy = new QSizePolicy();
2752 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2753 searchField.setSizePolicy(sizePolicy);
2754 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2756 searchClearButton = toolBar.addAction("Search Clear");
2757 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2758 searchClearButton.setIcon(searchClearIcon);
2759 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2760 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2762 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2764 // Update the sychronize button picture
2766 public QMenu createPopupMenu() {
2767 QMenu contextMenu = super.createPopupMenu();
2769 contextMenu.addSeparator();
2770 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2771 contextMenu.addAction(prevAction);
2772 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2774 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2775 contextMenu.addAction(nextAction);
2776 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2778 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2779 contextMenu.addAction(upAction);
2780 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2782 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2783 contextMenu.addAction(downAction);
2784 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2786 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2787 contextMenu.addAction(synchronizeAction);
2788 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2790 QAction printAction = addContextAction("print", tr("Print"));
2791 contextMenu.addAction(printAction);
2792 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2794 QAction tagAction = addContextAction("tag", tr("Tag"));
2795 contextMenu.addAction(tagAction);
2796 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2798 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2799 contextMenu.addAction(attributeAction);
2800 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2802 QAction emailAction = addContextAction("email", tr("Email"));
2803 contextMenu.addAction(emailAction);
2804 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2806 QAction deleteAction = addContextAction("delete", tr("Delete"));
2807 contextMenu.addAction(deleteAction);
2808 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2810 QAction newAction = addContextAction("new", tr("Add"));
2811 contextMenu.addAction(newAction);
2812 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2814 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2815 contextMenu.addAction(allNotesAction);
2816 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2818 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2819 contextMenu.addAction(searchClearAction);
2820 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2825 private QAction addContextAction(String config, String name) {
2826 QAction newAction = new QAction(this);
2827 newAction.setText(name);
2828 newAction.setCheckable(true);
2829 newAction.setChecked(Global.isToolbarButtonVisible(config));
2832 private void togglePrevArrowButton(Boolean toggle) {
2833 prevButton.setVisible(toggle);
2834 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2836 private void toggleNextArrowButton(Boolean toggle) {
2837 nextButton.setVisible(toggle);
2838 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2840 private void toggleUpArrowButton(Boolean toggle) {
2841 upButton.setVisible(toggle);
2842 Global.saveToolbarButtonsVisible("upArrow", toggle);
2844 private void toggleDownArrowButton(Boolean toggle) {
2845 downButton.setVisible(toggle);
2846 Global.saveToolbarButtonsVisible("downArrow", toggle);
2848 private void toggleSynchronizeButton(Boolean toggle) {
2849 synchronizeButton.setVisible(toggle);
2850 Global.saveToolbarButtonsVisible("synchronize", toggle);
2852 private void togglePrintButton(Boolean toggle) {
2853 printButton.setVisible(toggle);
2854 Global.saveToolbarButtonsVisible("print", toggle);
2856 private void toggleTagButton(Boolean toggle) {
2857 tagButton.setVisible(toggle);
2858 Global.saveToolbarButtonsVisible("tag", toggle);
2860 private void toggleAttributeButton(Boolean toggle) {
2861 attributeButton.setVisible(toggle);
2862 Global.saveToolbarButtonsVisible("attribute", toggle);
2864 private void toggleEmailButton(Boolean toggle) {
2865 emailButton.setVisible(toggle);
2866 Global.saveToolbarButtonsVisible("email", toggle);
2868 private void toggleDeleteButton(Boolean toggle) {
2869 deleteButton.setVisible(toggle);
2870 Global.saveToolbarButtonsVisible("delete", toggle);
2872 private void toggleNewButton(Boolean toggle) {
2873 newButton.setVisible(toggle);
2874 Global.saveToolbarButtonsVisible("new", toggle);
2876 private void toggleAllNotesButton(Boolean toggle) {
2877 allNotesButton.setVisible(toggle);
2878 Global.saveToolbarButtonsVisible("allNotes", toggle);
2880 private void toggleSearchClearButton(Boolean toggle) {
2881 searchClearButton.setVisible(toggle);
2882 Global.saveToolbarButtonsVisible("searchClear", toggle);
2889 @SuppressWarnings("unused")
2890 private void updateSyncButton() {
2892 if (syncIcons == null) {
2893 syncIcons = new ArrayList<QPixmap>();
2895 synchronizeIconAngle = 0;
2896 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2898 for (int i=0; i<=360; i++) {
2899 QPixmap rotatedPix = new QPixmap(pix.size());
2900 QPainter p = new QPainter(rotatedPix);
2901 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2902 QSize size = pix.size();
2903 p.translate(size.width()/2, size.height()/2);
2906 p.setBackgroundMode(BGMode.OpaqueMode);
2907 p.translate(-size.width()/2, -size.height()/2);
2908 p.drawPixmap(0,0, pix);
2910 syncIcons.add(rotatedPix);
2914 synchronizeIconAngle++;
2915 if (synchronizeIconAngle > 359)
2916 synchronizeIconAngle=0;
2917 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2920 // Synchronize with Evernote
2921 @SuppressWarnings("unused")
2922 private void evernoteSync() {
2923 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2924 if (!Global.isConnected)
2926 if (Global.isConnected)
2927 synchronizeAnimationTimer.start(5);
2928 // synchronizeAnimationTimer.start(200);
2930 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2932 private void updateQuotaBar() {
2933 long limit = Global.getUploadLimit();
2934 long amount = Global.getUploadAmount();
2935 if (amount>0 && limit>0) {
2936 int percent =(int)(amount*100/limit);
2937 quotaBar.setValue(percent);
2939 quotaBar.setValue(0);
2942 @SuppressWarnings("unused")
2943 private void zoomChanged() {
2944 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2947 //****************************************************************
2948 //****************************************************************
2949 //* System Tray functions
2950 //****************************************************************
2951 //****************************************************************
2952 private void trayToggleVisible() {
2957 if (windowMaximized)
2964 @SuppressWarnings("unused")
2965 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2966 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2967 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2968 trayToggleVisible();
2973 //***************************************************************
2974 //***************************************************************
2975 //** These functions deal with the trash tree
2976 //***************************************************************
2977 //***************************************************************
2978 // Setup the tree containing the trash.
2979 @SuppressWarnings("unused")
2980 private void trashTreeSelection() {
2981 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2983 clearNotebookFilter();
2985 clearAttributeFilter();
2986 clearSavedSearchFilter();
2988 String tempGuid = currentNoteGuid;
2990 // currentNoteGuid = "";
2991 currentNote = new Note();
2992 selectedNoteGUIDs.clear();
2993 listManager.getSelectedNotebooks().clear();
2994 listManager.getSelectedTags().clear();
2995 listManager.setSelectedSavedSearch("");
2996 browserWindow.clear();
2998 // toggle the add buttons
2999 newButton.setEnabled(!newButton.isEnabled());
3000 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3001 menuBar.noteAdd.setVisible(true);
3003 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3004 if (selections.size() == 0) {
3005 currentNoteGuid = trashNoteGuid;
3006 trashNoteGuid = tempGuid;
3007 Global.showDeleted = false;
3008 menuBar.noteRestoreAction.setEnabled(false);
3009 menuBar.noteRestoreAction.setVisible(false);
3012 currentNoteGuid = trashNoteGuid;
3013 trashNoteGuid = tempGuid;
3014 menuBar.noteRestoreAction.setEnabled(true);
3015 menuBar.noteRestoreAction.setVisible(true);
3016 Global.showDeleted = true;
3018 listManager.loadNotesIndex();
3019 noteIndexUpdated(false);
3020 //// browserWindow.setEnabled(newButton.isEnabled());
3021 browserWindow.setReadOnly(!newButton.isEnabled());
3022 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3024 // Empty the trash file
3025 @SuppressWarnings("unused")
3026 private void emptyTrash() {
3027 // browserWindow.clear();
3028 listManager.emptyTrash();
3029 if (trashTree.selectedItems().size() > 0) {
3030 listManager.getSelectedNotebooks().clear();
3031 listManager.getSelectedTags().clear();
3032 listManager.setSelectedSavedSearch("");
3033 newButton.setEnabled(!newButton.isEnabled());
3034 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3035 menuBar.noteAdd.setVisible(true);
3036 browserWindow.clear();
3039 clearNotebookFilter();
3040 clearSavedSearchFilter();
3041 clearAttributeFilter();
3043 Global.showDeleted = false;
3044 menuBar.noteRestoreAction.setEnabled(false);
3045 menuBar.noteRestoreAction.setVisible(false);
3047 listManager.loadNotesIndex();
3048 //--->>> noteIndexUpdated(true);
3049 noteIndexUpdated(false);
3052 // Show/Hide trash window
3053 private void toggleTrashWindow() {
3054 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3055 if (trashTree.isVisible())
3059 menuBar.hideTrash.setChecked(trashTree.isVisible());
3061 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3062 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3064 private void clearTrashFilter() {
3065 Global.showDeleted = false;
3066 newButton.setEnabled(true);
3067 menuBar.noteAdd.setEnabled(true);
3068 menuBar.noteAdd.setVisible(true);
3069 trashTree.blockSignals(true);
3070 trashTree.clearSelection();
3071 trashTree.blockSignals(false);
3076 //***************************************************************
3077 //***************************************************************
3078 //** These functions deal with connection settings
3079 //***************************************************************
3080 //***************************************************************
3081 // SyncRunner had a problem and things are disconnected
3082 @SuppressWarnings("unused")
3083 private void remoteErrorDisconnect() {
3084 menuBar.connectAction.setText(tr("Connect"));
3085 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3086 menuBar.synchronizeAction.setEnabled(false);
3087 Global.isConnected = false;
3088 synchronizeAnimationTimer.stop();
3091 // Do a manual connect/disconnect
3092 private void remoteConnect() {
3093 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3095 if (Global.isConnected) {
3096 Global.isConnected = false;
3097 syncRunner.enDisconnect();
3098 setupConnectMenuOptions();
3103 AESEncrypter aes = new AESEncrypter();
3105 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3106 } catch (FileNotFoundException e) {
3107 // File not found, so we'll just get empty strings anyway.
3109 String userid = aes.getUserid();
3110 String password = aes.getPassword();
3111 if (!userid.equals("") && !password.equals("")) {
3112 Global.username = userid;
3113 Global.password = password;
3116 // Show the login dialog box
3117 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3118 LoginDialog login = new LoginDialog();
3121 if (!login.okPressed()) {
3125 Global.username = login.getUserid();
3126 Global.password = login.getPassword();
3128 syncRunner.username = Global.username;
3129 syncRunner.password = Global.password;
3130 syncRunner.userStoreUrl = Global.userStoreUrl;
3131 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3132 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3134 if (Global.getProxyValue("url").equals("")) {
3135 System.setProperty("http.proxyHost","") ;
3136 System.setProperty("http.proxyPort", "") ;
3137 System.setProperty("https.proxyHost","") ;
3138 System.setProperty("https.proxyPort", "") ;
3141 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3142 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3143 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3144 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3146 if (Global.getProxyValue("userid").equals("")) {
3147 Authenticator.setDefault(new Authenticator() {
3149 protected PasswordAuthentication getPasswordAuthentication() {
3151 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3157 syncRunner.enConnect();
3158 Global.isConnected = syncRunner.isConnected;
3160 setupConnectMenuOptions();
3161 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3163 private void setupConnectMenuOptions() {
3164 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3165 if (!Global.isConnected) {
3166 menuBar.connectAction.setText(tr("Connect"));
3167 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3168 menuBar.synchronizeAction.setEnabled(false);
3170 menuBar.connectAction.setText(tr("Disconnect"));
3171 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3172 menuBar.synchronizeAction.setEnabled(true);
3174 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3179 //***************************************************************
3180 //***************************************************************
3181 //** These functions deal with the GUI Attribute tree
3182 //***************************************************************
3183 //***************************************************************
3184 @SuppressWarnings("unused")
3185 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3187 // clearTagFilter();
3188 // clearNotebookFilter();
3190 // clearSavedSearchFilter();
3192 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3193 if (item.childCount() > 0) {
3194 item.setSelected(false);
3196 Global.createdBeforeFilter.reset();
3197 Global.createdSinceFilter.reset();
3198 Global.changedBeforeFilter.reset();
3199 Global.changedSinceFilter.reset();
3200 Global.containsFilter.reset();
3201 attributeTreeSelected = item;
3202 DateAttributeFilterTable f = null;
3203 f = findDateAttributeFilterTable(item.parent());
3205 f.select(item.parent().indexOfChild(item));
3207 Global.containsFilter.select(item.parent().indexOfChild(item));
3210 listManager.loadNotesIndex();
3211 noteIndexUpdated(false);
3214 attributeTreeSelected = null;
3215 item.setSelected(false);
3216 Global.createdBeforeFilter.reset();
3217 Global.createdSinceFilter.reset();
3218 Global.changedBeforeFilter.reset();
3219 Global.changedSinceFilter.reset();
3220 Global.containsFilter.reset();
3221 listManager.loadNotesIndex();
3222 noteIndexUpdated(false);
3224 // This determines what attribute filter we need, depending upon the selection
3225 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3226 if (w.parent() != null && w.childCount() > 0) {
3227 QTreeWidgetItem parent = w.parent();
3228 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3229 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3230 return Global.createdSinceFilter;
3231 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3232 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3233 return Global.createdBeforeFilter;
3234 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3235 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3236 return Global.changedSinceFilter;
3237 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3238 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3239 return Global.changedBeforeFilter;
3244 // Show/Hide attribute search window
3245 private void toggleAttributesWindow() {
3246 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3247 if (attributeTree.isVisible())
3248 attributeTree.hide();
3250 attributeTree.show();
3251 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3253 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3254 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3256 private void clearAttributeFilter() {
3257 Global.createdBeforeFilter.reset();
3258 Global.createdSinceFilter.reset();
3259 Global.changedBeforeFilter.reset();
3260 Global.changedSinceFilter.reset();
3261 Global.containsFilter.reset();
3262 attributeTreeSelected = null;
3263 attributeTree.blockSignals(true);
3264 attributeTree.clearSelection();
3265 attributeTree.blockSignals(false);
3269 //***************************************************************
3270 //***************************************************************
3271 //** These functions deal with the GUI Note index table
3272 //***************************************************************
3273 //***************************************************************
3274 // Initialize the note list table
3275 private void initializeNoteTable() {
3276 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3277 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3278 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3279 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3281 // Show/Hide trash window
3282 @SuppressWarnings("unused")
3283 private void toggleNoteListWindow() {
3284 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3285 if (noteTableView.isVisible())
3286 noteTableView.hide();
3288 noteTableView.show();
3289 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3291 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3292 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3294 // Handle the event that a user selects a note from the table
3295 @SuppressWarnings("unused")
3296 private void noteTableSelection() {
3297 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3299 if (historyGuids.size() == 0) {
3300 historyGuids.add(currentNoteGuid);
3301 historyPosition = 1;
3303 noteTableView.showColumn(Global.noteTableGuidPosition);
3305 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3306 if (!Global.isColumnVisible("guid"))
3307 noteTableView.hideColumn(Global.noteTableGuidPosition);
3309 if (selections.size() > 0) {
3311 menuBar.noteDuplicateAction.setEnabled(true);
3312 menuBar.noteOnlineHistoryAction.setEnabled(true);
3313 menuBar.noteMergeAction.setEnabled(true);
3314 selectedNoteGUIDs.clear();
3315 if (selections.size() != 1 || Global.showDeleted) {
3316 menuBar.noteDuplicateAction.setEnabled(false);
3318 if (selections.size() != 1 || !Global.isConnected) {
3319 menuBar.noteOnlineHistoryAction.setEnabled(false);
3321 if (selections.size() == 1) {
3322 menuBar.noteMergeAction.setEnabled(false);
3324 for (int i=0; i<selections.size(); i++) {
3325 int row = selections.get(i).row();
3327 upButton.setEnabled(false);
3329 upButton.setEnabled(true);
3330 if (row < listManager.getNoteTableModel().rowCount()-1)
3331 downButton.setEnabled(true);
3333 downButton.setEnabled(false);
3334 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3335 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3336 currentNoteGuid = (String)ix.values().toArray()[0];
3337 selectedNoteGUIDs.add(currentNoteGuid);
3341 nextButton.setEnabled(true);
3342 prevButton.setEnabled(true);
3344 int endPosition = historyGuids.size()-1;
3345 for (int j=historyPosition; j<=endPosition; j++) {
3346 historyGuids.remove(historyGuids.size()-1);
3348 historyGuids.add(currentNoteGuid);
3349 historyPosition = historyGuids.size();
3351 if (historyPosition <= 1)
3352 prevButton.setEnabled(false);
3353 if (historyPosition == historyGuids.size())
3354 nextButton.setEnabled(false);
3356 fromHistory = false;
3357 scrollToGuid(currentNoteGuid);
3358 refreshEvernoteNote(true);
3359 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3361 // Trigger a refresh when the note db has been updated
3362 private void noteIndexUpdated(boolean reload) {
3363 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3365 refreshEvernoteNoteList();
3366 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3367 noteTableView.load(reload);
3368 scrollToGuid(currentNoteGuid);
3369 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3371 // Called when the list of notes is updated
3372 private void refreshEvernoteNoteList() {
3373 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3374 browserWindow.setDisabled(false);
3375 if (selectedNoteGUIDs == null)
3376 selectedNoteGUIDs = new ArrayList<String>();
3377 selectedNoteGUIDs.clear(); // clear out old entries
3379 String saveCurrentNoteGuid = new String();
3380 String tempNoteGuid = new String();
3382 historyGuids.clear();
3383 historyPosition = 0;
3384 prevButton.setEnabled(false);
3385 nextButton.setEnabled(false);
3387 if (currentNoteGuid == null)
3388 currentNoteGuid = new String();
3390 //determine current note guid
3391 for (Note note : listManager.getNoteIndex()) {
3392 tempNoteGuid = note.getGuid();
3393 if (currentNoteGuid.equals(tempNoteGuid)) {
3394 saveCurrentNoteGuid = tempNoteGuid;
3398 if (listManager.getNoteIndex().size() == 0) {
3399 currentNoteGuid = "";
3401 browserWindow.clear();
3402 browserWindow.setDisabled(true);
3405 if (saveCurrentNoteGuid.equals("") && listManager.getNoteIndex().size() > 0) {
3406 currentNote = listManager.getNoteIndex().get(listManager.getNoteIndex().size()-1);
3407 currentNoteGuid = currentNote.getGuid();
3408 refreshEvernoteNote(true);
3410 //we can reload if note not dirty
3411 // refreshEvernoteNote(!noteDirty);
3412 refreshEvernoteNote(false);
3414 reloadTagTree(false);
3416 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3418 // Called when the previous arrow button is clicked
3419 @SuppressWarnings("unused")
3420 private void previousViewedAction() {
3421 if (!prevButton.isEnabled())
3423 if (historyPosition == 0)
3426 if (historyPosition <= 0)
3428 String historyGuid = historyGuids.get(historyPosition-1);
3430 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3431 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3432 if (modelIndex != null) {
3433 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3434 String tableGuid = (String)ix.values().toArray()[0];
3435 if (tableGuid.equals(historyGuid)) {
3436 noteTableView.selectRow(i);
3442 @SuppressWarnings("unused")
3443 private void nextViewedAction() {
3444 if (!nextButton.isEnabled())
3446 String historyGuid = historyGuids.get(historyPosition);
3449 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3450 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3451 if (modelIndex != null) {
3452 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3453 String tableGuid = (String)ix.values().toArray()[0];
3454 if (tableGuid.equals(historyGuid)) {
3455 noteTableView.selectRow(i);
3461 // Called when the up arrow is clicked
3462 @SuppressWarnings("unused")
3463 private void upAction() {
3464 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3465 int row = selections.get(0).row();
3467 noteTableView.selectRow(row-1);
3470 // Called when the down arrow is clicked
3471 @SuppressWarnings("unused")
3472 private void downAction() {
3473 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3474 int row = selections.get(0).row();
3475 int max = listManager.getNoteTableModel().rowCount();
3477 noteTableView.selectRow(row+1);
3480 // Update a tag string for a specific note in the list
3481 @SuppressWarnings("unused")
3482 private void updateListTags(String guid, List<String> tags) {
3483 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3484 StringBuffer tagBuffer = new StringBuffer();
3485 for (int i=0; i<tags.size(); i++) {
3486 tagBuffer.append(tags.get(i));
3487 if (i<tags.size()-1)
3488 tagBuffer.append(", ");
3491 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3492 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3493 if (modelIndex != null) {
3494 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3495 String tableGuid = (String)ix.values().toArray()[0];
3496 if (tableGuid.equals(guid)) {
3497 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3498 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3499 noteTableView.proxyModel.invalidate();
3504 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3506 // Update a title for a specific note in the list
3507 @SuppressWarnings("unused")
3508 private void updateListAuthor(String guid, String author) {
3509 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3511 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3512 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3513 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3514 if (modelIndex != null) {
3515 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3516 String tableGuid = (String)ix.values().toArray()[0];
3517 if (tableGuid.equals(guid)) {
3518 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3519 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3520 noteTableView.proxyModel.invalidate();
3526 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3528 private void updateListNoteNotebook(String guid, String notebook) {
3529 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3530 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3531 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3533 // Update a title for a specific note in the list
3534 @SuppressWarnings("unused")
3535 private void updateListSourceUrl(String guid, String url) {
3536 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3538 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3539 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3540 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3541 if (modelIndex != null) {
3542 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3543 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3544 String tableGuid = (String)ix.values().toArray()[0];
3545 if (tableGuid.equals(guid)) {
3546 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3547 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3548 noteTableView.proxyModel.invalidate();
3553 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3555 @SuppressWarnings("unused")
3556 private void updateListGuid(String oldGuid, String newGuid) {
3557 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3559 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3560 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3561 if (modelIndex != null) {
3562 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3563 String tableGuid = (String)ix.values().toArray()[0];
3564 if (tableGuid.equals(oldGuid)) {
3565 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3566 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3571 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3573 private void updateListTagName(String guid) {
3574 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3576 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3577 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3578 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3580 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3581 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3582 if (modelIndex != null) {
3583 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3584 String noteGuid = (String)ix.values().toArray()[0];
3585 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3586 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3587 i=listManager.getNoteTableModel().rowCount();
3593 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3595 private void removeListTagName(String guid) {
3596 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3598 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3599 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3600 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3601 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3602 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3605 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3606 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3607 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3608 if (modelIndex != null) {
3609 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3610 String noteGuid = (String)ix.values().toArray()[0];
3611 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3612 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3613 i=listManager.getNoteTableModel().rowCount();
3619 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3621 private void updateListNotebookName(String oldName, String newName) {
3622 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3624 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3625 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3626 if (modelIndex != null) {
3627 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3628 String tableName = (String)ix.values().toArray()[0];
3629 if (tableName.equalsIgnoreCase(oldName)) {
3630 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3634 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3636 @SuppressWarnings("unused")
3637 private void updateListDateCreated(String guid, QDateTime date) {
3638 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3640 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3641 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3642 if (modelIndex != null) {
3643 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3644 String tableGuid = (String)ix.values().toArray()[0];
3645 if (tableGuid.equals(guid)) {
3646 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3647 noteTableView.proxyModel.invalidate();
3652 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3654 @SuppressWarnings("unused")
3655 private void updateListDateSubject(String guid, QDateTime date) {
3656 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3658 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3659 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3660 if (modelIndex != null) {
3661 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3662 String tableGuid = (String)ix.values().toArray()[0];
3663 if (tableGuid.equals(guid)) {
3664 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3665 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3666 noteTableView.proxyModel.invalidate();
3671 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3673 private void updateListDateChanged(String guid, QDateTime date) {
3674 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3676 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3677 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3678 if (modelIndex != null) {
3679 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3680 String tableGuid = (String)ix.values().toArray()[0];
3681 if (tableGuid.equals(guid)) {
3682 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3683 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3688 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3690 private void updateListDateChanged() {
3691 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3692 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3693 updateListDateChanged(currentNoteGuid, date);
3694 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3697 private void scrollToCurrentGuid() {
3698 //scrollToGuid(currentNoteGuid);
3699 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3700 if (selections.size() == 0)
3702 QModelIndex index = selections.get(0);
3703 int row = selections.get(0).row();
3704 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3707 // Scroll to a particular index item
3708 private void scrollToGuid(String guid) {
3709 if (currentNote == null || guid == null)
3711 if (currentNote.isActive() && Global.showDeleted) {
3712 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3713 if (!listManager.getNoteIndex().get(i).isActive()) {
3714 currentNote = listManager.getNoteIndex().get(i);
3715 currentNoteGuid = currentNote.getGuid();
3716 i = listManager.getNoteIndex().size();
3721 if (!currentNote.isActive() && !Global.showDeleted) {
3722 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3723 if (listManager.getNoteIndex().get(i).isActive()) {
3724 currentNote = listManager.getNoteIndex().get(i);
3725 currentNoteGuid = currentNote.getGuid();
3726 i = listManager.getNoteIndex().size();
3732 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3733 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3734 if (currentNoteGuid.equals(index.data())) {
3735 // noteTableView.setCurrentIndex(index);
3736 noteTableView.selectRow(i);
3737 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3738 i=listManager.getNoteTableModel().rowCount();
3741 noteTableView.repaint();
3743 // Show/Hide columns
3744 private void showColumns() {
3745 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3746 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3747 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3748 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3749 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3750 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3751 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3752 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3753 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3754 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3755 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3757 // Title color has changed
3758 @SuppressWarnings("unused")
3759 private void titleColorChanged(Integer color) {
3760 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3762 QColor backgroundColor = new QColor();
3763 QColor foregroundColor = new QColor(QColor.black);
3764 backgroundColor.setRgb(color);
3766 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3767 foregroundColor.setRgb(QColor.white.rgb());
3769 if (selectedNoteGUIDs.size() == 0)
3770 selectedNoteGUIDs.add(currentNoteGuid);
3772 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3773 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3774 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3775 if (modelIndex != null) {
3776 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3777 String tableGuid = (String)ix.values().toArray()[0];
3778 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3779 for (int k=0; k<Global.noteTableColumnCount; k++) {
3780 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3781 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3782 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3784 i=listManager.getNoteTableModel().rowCount();
3789 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3791 // Wide list was chosen
3792 public void narrowListView() {
3793 saveNoteColumnPositions();
3794 saveNoteIndexWidth();
3796 int sortCol = noteTableView.proxyModel.sortColumn();
3797 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3798 Global.setSortColumn(sortCol);
3799 Global.setSortOrder(sortOrder);
3801 Global.setListView(Global.View_List_Narrow);
3803 menuBar.wideListView.blockSignals(true);
3804 menuBar.narrowListView.blockSignals(true);
3806 menuBar.wideListView.setChecked(false);
3807 menuBar.narrowListView.setChecked(true);
3809 menuBar.wideListView.blockSignals(false);
3810 menuBar.narrowListView.blockSignals(false);
3812 mainLeftRightSplitter.addWidget(noteTableView);
3813 mainLeftRightSplitter.addWidget(browserWindow);
3814 restoreWindowState(false);
3815 noteTableView.repositionColumns();
3816 noteTableView.resizeColumnWidths();
3817 noteTableView.resizeRowHeights();
3819 sortCol = Global.getSortColumn();
3820 sortOrder = Global.getSortOrder();
3821 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3824 noteTableView.load(false);
3825 scrollToCurrentGuid();
3827 public void wideListView() {
3828 int sortCol = noteTableView.proxyModel.sortColumn();
3829 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3830 Global.setSortColumn(sortCol);
3831 Global.setSortOrder(sortOrder);
3834 saveNoteColumnPositions();
3835 saveNoteIndexWidth();
3836 Global.setListView(Global.View_List_Wide);
3838 menuBar.wideListView.blockSignals(true);
3839 menuBar.narrowListView.blockSignals(true);
3841 menuBar.wideListView.setChecked(true);
3842 menuBar.narrowListView.setChecked(false);
3844 menuBar.wideListView.blockSignals(false);
3845 menuBar.narrowListView.blockSignals(false);
3846 browserIndexSplitter.setVisible(true);
3847 browserIndexSplitter.addWidget(noteTableView);
3848 browserIndexSplitter.addWidget(browserWindow);
3849 restoreWindowState(false);
3850 noteTableView.repositionColumns();
3851 noteTableView.resizeColumnWidths();
3852 noteTableView.resizeRowHeights();
3854 sortCol = Global.getSortColumn();
3855 sortOrder = Global.getSortOrder();
3856 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3859 noteTableView.load(false);
3860 scrollToCurrentGuid();
3864 //***************************************************************
3865 //***************************************************************
3866 //** External editor window functions
3867 //***************************************************************
3868 //***************************************************************
3869 private void listDoubleClick() {
3871 if (externalWindows.containsKey(currentNoteGuid)) {
3872 externalWindows.get(currentNoteGuid).raise();
3875 // We have a new external editor to create
3876 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3877 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3878 newBrowser.setWindowIcon(appIcon);
3879 externalWindows.put(currentNoteGuid, newBrowser);
3880 showEditorButtons(newBrowser.getBrowserWindow());
3881 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3882 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3883 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3884 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3885 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3886 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3888 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3889 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3890 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3894 @SuppressWarnings("unused")
3895 private void externalWindowTitleEdited(String guid, String text) {
3896 if (guid.equals(currentNoteGuid)) {
3897 browserWindow.setTitle(text);
3900 @SuppressWarnings({ "rawtypes", "unused" })
3901 private void externalWindowTagsEdited(String guid, List values) {
3902 StringBuffer line = new StringBuffer(100);
3903 for (int i=0; i<values.size(); i++) {
3905 line.append(Global.tagDelimeter+" ");
3906 line.append(values.get(i));
3908 if (guid.equals(currentNoteGuid)) {
3909 browserWindow.setTag(line.toString());
3912 @SuppressWarnings("unused")
3913 private void externalWindowClosing(String guid) {
3914 externalWindows.remove(guid);
3919 //***************************************************************
3920 //***************************************************************
3921 //** These functions deal with Note specific things
3922 //***************************************************************
3923 //***************************************************************
3924 @SuppressWarnings("unused")
3925 private void setNoteDirty() {
3926 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
3927 // Find if the note is being edited externally. If it is, update it.
3928 if (externalWindows.containsKey(currentNoteGuid)) {
3929 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3930 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
3931 ExternalBrowse window = externalWindows.get(currentNoteGuid);
3932 window.getBrowserWindow().getBrowser().setContent(unicode);
3935 // If the note is dirty, then it is unsynchronized by default.
3939 // Set the note as dirty and check if its status is synchronized in the display table
3941 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
3942 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
3946 // If this wasn't already marked as unsynchronized, then we need to update the table
3947 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
3948 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
3949 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3950 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3951 if (modelIndex != null) {
3952 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3953 String tableGuid = (String)ix.values().toArray()[0];
3954 if (tableGuid.equals(currentNoteGuid)) {
3955 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3961 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
3963 @SuppressWarnings("unused")
3964 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
3965 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3966 QByteArray unicode = codec.fromUnicode(content);
3967 noteCache.remove(guid);
3968 noteCache.put(guid, unicode.toString());
3969 if (guid.equals(currentNoteGuid)) {
3971 browserWindow.getBrowser().setContent(unicode);
3974 thumbnailRunner.addWork("GENERATE "+ guid);
3975 saveNote(guid, browser);
3979 private void saveNote() {
3981 saveNote(currentNoteGuid, browserWindow);
3982 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
3986 private void saveNote(String guid, BrowserWindow window) {
3987 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
3988 logger.log(logger.EXTREME, "Note is dirty.");
3991 logger.log(logger.EXTREME, "Saving to cache");
3992 QTextCodec codec = QTextCodec.codecForLocale();
3993 // QTextDecoder decoder = codec.makeDecoder();
3994 codec = QTextCodec.codecForName("UTF-8");
3995 QByteArray unicode = codec.fromUnicode(window.getContent());
3996 noteCache.put(guid, unicode.toString());
3998 logger.log(logger.EXTREME, "updating list manager");
3999 listManager.updateNoteContent(guid, window.getContent());
4000 logger.log(logger.EXTREME, "Updating title");
4001 listManager.updateNoteTitle(guid, window.getTitle());
4002 updateListDateChanged();
4004 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4005 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4006 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4007 currentNote = listManager.getNoteIndex().get(i);
4008 i = listManager.getNoteIndex().size();
4013 // Get a note from Evernote (and put it in the browser)
4014 private void refreshEvernoteNote(boolean reload) {
4015 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4017 if (Global.disableViewing) {
4018 browserWindow.setEnabled(false);
4023 if (Global.showDeleted)
4025 Global.cryptCounter =0;
4026 if (currentNoteGuid.equals("")) {
4027 browserWindow.setReadOnly(true);
4035 browserWindow.loadingData(true);
4037 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4038 if (currentNote == null)
4041 loadNoteBrowserInformation(browserWindow);
4044 private void loadNoteBrowserInformation(BrowserWindow browser) {
4045 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4046 formatter.setNote(currentNote, Global.pdfPreview());
4047 formatter.setHighlight(listManager.getEnSearch());
4049 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4050 js = new QByteArray();
4051 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4052 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4053 js.append("<style type=\"text/css\">.en-crypt-temp { border-collapse:collapse; border-style:solid; border-color:blue; padding:0.0mm 0.0mm 0.0mm 0.0mm; }</style>");
4054 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4055 js.append("<style> img { max-width:100%; }</style>");
4056 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4057 js.append("</head>");
4058 formatter.setNote(currentNote, Global.pdfPreview());
4059 js.append(formatter.rebuildNoteHTML());
4060 js.append("</HTML>");
4061 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4062 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4063 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4064 browser.getBrowser().setContent(js);
4065 noteCache.put(currentNoteGuid, js.toString());
4067 if (formatter.resourceError)
4068 resourceErrorMessage();
4069 readOnly = formatter.readOnly;
4070 inkNote = formatter.inkNote;
4072 readOnlyCache.put(currentNoteGuid, true);
4074 inkNoteCache.put(currentNoteGuid, true);
4076 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4077 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4078 js = new QByteArray(cachedContent);
4079 browser.getBrowser().setContent(js);
4080 if (readOnlyCache.containsKey(currentNoteGuid))
4082 if (inkNoteCache.containsKey(currentNoteGuid))
4085 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4086 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4089 if (readOnly || inkNote)
4090 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4092 browser.getBrowser().page().setContentEditable(true);
4093 browser.setReadOnly(readOnly);
4094 deleteButton.setEnabled(!readOnly);
4095 tagButton.setEnabled(!readOnly);
4096 menuBar.noteDelete.setEnabled(!readOnly);
4097 menuBar.noteTags.setEnabled(!readOnly);
4098 browser.setNote(currentNote);
4100 if (conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4101 deleteButton.setEnabled(false);
4102 menuBar.notebookDeleteAction.setEnabled(false);
4104 deleteButton.setEnabled(true);
4105 menuBar.notebookDeleteAction.setEnabled(true);
4108 // Build a list of non-closed notebooks
4109 List<Notebook> nbooks = new ArrayList<Notebook>();
4110 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4111 boolean found=false;
4112 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4113 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4117 nbooks.add(listManager.getNotebookIndex().get(i));
4120 browser.setTitle(currentNote.getTitle());
4121 browser.setTag(getTagNamesForNote(currentNote));
4122 browser.setAuthor(currentNote.getAttributes().getAuthor());
4124 browser.setAltered(currentNote.getUpdated());
4125 browser.setCreation(currentNote.getCreated());
4126 if (currentNote.getAttributes().getSubjectDate() > 0)
4127 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4129 browser.setSubjectDate(currentNote.getCreated());
4130 browser.setUrl(currentNote.getAttributes().getSourceURL());
4132 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4133 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4134 browser.setAllTags(tagList);
4136 browser.setCurrentTags(currentNote.getTagNames());
4138 scrollToGuid(currentNoteGuid);
4140 browser.loadingData(false);
4141 if (thumbnailViewer.isActiveWindow())
4144 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4145 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4148 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4150 // Save a generated thumbnail
4151 private void toggleNoteInformation() {
4152 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4153 browserWindow.toggleInformation();
4154 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4155 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4156 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4158 // Listener triggered when a print button is pressed
4159 @SuppressWarnings("unused")
4160 private void printNote() {
4161 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4163 QPrintDialog dialog = new QPrintDialog();
4164 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4165 QPrinter printer = dialog.printer();
4166 browserWindow.getBrowser().print(printer);
4168 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4171 // Listener triggered when the email button is pressed
4172 @SuppressWarnings("unused")
4173 private void emailNote() {
4174 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4176 if (Desktop.isDesktopSupported()) {
4177 Desktop desktop = Desktop.getDesktop();
4179 String text2 = browserWindow.getContentsToEmail();
4180 QUrl url = new QUrl("mailto:");
4181 url.addQueryItem("subject", currentNote.getTitle());
4182 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4183 url.addQueryItem("body", text2);
4184 QDesktopServices.openUrl(url);
4188 if (desktop.isSupported(Desktop.Action.MAIL)) {
4189 URI uriMailTo = null;
4191 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4192 String text = browserWindow.getContentsToEmail();
4193 //text = "<b>" +text +"</b>";
4194 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4195 +"&BODY=" +text, null);
4196 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4197 +"&ATTACHMENT=d:/test.pdf", null);
4198 desktop.mail(uriMailTo);
4199 } catch (URISyntaxException e) {
4200 e.printStackTrace();
4201 } catch (IOException e) {
4202 e.printStackTrace();
4209 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4211 // Reindex all notes
4212 @SuppressWarnings("unused")
4213 private void fullReindex() {
4214 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4215 indexRunner.addWork("REINDEXALL");
4216 setMessage(tr("Database will be reindexed."));
4217 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4219 // Listener when a user wants to reindex a specific note
4220 @SuppressWarnings("unused")
4221 private void reindexNote() {
4222 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4223 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4224 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4226 if (selectedNotebookGUIDs.size() > 1)
4227 setMessage(tr("Notes will be reindexed."));
4229 setMessage(tr("Note will be reindexed."));
4230 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4233 @SuppressWarnings("unused")
4234 private void deleteNote() {
4235 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4236 if (currentNote == null)
4238 if (currentNoteGuid.equals(""))
4241 // If we are deleting non-trash notes
4242 if (currentNote.isActive()) {
4243 if (Global.verifyDelete()) {
4244 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4245 QMessageBox.StandardButton.Yes,
4246 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4250 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4251 selectedNoteGUIDs.add(currentNoteGuid);
4252 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4253 listManager.deleteNote(selectedNoteGUIDs.get(i));
4256 // If we are deleting from the trash.
4257 if (Global.verifyDelete()) {
4258 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4259 QMessageBox.StandardButton.Yes,
4260 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4264 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4265 selectedNoteGUIDs.add(currentNoteGuid);
4266 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4267 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4268 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4269 if (modelIndex != null) {
4270 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4271 String tableGuid = (String)ix.values().toArray()[0];
4272 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4273 listManager.getNoteTableModel().removeRow(j);
4278 listManager.expungeNote(selectedNoteGUIDs.get(i));
4281 currentNoteGuid = "";
4282 listManager.loadNotesIndex();
4283 noteIndexUpdated(false);
4284 refreshEvernoteNote(true);
4285 scrollToGuid(currentNoteGuid);
4286 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4289 @SuppressWarnings("unused")
4290 private void addNote() {
4291 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4292 // browserWindow.setEnabled(true);
4293 browserWindow.setReadOnly(false);
4295 Calendar currentTime = new GregorianCalendar();
4296 StringBuffer noteString = new StringBuffer(100);
4297 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4298 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4301 if (Global.overrideDefaultFont()) {
4302 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4303 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4304 noteString.append("<br clear=\"none\" />\n");
4305 noteString.append("</span>\n</font>\n");
4307 noteString.append("<br clear=\"none\" />\n");
4308 noteString.append("</en-note>");
4310 Long l = new Long(currentTime.getTimeInMillis());
4311 String randint = new String(Long.toString(l));
4313 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4315 // for the first non-archived notebook. Finally, if nothing else we
4316 // pick the first notebook in the list.
4317 String notebook = null;
4318 listManager.getNotebookIndex().get(0).getGuid();
4319 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4320 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4321 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4322 notebook = currentSelectedNotebook.text(2);
4324 boolean found = false;
4325 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4326 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4327 boolean match = false;
4328 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4329 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4331 j = listManager.getArchiveNotebookIndex().size();
4335 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4337 // Now we have a list of good notebooks, so we can look for the default
4339 for (int i=0; i<goodNotebooks.size(); i++) {
4340 if (goodNotebooks.get(i).isDefaultNotebook()) {
4341 notebook = goodNotebooks.get(i).getGuid();
4343 i = goodNotebooks.size();
4347 if (goodNotebooks.size() > 0 && !found)
4348 notebook = goodNotebooks.get(0).getGuid();
4351 notebook = listManager.getNotebookIndex().get(0).getGuid();
4354 Note newNote = new Note();
4355 newNote.setUpdateSequenceNum(0);
4356 newNote.setGuid(randint);
4357 newNote.setNotebookGuid(notebook);
4358 newNote.setTitle("");
4359 newNote.setContent(noteString.toString());
4360 newNote.setDeleted(0);
4361 newNote.setCreated(System.currentTimeMillis());
4362 newNote.setUpdated(System.currentTimeMillis());
4363 newNote.setActive(true);
4364 NoteAttributes na = new NoteAttributes();
4365 na.setLatitude(0.0);
4366 na.setLongitude(0.0);
4367 na.setAltitude(0.0);
4368 newNote.setAttributes(new NoteAttributes());
4369 newNote.setTagGuids(new ArrayList<String>());
4370 newNote.setTagNames(new ArrayList<String>());
4372 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4373 if (Global.newNoteWithSelectedTags()) {
4374 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4375 QTreeWidgetItem currentSelection;
4376 for (int i=0; i<selections.size(); i++) {
4377 currentSelection = selections.get(i);
4378 newNote.getTagGuids().add(currentSelection.text(2));
4379 newNote.getTagNames().add(currentSelection.text(0));
4383 conn.getNoteTable().addNote(newNote, true);
4384 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4385 listManager.addNote(newNote);
4386 // noteTableView.insertRow(newNote, true, -1);
4388 currentNote = newNote;
4389 currentNoteGuid = currentNote.getGuid();
4390 refreshEvernoteNote(true);
4391 listManager.countNotebookResults(listManager.getNoteIndex());
4392 browserWindow.titleLabel.setFocus();
4393 browserWindow.titleLabel.selectAll();
4394 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4396 // If the window is hidden, then we want to popup this in an external window &
4399 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4401 // Restore a note from the trash;
4402 @SuppressWarnings("unused")
4403 private void restoreNote() {
4405 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4406 selectedNoteGUIDs.add(currentNoteGuid);
4407 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4408 listManager.restoreNote(selectedNoteGUIDs.get(i));
4410 currentNoteGuid = "";
4411 listManager.loadNotesIndex();
4412 noteIndexUpdated(false);
4415 // Search a note for specific txt
4416 @SuppressWarnings("unused")
4417 private void findText() {
4419 find.setFocusOnTextField();
4421 @SuppressWarnings("unused")
4422 private void doFindText() {
4423 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4426 @SuppressWarnings("unused")
4427 private void updateNoteTitle(String guid, String title) {
4428 listManager.setNoteSynchronized(guid, false);
4430 // Signal received that note content has changed. Normally we just need the guid to remove
4431 // it from the cache.
4432 @SuppressWarnings("unused")
4433 private void invalidateNoteCache(String guid, String content) {
4434 String v = noteCache.remove(guid);
4435 // if (guid.equals(currentNoteGuid) && !noteDirty)
4436 refreshEvernoteNote(true);
4438 // Signal received that a note guid has changed
4439 @SuppressWarnings("unused")
4440 private void noteGuidChanged(String oldGuid, String newGuid) {
4441 if (noteCache.containsKey(oldGuid)) {
4442 if (!oldGuid.equals(currentNoteGuid)) {
4443 String cache = noteCache.get(oldGuid);
4444 noteCache.put(newGuid, cache);
4445 noteCache.remove(oldGuid);
4447 noteCache.remove(oldGuid);
4448 noteCache.put(newGuid, browserWindow.getContent());
4452 listManager.updateNoteGuid(oldGuid, newGuid, false);
4453 if (currentNoteGuid.equals(oldGuid)) {
4454 if (currentNote != null)
4455 currentNote.setGuid(newGuid);
4456 currentNoteGuid = newGuid;
4459 if (externalWindows.containsKey(oldGuid)) {
4460 ExternalBrowse b = externalWindows.get(oldGuid);
4461 externalWindows.remove(oldGuid);
4462 b.getBrowserWindow().getNote().setGuid(newGuid);
4463 externalWindows.put(newGuid, b);
4466 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4467 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4468 noteTableView.proxyModel.addGuid(newGuid);
4469 i=listManager.getNoteIndex().size();
4473 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4474 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4475 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4476 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4480 // Toggle the note editor button bar
4481 private void toggleEditorButtonBar() {
4482 if (browserWindow.buttonsVisible) {
4483 browserWindow.hideButtons();
4484 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4485 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4487 browserWindow.buttonsVisible = true;
4488 showEditorButtons(browserWindow);
4490 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4492 // Show editor buttons
4493 private void showEditorButtons(BrowserWindow browser) {
4494 browser.buttonLayout.setVisible(true);
4495 browser.undoAction.setVisible(false);
4497 browser.undoButton.setVisible(false);
4499 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4500 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4501 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4502 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4503 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4504 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4505 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4506 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4507 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4508 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4509 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4510 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4511 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4512 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4513 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4514 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4515 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4516 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4517 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4518 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4519 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4520 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4521 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4523 private void duplicateNote(String guid) {
4525 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
4526 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4527 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4528 oldNote.setResources(resList);
4529 duplicateNote(oldNote);
4531 private void duplicateNote(Note oldNote) {
4533 // Now that we have a good notebook guid, we need to move the conflicting note
4534 // to the local notebook
4535 Calendar currentTime = new GregorianCalendar();
4536 Long l = new Long(currentTime.getTimeInMillis());
4537 String newGuid = new String(Long.toString(l));
4539 Note newNote = oldNote.deepCopy();
4540 newNote.setUpdateSequenceNum(0);
4541 newNote.setGuid(newGuid);
4542 newNote.setDeleted(0);
4543 newNote.setActive(true);
4544 List<Resource> resList = oldNote.getResources();
4545 if (resList == null)
4546 resList = new ArrayList<Resource>();
4548 for (int i=0; i<resList.size(); i++) {
4550 while (l == prevGuid) {
4551 currentTime = new GregorianCalendar();
4552 l = new Long(currentTime.getTimeInMillis());
4555 String newResGuid = new String(Long.toString(l));
4556 resList.get(i).setNoteGuid(newGuid);
4557 resList.get(i).setGuid(newResGuid);
4558 resList.get(i).setUpdateSequenceNum(0);
4559 resList.get(i).setActive(true);
4560 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
4562 newNote.setResources(resList);
4563 listManager.addNote(newNote);
4564 conn.getNoteTable().addNote(newNote, true);
4565 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4566 noteTableView.insertRow(newNote, true, -1);
4567 listManager.countNotebookResults(listManager.getNoteIndex());
4571 @SuppressWarnings("unused")
4572 private void allNotes() {
4573 clearAttributeFilter();
4574 clearNotebookFilter();
4575 clearSavedSearchFilter();
4578 searchField.clear();
4579 if (Global.mimicEvernoteInterface) {
4580 notebookTree.selectGuid("");
4582 notebookTreeSelection();
4585 @SuppressWarnings("unused")
4586 private void mergeNotes() {
4587 logger.log(logger.HIGH, "Merging notes");
4590 String masterGuid = null;
4591 List<String> sources = new ArrayList<String>();
4593 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4594 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4595 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4596 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4598 masterGuid = (String)ix.values().toArray()[0];
4600 sources.add((String)ix.values().toArray()[0]);
4603 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4604 logger.log(logger.EXTREME, "Children count: "+sources.size());
4605 mergeNoteContents(masterGuid, sources);
4606 currentNoteGuid = masterGuid;
4607 noteIndexUpdated(false);
4608 refreshEvernoteNote(true);
4611 private void mergeNoteContents(String targetGuid, List<String> sources) {
4612 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4613 String newContent = target.getContent();
4614 newContent = newContent.replace("</en-note>", "<br></br>");
4616 for (int i=0; i<sources.size(); i++) {
4617 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4618 if (source.isSetTitle()) {
4619 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4621 String sourceContent = source.getContent();
4622 logger.log(logger.EXTREME, "Merging contents into note");
4623 logger.log(logger.EXTREME, sourceContent);
4624 logger.log(logger.EXTREME, "End of content");
4625 int startOfNote = sourceContent.indexOf("<en-note>");
4626 sourceContent = sourceContent.substring(startOfNote+9);
4627 int endOfNote = sourceContent.indexOf("</en-note>");
4628 sourceContent = sourceContent.substring(0,endOfNote);
4629 newContent = newContent + sourceContent;
4630 logger.log(logger.EXTREME, "New note content");
4631 logger.log(logger.EXTREME, newContent);
4632 logger.log(logger.EXTREME, "End of content");
4633 for (int j=0; j<source.getResourcesSize(); j++) {
4634 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4635 Resource r = source.getResources().get(j);
4636 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4638 Calendar currentTime = new GregorianCalendar();
4639 Long l = new Long(currentTime.getTimeInMillis());
4643 while (l == prevGuid) {
4644 currentTime = new GregorianCalendar();
4645 l = new Long(currentTime.getTimeInMillis());
4647 String newResGuid = new String(Long.toString(l));
4648 newRes.setNoteGuid(targetGuid);
4649 newRes.setGuid(newResGuid);
4650 newRes.setUpdateSequenceNum(0);
4651 newRes.setActive(true);
4652 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4655 logger.log(logger.EXTREME, "Updating note");
4656 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4657 for (int i=0; i<sources.size(); i++) {
4658 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4659 listManager.deleteNote(sources.get(i));
4661 logger.log(logger.EXTREME, "Exiting merge note");
4663 // A resource within a note has had a guid change
4664 @SuppressWarnings("unused")
4665 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4666 if (!oldGuid.equals(newGuid))
4667 Global.resourceMap.put(oldGuid, newGuid);
4669 // View a thumbnail of the note
4670 public void thumbnailView() {
4672 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4673 QFile thumbnail = new QFile(thumbnailName);
4674 if (!thumbnail.exists()) {
4676 QImage img = new QImage();
4677 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4678 thumbnailViewer.setThumbnail(img);
4680 thumbnailViewer.setThumbnail(thumbnailName);
4681 if (!thumbnailViewer.isVisible())
4682 thumbnailViewer.showFullScreen();
4684 // An error happened while saving a note. Inform the user
4685 @SuppressWarnings("unused")
4686 private void saveRunnerError(String guid, String msg) {
4688 String title = "*Unknown*";
4689 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4690 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4691 title = listManager.getMasterNoteIndex().get(i).getTitle();
4692 i=listManager.getMasterNoteIndex().size();
4695 msg = "An error has happened while saving the note \"" +title+
4696 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4697 "As a result, changes to the note may not be saved properly in the database."+
4698 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4699 "\nbe lost. Please review the note to recover any critical data before restarting.";
4701 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4704 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4705 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4706 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4707 // Find an idle preview object
4708 for (int i=0; i<thumbGenerators.size(); i++) {
4709 if (thumbGenerators.get(i).mutex.tryLock()) {
4710 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4711 thumbGenerators.get(i).loadContent(guid, html, zoom);
4715 if (thumbGenerators.size() >= 1) {
4716 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4720 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4721 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4722 thumbGenerators.add(preview);
4724 if (preview.mutex.tryLock()) {
4725 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4726 preview.loadContent(guid, html, zoom);
4728 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4733 //**********************************************************
4734 //**********************************************************
4735 //* Online user actions
4736 //**********************************************************
4737 //**********************************************************
4738 private void setupOnlineMenu() {
4739 if (!Global.isConnected) {
4740 menuBar.noteOnlineHistoryAction.setEnabled(false);
4741 menuBar.selectiveSyncAction.setEnabled(false);
4744 menuBar.noteOnlineHistoryAction.setEnabled(true);
4745 menuBar.selectiveSyncAction.setEnabled(true);
4748 @SuppressWarnings("unused")
4749 private void viewNoteHistory() {
4750 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4752 if (currentNote.getUpdateSequenceNum() == 0) {
4753 setMessage(tr("Note has never been synchronized."));
4754 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4758 setMessage(tr("Getting Note History"));
4760 Note currentOnlineNote = null;
4763 if (Global.isPremium())
4764 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4766 versions = new ArrayList<NoteVersionId>();
4767 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4768 } catch (EDAMUserException e) {
4769 setMessage("EDAMUserException: " +e.getMessage());
4771 } catch (EDAMSystemException e) {
4772 setMessage("EDAMSystemException: " +e.getMessage());
4774 } catch (EDAMNotFoundException e) {
4775 setMessage(tr("Note not found on server."));
4776 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4778 } catch (TException e) {
4779 setMessage("EDAMTransactionException: " +e.getMessage());
4783 // If we've gotten this far, we have a good note.
4784 if (historyWindow == null) {
4785 historyWindow = new OnlineNoteHistory(logger, conn);
4786 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4787 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4788 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4790 historyWindow.historyCombo.clear();
4792 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4793 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4795 historyWindow.setCurrent(isDirty);
4797 loadHistoryWindowContent(currentOnlineNote);
4798 historyWindow.load(versions);
4799 setMessage(tr("History retrieved"));
4801 historyWindow.exec();
4803 private Note reloadHistoryWindow(String selection) {
4805 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4806 String dateTimeFormat = new String(fmt);
4807 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4811 for (int i=0; i<versions.size(); i++) {
4812 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4813 if (versionDate.toString().equals(selection))
4817 if (index > -1 || selection.indexOf("Current") > -1) {
4818 Note historyNote = null;
4821 usn = versions.get(index).getUpdateSequenceNum();
4822 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4824 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4825 } catch (EDAMUserException e) {
4826 setMessage("EDAMUserException: " +e.getMessage());
4829 } catch (EDAMSystemException e) {
4830 setMessage("EDAMSystemException: " +e.getMessage());
4833 } catch (EDAMNotFoundException e) {
4834 setMessage("EDAMNotFoundException: " +e.getMessage());
4837 } catch (TException e) {
4838 setMessage("EDAMTransactionException: " +e.getMessage());
4844 if (historyNote != null)
4845 historyWindow.setContent(historyNote);
4851 private void loadHistoryWindowContent(Note note) {
4852 note.setUpdateSequenceNum(0);
4853 historyWindow.setContent(note);
4855 @SuppressWarnings("unused")
4856 private void restoreHistoryNoteAsNew() {
4857 setMessage(tr("Restoring as new note."));
4858 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4859 setMessage(tr("Note has been restored as a new note."));
4861 @SuppressWarnings("unused")
4862 private void restoreHistoryNote() {
4863 setMessage(tr("Restoring note."));
4864 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
4865 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
4868 for (int i=0; i<n.getResourcesSize(); i++) {
4869 n.getResources().get(i).setActive(true);
4870 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
4872 listManager.addNote(n);
4873 conn.getNoteTable().addNote(n, true);
4874 refreshEvernoteNote(true);
4875 setMessage(tr("Note has been restored."));
4877 @SuppressWarnings("unused")
4878 private void setupSelectiveSync() {
4880 // Get a list of valid notebooks
4881 List<Notebook> notebooks = null;
4882 List<Tag> tags = null;
4884 notebooks = syncRunner.noteStore.listNotebooks(syncRunner.authToken);
4885 tags = syncRunner.noteStore.listTags(syncRunner.authToken);
4886 } catch (EDAMUserException e) {
4887 setMessage("EDAMUserException: " +e.getMessage());
4889 } catch (EDAMSystemException e) {
4890 setMessage("EDAMSystemException: " +e.getMessage());
4892 } catch (TException e) {
4893 setMessage("EDAMTransactionException: " +e.getMessage());
4897 // Split up notebooks into synchronized & non-synchronized
4898 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
4899 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4901 for (int i=notebooks.size()-1; i>=0; i--) {
4902 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
4903 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
4904 ignoredBooks.add(notebooks.get(i));
4905 j=dbIgnoredNotebooks.size();
4910 // split up tags into synchronized & non-synchronized
4911 List<Tag> ignoredTags = new ArrayList<Tag>();
4912 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
4914 for (int i=tags.size()-1; i>=0; i--) {
4915 for (int j=0; j<dbIgnoredTags.size(); j++) {
4916 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
4917 ignoredTags.add(tags.get(i));
4918 j=dbIgnoredTags.size();
4923 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags);
4925 if (!ignore.okClicked())
4930 // Clear out old notebooks & add the new ones
4931 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4932 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
4933 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
4936 List<String> newNotebooks = new ArrayList<String>();
4937 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
4938 String text = ignore.getIgnoredBookList().takeItem(i).text();
4939 for (int j=0; j<notebooks.size(); j++) {
4940 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
4941 Notebook n = notebooks.get(j);
4942 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
4944 newNotebooks.add(n.getGuid());
4949 // Clear out old tags & add new ones
4950 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
4951 for (int i=0; i<oldIgnoreTags.size(); i++) {
4952 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
4955 List<String> newTags = new ArrayList<String>();
4956 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
4957 String text = ignore.getIgnoredTagList().takeItem(i).text();
4958 for (int j=0; j<tags.size(); j++) {
4959 if (tags.get(j).getName().equalsIgnoreCase(text)) {
4960 Tag t = tags.get(j);
4961 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
4962 newTags.add(t.getGuid());
4968 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags);
4974 //**********************************************************
4975 //**********************************************************
4976 //* XML Modifying methods
4977 //**********************************************************
4978 //**********************************************************
4979 // An error has happended fetching a resource. let the user know
4980 private void resourceErrorMessage() {
4983 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
4984 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
4985 "In a perfect world this wouldn't happen, but it has.\n" +
4986 "It is embarasing when a program like me, designed to save all your\n"+
4987 "precious data, has a problem finding data.\n\n" +
4988 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
4989 "In the mean time, I'm not going to let you make changes to this note.\n" +
4990 "Don't get angry. I'm doing it to prevent you from messing up\n"+
4991 "this note on the Evernote servers. Sorry."+
4992 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
4994 browserWindow.setReadOnly(true);
5000 //**********************************************************
5001 //**********************************************************
5003 //**********************************************************
5004 //**********************************************************
5005 // We should now do a sync with Evernote
5006 private void syncTimer() {
5007 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5008 syncRunner.syncNeeded = true;
5009 syncRunner.disableUploads = Global.disableUploads;
5011 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5013 private void syncStart() {
5014 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5016 if (!syncRunning && Global.isConnected) {
5017 syncRunner.setConnected(true);
5018 syncRunner.setKeepRunning(Global.keepRunning);
5019 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5021 if (syncThreadsReady > 0) {
5022 indexRunner.interrupt = true;
5023 saveNoteIndexWidth();
5024 saveNoteColumnPositions();
5025 if (syncRunner.addWork("SYNC")) {
5027 syncRunner.syncNeeded = true;
5032 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5034 @SuppressWarnings("unused")
5035 private void syncThreadComplete(Boolean refreshNeeded) {
5036 setMessage(tr("Finalizing Synchronization"));
5038 syncRunning = false;
5039 syncRunner.syncNeeded = false;
5040 synchronizeAnimationTimer.stop();
5041 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5043 if (currentNote == null) {
5044 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5046 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5047 noteIndexUpdated(false);
5048 noteTableView.selectionModel().blockSignals(true);
5049 scrollToGuid(currentNoteGuid);
5050 noteTableView.selectionModel().blockSignals(false);
5051 refreshEvernoteNote(false);
5052 scrollToGuid(currentNoteGuid);
5054 if (!syncRunner.error)
5055 setMessage(tr("Synchronization Complete"));
5057 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5058 logger.log(logger.MEDIUM, "Sync complete.");
5060 public void saveUploadAmount(long t) {
5061 Global.saveUploadAmount(t);
5063 public void saveUserInformation(User user) {
5064 Global.saveUserInformation(user);
5066 public void saveEvernoteUpdateCount(int i) {
5067 Global.saveEvernoteUpdateCount(i);
5069 public void refreshLists() {
5070 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5072 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5073 tagIndexUpdated(true);
5074 notebookIndexUpdated();
5075 savedSearchIndexUpdated();
5076 listManager.loadNotesIndex();
5078 noteTableView.selectionModel().blockSignals(true);
5079 noteIndexUpdated(true);
5080 noteTableView.selectionModel().blockSignals(false);
5081 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5085 @SuppressWarnings("unused")
5086 private void authTimer() {
5087 Calendar cal = Calendar.getInstance();
5089 // If we are not connected let's get out of here
5090 if (!Global.isConnected)
5093 // If this is the first time through, then we need to set this
5094 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5095 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5097 // long now = new Date().getTime();
5098 // if (now > Global.authRefreshTime && Global.isConnected) {
5099 syncRunner.authRefreshNeeded = true;
5103 @SuppressWarnings("unused")
5104 private void authRefreshComplete(boolean goodSync) {
5105 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5106 Global.isConnected = syncRunner.isConnected;
5108 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5109 authTimer.start(1000*60*15);
5110 logger.log(logger.LOW, "Authentication token has been renewed");
5111 // setMessage("Authentication token has been renewed.");
5113 authTimer.start(1000*60*5);
5114 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5115 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5117 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5121 @SuppressWarnings("unused")
5122 private synchronized void indexTimer() {
5123 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5126 if (!indexDisabled && indexRunner.idle) {
5127 indexRunner.addWork("SCAN");
5129 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5132 @SuppressWarnings("unused")
5133 private void indexStarted() {
5134 setMessage(tr("Indexing notes"));
5136 @SuppressWarnings("unused")
5137 private void indexComplete() {
5138 setMessage(tr("Index complete"));
5140 @SuppressWarnings("unused")
5141 private synchronized void toggleNoteIndexing() {
5142 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5143 indexDisabled = !indexDisabled;
5145 setMessage(tr("Indexing is now enabled."));
5147 setMessage(tr("Indexing is now disabled."));
5148 menuBar.disableIndexing.setChecked(indexDisabled);
5149 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5152 @SuppressWarnings("unused")
5153 private void threadMonitorCheck() {
5158 alive = listManager.threadCheck(Global.tagCounterThreadId);
5161 if (tagDeadCount > MAX)
5162 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5163 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5167 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5169 notebookThreadDeadCount++;
5170 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5171 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5173 notebookThreadDeadCount=0;
5175 alive = listManager.threadCheck(Global.trashCounterThreadId);
5178 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5179 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5183 alive = listManager.threadCheck(Global.saveThreadId);
5185 saveThreadDeadCount++;
5186 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5187 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5189 saveThreadDeadCount=0;
5191 if (!syncThread.isAlive()) {
5192 syncThreadDeadCount++;
5193 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5194 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5196 syncThreadDeadCount=0;
5198 if (!indexThread.isAlive()) {
5199 indexThreadDeadCount++;
5200 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5201 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5203 indexThreadDeadCount=0;
5208 private void thumbnailTimer() {
5209 if (Global.enableThumbnails() && conn.getNoteTable().getThumbnailNeededCount() > 1) {
5210 thumbnailTimer.setInterval(10*1000);
5211 thumbnailRunner.addWork("SCAN");
5213 thumbnailTimer.setInterval(60*1000);
5217 //**************************************************
5218 //* Backup & Restore
5219 //**************************************************
5220 @SuppressWarnings("unused")
5221 private void databaseBackup() {
5222 QFileDialog fd = new QFileDialog(this);
5223 fd.setFileMode(FileMode.AnyFile);
5224 fd.setConfirmOverwrite(true);
5225 fd.setWindowTitle(tr("Backup Database"));
5226 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5227 fd.setAcceptMode(AcceptMode.AcceptSave);
5228 fd.setDirectory(System.getProperty("user.home"));
5229 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5235 setMessage(tr("Backing up database"));
5237 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5239 ExportData noteWriter = new ExportData(conn, true);
5240 String fileName = fd.selectedFiles().get(0);
5242 if (!fileName.endsWith(".nnex"))
5243 fileName = fileName +".nnex";
5244 noteWriter.exportData(fileName);
5245 setMessage(tr("Database backup completed."));
5250 @SuppressWarnings("unused")
5251 private void databaseRestore() {
5252 if (QMessageBox.question(this, tr("Confirmation"),
5253 tr("This is used to restore a database from backups.\n" +
5254 "It is HIGHLY recommened that this only be used to populate\n" +
5255 "an empty database. Restoring into a database that\n already has data" +
5256 " can cause problems.\n\nAre you sure you want to continue?"),
5257 QMessageBox.StandardButton.Yes,
5258 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5263 QFileDialog fd = new QFileDialog(this);
5264 fd.setFileMode(FileMode.ExistingFile);
5265 fd.setConfirmOverwrite(true);
5266 fd.setWindowTitle(tr("Restore Database"));
5267 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5268 fd.setAcceptMode(AcceptMode.AcceptOpen);
5269 fd.setDirectory(System.getProperty("user.home"));
5270 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5276 setMessage(tr("Restoring database"));
5277 ImportData noteReader = new ImportData(conn, true);
5278 noteReader.importData(fd.selectedFiles().get(0));
5280 if (noteReader.lastError != 0) {
5281 setMessage(noteReader.getErrorMessage());
5282 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5287 listManager.loadNoteTitleColors();
5289 refreshEvernoteNote(true);
5290 setMessage(tr("Database has been restored."));
5293 @SuppressWarnings("unused")
5294 private void exportNotes() {
5295 QFileDialog fd = new QFileDialog(this);
5296 fd.setFileMode(FileMode.AnyFile);
5297 fd.setConfirmOverwrite(true);
5298 fd.setWindowTitle(tr("Backup Database"));
5299 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5300 fd.setAcceptMode(AcceptMode.AcceptSave);
5301 fd.setDirectory(System.getProperty("user.home"));
5302 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5308 setMessage(tr("Exporting Notes"));
5311 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5312 selectedNoteGUIDs.add(currentNoteGuid);
5314 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5315 String fileName = fd.selectedFiles().get(0);
5317 if (!fileName.endsWith(".nnex"))
5318 fileName = fileName +".nnex";
5319 noteWriter.exportData(fileName);
5320 setMessage(tr("Export completed."));
5326 @SuppressWarnings("unused")
5327 private void importNotes() {
5328 QFileDialog fd = new QFileDialog(this);
5329 fd.setFileMode(FileMode.ExistingFile);
5330 fd.setConfirmOverwrite(true);
5331 fd.setWindowTitle(tr("Import Notes"));
5332 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5333 fd.setAcceptMode(AcceptMode.AcceptOpen);
5334 fd.setDirectory(System.getProperty("user.home"));
5335 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5341 setMessage("Importing Notes");
5344 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5345 selectedNoteGUIDs.add(currentNoteGuid);
5347 ImportData noteReader = new ImportData(conn, false);
5348 String fileName = fd.selectedFiles().get(0);
5350 if (!fileName.endsWith(".nnex"))
5351 fileName = fileName +".nnex";
5352 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5353 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5355 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5357 noteReader.importData(fileName);
5359 if (noteReader.lastError != 0) {
5360 setMessage(noteReader.getErrorMessage());
5361 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5366 listManager.loadNoteTitleColors();
5368 refreshEvernoteNote(false);
5369 setMessage(tr("Notes have been imported."));
5372 setMessage("Import completed.");
5379 //**************************************************
5380 //* Duplicate a note
5381 //**************************************************
5382 @SuppressWarnings("unused")
5383 private void duplicateNote() {
5385 duplicateNote(currentNoteGuid);
5390 //**************************************************
5392 //**************************************************
5393 public void setupFolderImports() {
5394 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5396 if (importKeepWatcher == null)
5397 importKeepWatcher = new QFileSystemWatcher();
5398 if (importDeleteWatcher == null) {
5399 importDeleteWatcher = new QFileSystemWatcher();
5400 for (int i=0; i<records.size(); i++) {
5401 if (!records.get(i).keep)
5402 folderImportDelete(records.get(i).folder);
5408 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5409 for (int i=0; i<records.size(); i++) {
5410 if (records.get(i).keep)
5411 importKeepWatcher.addPath(records.get(i).folder);
5413 importDeleteWatcher.addPath(records.get(i).folder);
5416 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5417 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5419 // Look at the files already there so we don't import them again if a new file is created
5420 if (importedFiles == null) {
5421 importedFiles = new ArrayList<String>();
5422 for (int j=0; j<records.size(); j++) {
5423 QDir dir = new QDir(records.get(j).folder);
5424 List<QFileInfo> list = dir.entryInfoList();
5425 for (int k=0; k<list.size(); k++) {
5426 if (list.get(k).isFile())
5427 importedFiles.add(list.get(k).absoluteFilePath());
5432 public void folderImport() {
5433 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5434 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5436 if (!dialog.okClicked())
5439 // We have some sort of update.
5440 if (importKeepWatcher.directories().size() > 0)
5441 importKeepWatcher.removePaths(importKeepWatcher.directories());
5442 if (importDeleteWatcher.directories().size() > 0)
5443 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5445 conn.getWatchFolderTable().expungeAll();
5446 // Start building from the table
5447 for (int i=0; i<dialog.table.rowCount(); i++) {
5448 QTableWidgetItem item = dialog.table.item(i, 0);
5449 String dir = item.text();
5450 item = dialog.table.item(i, 1);
5451 String notebook = item.text();
5452 item = dialog.table.item(i, 2);
5454 if (item.text().equalsIgnoreCase("Keep"))
5459 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5460 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5462 setupFolderImports();
5465 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5467 String whichOS = System.getProperty("os.name");
5468 if (whichOS.contains("Windows"))
5469 dirName = dirName.replace('/','\\');
5471 FileImporter importer = new FileImporter(logger, conn);
5473 QDir dir = new QDir(dirName);
5474 List<QFileInfo> list = dir.entryInfoList();
5475 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5477 for (int i=0; i<list.size(); i++){
5479 boolean redundant = false;
5480 // Check if we've already imported this one or if it existed before
5481 for (int j=0; j<importedFiles.size(); j++) {
5482 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5487 importer.setFileInfo(list.get(i));
5488 importer.setFileName(list.get(i).absoluteFilePath());
5491 if (list.get(i).isFile() && importer.isValidType()) {
5493 if (!importer.importFile()) {
5494 // If we can't get to the file, it is probably locked. We'll try again later.
5495 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5496 importFilesKeep.add(list.get(i).absoluteFilePath());
5500 Note newNote = importer.getNote();
5501 newNote.setNotebookGuid(notebook);
5502 newNote.setTitle(dir.at(i));
5503 listManager.addNote(newNote);
5504 conn.getNoteTable().addNote(newNote, true);
5505 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5506 noteTableView.insertRow(newNote, true, -1);
5507 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5508 listManager.countNotebookResults(listManager.getNoteIndex());
5509 importedFiles.add(list.get(i).absoluteFilePath());
5517 public void folderImportDelete(String dirName) {
5519 String whichOS = System.getProperty("os.name");
5520 if (whichOS.contains("Windows"))
5521 dirName = dirName.replace('/','\\');
5523 FileImporter importer = new FileImporter(logger, conn);
5524 QDir dir = new QDir(dirName);
5525 List<QFileInfo> list = dir.entryInfoList();
5526 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5528 for (int i=0; i<list.size(); i++){
5529 importer.setFileInfo(list.get(i));
5530 importer.setFileName(list.get(i).absoluteFilePath());
5532 if (list.get(i).isFile() && importer.isValidType()) {
5534 if (!importer.importFile()) {
5535 // If we can't get to the file, it is probably locked. We'll try again later.
5536 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5537 importFilesKeep.add(list.get(i).absoluteFilePath());
5541 Note newNote = importer.getNote();
5542 newNote.setNotebookGuid(notebook);
5543 newNote.setTitle(dir.at(i));
5544 listManager.addNote(newNote);
5545 conn.getNoteTable().addNote(newNote, true);
5546 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5547 noteTableView.insertRow(newNote, true, -1);
5548 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5549 listManager.countNotebookResults(listManager.getNoteIndex());
5550 dir.remove(dir.at(i));
5556 //**************************************************
5558 //**************************************************
5559 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5560 logger.log(logger.HIGH, "Entering exernalFileEdited");
5562 // Strip URL prefix and base dir path
5563 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5564 String name = fileName.replace(dPath, "");
5565 int pos = name.lastIndexOf('.');
5568 guid = guid.substring(0,pos);
5570 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5572 guid = name.substring(0, pos);
5575 QFile file = new QFile(fileName);
5576 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5577 // If we can't get to the file, it is probably locked. We'll try again later.
5578 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5579 externalFiles.add(fileName);
5582 QByteArray binData = file.readAll();
5584 if (binData.size() == 0) {
5585 // If we can't get to the file, it is probably locked. We'll try again later.
5586 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5587 externalFiles.add(fileName);
5591 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5593 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5594 if (r == null || r.getData() == null || r.getData().getBody() == null)
5596 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5597 MessageDigest md = MessageDigest.getInstance("MD5");
5598 md.update(binData.toByteArray());
5599 byte[] hash = md.digest();
5600 String newHash = Global.byteArrayToHexString(hash);
5601 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5602 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5604 if (externalWindows.containsKey(r.getNoteGuid())) {
5605 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5606 r.getGuid(), oldHash, newHash);
5608 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5609 Data data = r.getData();
5610 data.setBody(binData.toByteArray());
5611 data.setBodyHash(hash);
5612 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5614 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5616 if (r.getNoteGuid().equals(currentNoteGuid)) {
5617 QWebSettings.setMaximumPagesInCache(0);
5618 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5619 refreshEvernoteNote(true);
5620 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5623 if (externalWindows.containsKey(r.getNoteGuid())) {
5624 QWebSettings.setMaximumPagesInCache(0);
5625 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5626 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5630 logger.log(logger.HIGH, "Exiting externalFielEdited");
5632 // This is a timer event that tries to save any external files that were edited. This
5633 // is only needed if we couldn't save a file earlier.
5634 public void externalFileEditedSaver() {
5635 for (int i=externalFiles.size()-1; i>=0; i--) {
5637 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5638 externalFileEdited(externalFiles.get(i));
5639 externalFiles.remove(i);
5640 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5642 for (int i=0; i<importFilesKeep.size(); i++) {
5644 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5645 folderImportKeep(importFilesKeep.get(i));
5646 importFilesKeep.remove(i);
5647 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5649 for (int i=0; i<importFilesDelete.size(); i++) {
5650 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5651 folderImportDelete(importFilesDelete.get(i));
5652 importFilesDelete.remove(i);
5659 // If an attachment on the current note was edited, we need to update the current notes's hash
5660 // Update a note content's hash. This happens if a resource is edited outside of NN
5661 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5662 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5664 for (;position>-1;) {
5665 endPos = browser.getContent().indexOf(">", position+1);
5666 String oldSegment = browser.getContent().substring(position,endPos);
5667 int hashPos = oldSegment.indexOf("hash=\"");
5668 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5669 String hash = oldSegment.substring(hashPos+6, hashEnd);
5670 if (hash.equalsIgnoreCase(oldHash)) {
5671 String newSegment = oldSegment.replace(oldHash, newHash);
5672 String content = browser.getContent().substring(0,position) +
5674 browser.getContent().substring(endPos);
5675 browser.getBrowser().setContent(new QByteArray(content));;
5678 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5683 //*************************************************
5684 //* Minimize to tray
5685 //*************************************************
5687 public void changeEvent(QEvent e) {
5688 if (e.type() == QEvent.Type.WindowStateChange) {
5689 if (isMinimized() && Global.showTrayIcon()) {
5691 QTimer.singleShot(10, this, "hide()");
5695 windowMaximized = true;
5697 windowMaximized = false;
5701 //*************************************************
5702 //* Check database userid & passwords
5703 //*************************************************
5704 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5705 Connection connection;
5708 Class.forName("org.h2.Driver");
5709 } catch (ClassNotFoundException e1) {
5710 e1.printStackTrace();
5715 String passwordString = null;
5716 if (cypherPassword==null || cypherPassword.trim().equals(""))
5717 passwordString = userPassword;
5719 passwordString = cypherPassword+" "+userPassword;
5720 connection = DriverManager.getConnection(url,userid,passwordString);
5721 } catch (SQLException e) {
5726 } catch (SQLException e) {
5727 e.printStackTrace();