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);
321 private String saveLastPath; // last path we used
324 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
327 //***************************************************************
328 //***************************************************************
329 //** Constructor & main entry point
330 //***************************************************************
331 //***************************************************************
332 // Application Constructor
333 @SuppressWarnings("static-access")
334 public NeverNote(DatabaseConnection dbConn) {
336 if (conn.getConnection() == null) {
337 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
338 "is accessing the database or NeverNote is already running.\n\n" +
339 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
341 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
345 thread().setPriority(Thread.MAX_PRIORITY);
347 logger = new ApplicationLogger("nevernote.log");
348 logger.log(logger.HIGH, "Starting Application");
350 decryptOnShutdown = false;
351 encryptOnShutdown = false;
352 conn.checkDatabaseVersion();
356 // Start building the invalid XML tables
357 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
358 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
360 for (int i=0; i<elements.size(); i++) {
361 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
364 logger.log(logger.EXTREME, "Starting GUI build");
366 QTranslator nevernoteTranslator = new QTranslator();
367 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
368 QApplication.instance().installTranslator(nevernoteTranslator);
370 Global.originalPalette = QApplication.palette();
371 QApplication.setStyle(Global.getStyle());
372 if (Global.useStandardPalette())
373 QApplication.setPalette(QApplication.style().standardPalette());
374 setWindowTitle("NeverNote");
376 mainLeftRightSplitter = new QSplitter();
377 setCentralWidget(mainLeftRightSplitter);
378 leftSplitter1 = new QSplitter();
379 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
381 browserIndexSplitter = new QSplitter();
382 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
384 //* Setup threads & thread timers
385 int indexRunnerCount = Global.getIndexThreads();
386 indexRunnerCount = 1;
387 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
389 logger.log(logger.EXTREME, "Building list manager");
390 listManager = new ListManager(conn, logger);
392 logger.log(logger.EXTREME, "Building index runners & timers");
393 indexRunner = new IndexRunner("indexRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
394 indexThread = new QThread(indexRunner, "Index Thread");
395 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
398 synchronizeAnimationTimer = new QTimer();
399 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
401 indexTimer = new QTimer();
402 indexTime = 1000*Global.getIndexThreadSleepInterval();
403 indexTimer.start(indexTime); // Start indexing timer
404 indexTimer.timeout.connect(this, "indexTimer()");
405 indexDisabled = false;
406 indexRunning = false;
408 logger.log(logger.EXTREME, "Setting sync thread & timers");
410 syncRunner = new SyncRunner("syncRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
411 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
412 syncTimer = new QTimer();
413 syncTimer.timeout.connect(this, "syncTimer()");
414 syncRunner.status.message.connect(this, "setMessage(String)");
415 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
416 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
419 automaticSync = true;
420 syncTimer.start(syncTime*60*1000);
422 automaticSync = false;
425 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
426 syncThread = new QThread(syncRunner, "Synchronization Thread");
430 logger.log(logger.EXTREME, "Starting thumnail thread");
431 pdfReadyQueue = new ArrayList<String>();
432 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log", Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
433 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
434 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
435 thumbnailThread.start();
436 thumbGenerators = new ArrayList<Thumbnailer>();
437 thumbnailTimer = new QTimer();
438 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
440 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
441 thumbnailTimer.start();
443 logger.log(logger.EXTREME, "Starting authentication timer");
444 authTimer = new QTimer();
445 authTimer.timeout.connect(this, "authTimer()");
446 authTimer.start(1000*60*15);
447 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
449 logger.log(logger.EXTREME, "Setting save note timer");
450 saveTimer = new QTimer();
451 saveTimer.timeout.connect(this, "saveNote()");
452 if (Global.getAutoSaveInterval() > 0) {
453 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
456 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
458 logger.log(logger.EXTREME, "Starting external file monitor timer");
459 externalFileSaveTimer = new QTimer();
460 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
461 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
462 externalFiles = new ArrayList<String>();
463 importFilesDelete = new ArrayList<String>();
464 importFilesKeep = new ArrayList<String>();
465 externalFileSaveTimer.start();
467 notebookTree = new NotebookTreeWidget(conn);
468 attributeTree = new AttributeTreeWidget();
469 tagTree = new TagTreeWidget(conn);
470 savedSearchTree = new SavedSearchTreeWidget();
471 trashTree = new TrashTreeWidget();
472 noteTableView = new TableView(logger, listManager);
474 QGridLayout leftGrid = new QGridLayout();
475 leftSplitter1.setLayout(leftGrid);
476 leftGrid.addWidget(notebookTree, 1, 1);
477 leftGrid.addWidget(tagTree,2,1);
478 leftGrid.addWidget(attributeTree,3,1);
479 leftGrid.addWidget(savedSearchTree,4,1);
480 leftGrid.addWidget(trashTree, 5, 1);
482 // Setup the browser window
483 noteCache = new HashMap<String,String>();
484 readOnlyCache = new HashMap<String, Boolean>();
485 inkNoteCache = new HashMap<String, Boolean>();
486 browserWindow = new BrowserWindow(conn);
488 mainLeftRightSplitter.addWidget(leftSplitter1);
489 mainLeftRightSplitter.addWidget(browserIndexSplitter);
491 if (Global.getListView() == Global.View_List_Wide) {
492 browserIndexSplitter.addWidget(noteTableView);
493 browserIndexSplitter.addWidget(browserWindow);
495 mainLeftRightSplitter.addWidget(noteTableView);
496 mainLeftRightSplitter.addWidget(browserWindow);
499 searchField = new QComboBox();
500 searchField.setEditable(true);
501 searchField.activatedIndex.connect(this, "searchFieldChanged()");
502 searchField.setDuplicatesEnabled(false);
503 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
505 quotaBar = new QuotaProgressBar();
507 // Setup the thumbnail viewer
508 thumbnailViewer = new ThumbnailViewer();
509 thumbnailViewer.upArrow.connect(this, "upAction()");
510 thumbnailViewer.downArrow.connect(this, "downAction()");
511 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
512 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
514 //Setup external browser manager
515 externalWindows = new HashMap<String, ExternalBrowse>();
517 listManager.loadNotesIndex();
518 initializeNotebookTree();
520 initializeSavedSearchTree();
521 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
522 attributeTreeSelected = null;
523 initializeNoteTable();
525 selectedNoteGUIDs = new ArrayList<String>();
526 statusBar = new QStatusBar();
527 setStatusBar(statusBar);
528 menuBar = new MainMenuBar(this);
529 emitLog = new ArrayList<String>();
531 tagTree.setDeleteAction(menuBar.tagDeleteAction);
532 tagTree.setEditAction(menuBar.tagEditAction);
533 tagTree.setAddAction(menuBar.tagAddAction);
534 tagTree.setIconAction(menuBar.tagIconAction);
535 tagTree.setVisible(Global.isWindowVisible("tagTree"));
536 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
537 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
538 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
540 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
541 notebookTree.setEditAction(menuBar.notebookEditAction);
542 notebookTree.setAddAction(menuBar.notebookAddAction);
543 notebookTree.setIconAction(menuBar.notebookIconAction);
544 notebookTree.setStackAction(menuBar.notebookStackAction);
545 notebookTree.setPublishAction(menuBar.notebookPublishAction);
546 notebookTree.setShareAction(menuBar.notebookShareAction);
547 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
548 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
549 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
550 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
551 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
553 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
554 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
555 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
556 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
557 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
558 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
559 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
561 noteTableView.setAddAction(menuBar.noteAdd);
562 noteTableView.setDeleteAction(menuBar.noteDelete);
563 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
564 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
565 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
566 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
567 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
568 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
569 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
570 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
571 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
573 quotaBar.setMouseClickAction(menuBar.accountAction);
576 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
577 trashTree.setEmptyAction(menuBar.emptyTrashAction);
578 trashTree.setVisible(Global.isWindowVisible("trashTree"));
579 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
580 trashTree.updateCounts(listManager.getTrashCount());
581 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
582 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
584 noteTableView.setVisible(Global.isWindowVisible("noteList"));
585 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
587 if (!Global.isWindowVisible("editorButtonBar"))
588 toggleEditorButtonBar();
589 if (!Global.isWindowVisible("leftPanel"))
590 menuBar.hideLeftSide.setChecked(true);
591 if (Global.isWindowVisible("noteInformation"))
592 toggleNoteInformation();
596 find = new FindDialog();
597 find.getOkButton().clicked.connect(this, "doFindText()");
599 // Setup the tray icon menu bar
600 trayShowAction = new QAction("Show/Hide", this);
601 trayExitAction = new QAction("Exit", this);
602 trayAddNoteAction = new QAction("Add Note", this);
604 trayExitAction.triggered.connect(this, "closeNeverNote()");
605 trayAddNoteAction.triggered.connect(this, "addNote()");
606 trayShowAction.triggered.connect(this, "trayToggleVisible()");
608 trayMenu = new QMenu(this);
609 trayMenu.addAction(trayAddNoteAction);
610 trayMenu.addAction(trayShowAction);
611 trayMenu.addAction(trayExitAction);
614 trayIcon = new QSystemTrayIcon(this);
615 trayIcon.setToolTip("NeverNote");
616 trayIcon.setContextMenu(trayMenu);
617 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
620 currentNoteGuid = Global.getLastViewedNoteGuid();
621 historyGuids = new ArrayList<String>();
625 if (!currentNoteGuid.trim().equals("")) {
626 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
629 noteIndexUpdated(true);
631 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
632 if (menuBar.showEditorBar.isChecked())
633 showEditorButtons(browserWindow);
634 tagIndexUpdated(true);
635 savedSearchIndexUpdated();
636 notebookIndexUpdated();
638 setupSyncSignalListeners();
639 setupBrowserSignalListeners();
640 setupIndexListeners();
643 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
644 tagTree.showAllTags(true);
646 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
647 setWindowIcon(appIcon);
648 trayIcon.setIcon(appIcon);
649 if (Global.showTrayIcon())
654 scrollToGuid(currentNoteGuid);
655 if (Global.automaticLogin()) {
657 if (Global.isConnected)
660 setupFolderImports();
663 restoreWindowState(true);
665 if (Global.mimicEvernoteInterface) {
666 notebookTree.selectGuid("");
669 threadMonitorTimer = new QTimer();
670 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
671 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
673 historyGuids.add(currentNoteGuid);
676 menuBar.blockSignals(true);
677 menuBar.narrowListView.blockSignals(true);
678 menuBar.wideListView.blockSignals(true);
679 if (Global.getListView() == Global.View_List_Narrow) {
680 menuBar.narrowListView.setChecked(true);
683 menuBar.wideListView.setChecked(true);
685 menuBar.blockSignals(false);
686 menuBar.narrowListView.blockSignals(false);
687 menuBar.wideListView.blockSignals(false);
689 if (Global.getListView() == Global.View_List_Wide) {
690 browserIndexSplitter.addWidget(noteTableView);
691 browserIndexSplitter.addWidget(browserWindow);
693 mainLeftRightSplitter.addWidget(noteTableView);
694 mainLeftRightSplitter.addWidget(browserWindow);
697 int sortCol = Global.getSortColumn();
698 int sortOrder = Global.getSortOrder();
699 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
700 if (Global.checkVersionUpgrade())
705 public static void main(String[] args) {
706 log.setLevel(Level.FATAL);
707 QApplication.initialize(args);
708 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
709 QSplashScreen splash = new QSplashScreen(pixmap);
712 DatabaseConnection dbConn;
715 initializeGlobalSettings(args);
717 showSplash = Global.isWindowVisible("SplashScreen");
721 dbConn = setupDatabaseConnection();
723 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
724 Global.getFileManager().purgeResDirectory(true);
726 } catch (InitializationException e) {
729 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
733 NeverNote application = new NeverNote(dbConn);
735 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
736 if (Global.startMinimized())
737 application.showMinimized();
739 if (Global.wasWindowMaximized())
740 application.showMaximized();
746 splash.finish(application);
748 System.out.println("Goodbye.");
753 * Open the internal database, or create if not present
755 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
757 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
758 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
760 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
761 boolean dbExists = f.exists();
763 Global.setDatabaseUrl("");
765 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
766 boolean goodCheck = false;
768 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
770 if (!dialog.okPressed())
772 Global.cipherPassword = dialog.getPassword();
773 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
774 Global.getDatabaseUserPassword(), Global.cipherPassword);
777 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(), Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
781 // Encrypt the database upon shutdown
782 private void encryptOnShutdown() {
783 String dbPath= Global.getFileManager().getDbDirPath("");
784 String dbName = "NeverNote";
786 Statement st = conn.getConnection().createStatement();
787 st.execute("shutdown");
788 if (QMessageBox.question(this, "Are you sure",
789 "Are you sure you wish to encrypt the database?",
790 QMessageBox.StandardButton.Yes,
791 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
792 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
793 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
794 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
796 } catch (SQLException e) {
801 // Decrypt the database upon shutdown
802 private void decryptOnShutdown() {
803 String dbPath= Global.getFileManager().getDbDirPath("");
804 String dbName = "NeverNote";
806 Statement st = conn.getConnection().createStatement();
807 st.execute("shutdown");
808 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
809 encryptCipher = "AES";
811 encryptCipher = "XTEA";
812 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
813 "Are you sure you wish to decrypt the database?"),
814 QMessageBox.StandardButton.Yes,
815 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
817 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
818 Global.setDatabaseUrl("");
819 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
821 } catch (SQLException e) {
826 * Encrypt/Decrypt the local database
828 public void doDatabaseEncrypt() {
829 // The database is not currently encrypted
830 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
831 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
832 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
833 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
834 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
835 "Do you wish to proceed?"),
836 QMessageBox.StandardButton.Yes,
837 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
840 DBEncryptDialog dialog = new DBEncryptDialog();
842 if (dialog.okPressed()) {
843 Global.cipherPassword = dialog.getPassword();
844 encryptOnShutdown = true;
845 encryptCipher = dialog.getEncryptionMethod();
848 DBEncryptDialog dialog = new DBEncryptDialog();
849 dialog.setWindowTitle("Database Decryption");
850 dialog.hideEncryption();
852 if (dialog.okPressed()) {
853 if (!dialog.getPassword().equals(Global.cipherPassword)) {
854 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
857 decryptOnShutdown = true;
864 private static void initializeGlobalSettings(String[] args) throws InitializationException {
865 StartupConfig startupConfig = new StartupConfig();
867 for (String arg : args) {
868 String lower = arg.toLowerCase();
869 if (lower.startsWith("--name="))
870 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
871 if (lower.startsWith("--home="))
872 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
873 if (lower.startsWith("--disable-viewing"))
874 startupConfig.setDisableViewing(true);
876 Global.setup(startupConfig);
881 public void closeEvent(QCloseEvent event) {
882 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
887 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
890 if (currentNote!= null & browserWindow!=null) {
891 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
892 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
895 setMessage(tr("Beginning shutdown."));
897 // Close down external windows
898 Collection<ExternalBrowse> windows = externalWindows.values();
899 Iterator<ExternalBrowse> iterator = windows.iterator();
900 while (iterator.hasNext()) {
901 ExternalBrowse browser = iterator.next();
902 browser.windowClosing.disconnect();
907 externalFileEditedSaver();
908 if (Global.isConnected && Global.synchronizeOnClose()) {
909 setMessage(tr("Performing synchronization before closing."));
910 syncRunner.addWork("SYNC");
912 setMessage("Closing Program.");
913 threadMonitorTimer.stop();
915 syncRunner.addWork("STOP");
916 syncRunner.keepRunning = false;
917 thumbnailRunner.addWork("STOP");
918 syncRunner.keepRunning = false;
919 indexRunner.addWork("STOP");
920 syncRunner.keepRunning = false;
925 if (tempFiles != null)
928 browserWindow.noteSignal.tagsChanged.disconnect();
929 browserWindow.noteSignal.titleChanged.disconnect();
930 browserWindow.noteSignal.noteChanged.disconnect();
931 browserWindow.noteSignal.notebookChanged.disconnect();
932 browserWindow.noteSignal.createdDateChanged.disconnect();
933 browserWindow.noteSignal.alteredDateChanged.disconnect();
934 syncRunner.searchSignal.listChanged.disconnect();
935 syncRunner.tagSignal.listChanged.disconnect();
936 syncRunner.notebookSignal.listChanged.disconnect();
937 syncRunner.noteIndexSignal.listChanged.disconnect();
940 Global.saveWindowVisible("toolBar", toolBar.isVisible());
941 saveNoteColumnPositions();
942 saveNoteIndexWidth();
944 int width = notebookTree.columnWidth(0);
945 Global.setColumnWidth("notebookTreeName", width);
946 width = tagTree.columnWidth(0);
947 Global.setColumnWidth("tagTreeName", width);
949 Global.saveWindowMaximized(isMaximized());
950 Global.saveCurrentNoteGuid(currentNoteGuid);
952 int sortCol = noteTableView.proxyModel.sortColumn();
953 int sortOrder = noteTableView.proxyModel.sortOrder().value();
954 Global.setSortColumn(sortCol);
955 Global.setSortOrder(sortOrder);
959 Global.keepRunning = false;
961 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
962 if (indexRunner.thread().isAlive())
963 indexRunner.thread().join(50);
964 if (!indexRunner.thread().isAlive())
965 logger.log(logger.MEDIUM, "Index thread has stopped");
967 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
968 indexRunner.thread().interrupt();
970 } catch (InterruptedException e1) {
971 e1.printStackTrace();
973 if (!syncRunner.isIdle()) {
975 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
977 logger.log(logger.MEDIUM, "Sync thread has stopped");
978 } catch (InterruptedException e1) {
979 e1.printStackTrace();
983 if (encryptOnShutdown) {
986 if (decryptOnShutdown) {
990 Global.getFileManager().purgeResDirectory(false);
991 } catch (InitializationException e) {
992 System.out.println(tr("Empty res directory purge failed"));
995 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
998 @SuppressWarnings("unused")
999 private void closeNeverNote() {
1003 public void setMessage(String s) {
1004 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1005 logger.log(logger.HIGH, "Message: " +s);
1006 statusBar.showMessage(s);
1008 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1011 private void waitCursor(boolean wait) {
1013 if (QApplication.overrideCursor() == null)
1014 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1017 while (QApplication.overrideCursor() != null)
1018 QApplication.restoreOverrideCursor();
1022 private void setupIndexListeners() {
1023 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1024 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1025 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1026 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1028 private void setupSyncSignalListeners() {
1029 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1030 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1031 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1032 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1033 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1035 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1036 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1037 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1039 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1040 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1041 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1042 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1043 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1045 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1048 private void setupBrowserSignalListeners() {
1049 setupBrowserWindowListeners(browserWindow, true);
1052 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1053 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1054 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1055 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1056 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1057 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1058 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1059 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1060 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1061 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1062 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1063 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1064 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1065 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1066 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1067 if (master) browser.focusLost.connect(this, "saveNote()");
1068 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1071 //***************************************************************
1072 //***************************************************************
1073 //* Settings and look & feel
1074 //***************************************************************
1075 //***************************************************************
1076 @SuppressWarnings("unused")
1077 private void settings() {
1078 logger.log(logger.HIGH, "Entering NeverNote.settings");
1079 saveNoteColumnPositions();
1080 saveNoteIndexWidth();
1082 ConfigDialog settings = new ConfigDialog(this);
1083 String dateFormat = Global.getDateFormat();
1084 String timeFormat = Global.getTimeFormat();
1086 indexTime = 1000*Global.getIndexThreadSleepInterval();
1087 indexTimer.start(indexTime); // reset indexing timer
1090 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1091 if (Global.showTrayIcon())
1096 if (menuBar.showEditorBar.isChecked())
1097 showEditorButtons(browserWindow);
1099 // Reset the save timer
1100 if (Global.getAutoSaveInterval() > 0)
1101 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1105 // This is a hack to force a reload of the index in case the date or time changed.
1106 // if (!dateFormat.equals(Global.getDateFormat()) ||
1107 // !timeFormat.equals(Global.getTimeFormat())) {
1109 readOnlyCache.clear();
1110 inkNoteCache.clear();
1111 noteIndexUpdated(true);
1114 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1116 // Restore things to the way they were
1117 private void restoreWindowState(boolean mainWindow) {
1118 // We need to name things or this doesn't work.
1119 setObjectName("NeverNote");
1120 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1121 browserIndexSplitter.setObjectName("browserIndexSplitter");
1122 leftSplitter1.setObjectName("leftSplitter1");
1124 // Restore the actual positions.
1126 restoreGeometry(Global.restoreGeometry(objectName()));
1127 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1128 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1129 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1132 // Save window positions for the next start
1133 private void saveWindowState() {
1134 Global.saveGeometry(objectName(), saveGeometry());
1135 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1136 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1137 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1139 // Load the style sheet
1140 private void loadStyleSheet() {
1141 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1142 fileName = Global.getFileManager().getQssDirPath("default.qss");
1143 QFile file = new QFile(fileName);
1145 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1146 if (!file.exists()) {
1147 fileName = Global.getFileManager().getQssDirPath("default.qss");
1148 file = new QFile(fileName);
1150 file.open(OpenModeFlag.ReadOnly);
1151 String styleSheet = file.readAll().toString();
1153 setStyleSheet(styleSheet);
1155 // Save column positions for the next time
1156 private void saveNoteColumnPositions() {
1157 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1158 Global.setColumnPosition("noteTableCreationPosition", position);
1159 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1160 Global.setColumnPosition("noteTableTagPosition", position);
1161 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1162 Global.setColumnPosition("noteTableNotebookPosition", position);
1163 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1164 Global.setColumnPosition("noteTableChangedPosition", position);
1165 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1166 Global.setColumnPosition("noteTableAuthorPosition", position);
1167 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1168 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1169 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1170 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1171 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1172 Global.setColumnPosition("noteTableTitlePosition", position);
1173 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1174 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1175 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1176 Global.setColumnPosition("noteTableGuidPosition", position);
1177 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1178 Global.setColumnPosition("noteTableThumbnailPosition", position);
1181 // Save column widths for the next time
1182 private void saveNoteIndexWidth() {
1184 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1185 Global.setColumnWidth("noteTableCreationPosition", width);
1186 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1187 Global.setColumnWidth("noteTableChangedPosition", width);
1188 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1189 Global.setColumnWidth("noteTableGuidPosition", width);
1190 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1191 Global.setColumnWidth("noteTableNotebookPosition", width);
1192 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1193 Global.setColumnWidth("noteTableTagPosition", width);
1194 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1195 Global.setColumnWidth("noteTableTitlePosition", width);
1196 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1197 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1198 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1199 Global.setColumnWidth("noteTableAuthorPosition", width);
1200 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1201 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1202 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1203 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1204 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1205 Global.setColumnWidth("noteTableThumbnailPosition", width);
1206 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1207 Global.setColumnWidth("noteTableGuidPosition", width);
1211 //***************************************************************
1212 //***************************************************************
1213 //** These functions deal with Notebook menu items
1214 //***************************************************************
1215 //***************************************************************
1216 // Setup the tree containing the user's notebooks.
1217 private void initializeNotebookTree() {
1218 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1219 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1220 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1221 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1222 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1224 // Listener when a notebook is selected
1225 private void notebookTreeSelection() {
1226 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1229 clearAttributeFilter();
1230 clearSavedSearchFilter();
1231 if (Global.mimicEvernoteInterface) {
1233 searchField.clear();
1235 menuBar.noteRestoreAction.setVisible(false);
1236 menuBar.notebookEditAction.setEnabled(true);
1237 menuBar.notebookDeleteAction.setEnabled(true);
1238 menuBar.notebookPublishAction.setEnabled(true);
1239 menuBar.notebookShareAction.setEnabled(true);
1240 menuBar.notebookIconAction.setEnabled(true);
1241 menuBar.notebookStackAction.setEnabled(true);
1242 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1243 selectedNotebookGUIDs.clear();
1245 String stackName = "";
1246 if (selections.size() > 0) {
1247 guid = (selections.get(0).text(2));
1248 stackName = selections.get(0).text(0);
1250 if (!Global.mimicEvernoteInterface) {
1251 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1252 if (selections.size()==0) {
1253 selectedNotebookGUIDs.clear();
1254 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1255 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1257 menuBar.notebookEditAction.setEnabled(false);
1258 menuBar.notebookDeleteAction.setEnabled(false);
1259 menuBar.notebookStackAction.setEnabled(false);
1260 menuBar.notebookIconAction.setEnabled(false);
1263 if (!guid.equals("") && !guid.equals("STACK")) {
1264 selectedNotebookGUIDs.add(guid);
1265 menuBar.notebookIconAction.setEnabled(true);
1267 menuBar.notebookIconAction.setEnabled(true);
1268 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1269 Notebook book = listManager.getNotebookIndex().get(j);
1270 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1271 selectedNotebookGUIDs.add(book.getGuid());
1274 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1275 listManager.loadNotesIndex();
1276 noteIndexUpdated(false);
1277 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1280 private void clearNotebookFilter() {
1281 notebookTree.blockSignals(true);
1282 notebookTree.clearSelection();
1283 menuBar.noteRestoreAction.setVisible(false);
1284 menuBar.notebookEditAction.setEnabled(false);
1285 menuBar.notebookDeleteAction.setEnabled(false);
1286 selectedNotebookGUIDs.clear();
1287 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1288 notebookTree.blockSignals(false);
1290 // Triggered when the notebook DB has been updated
1291 private void notebookIndexUpdated() {
1292 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1294 // Get the possible icons
1295 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1296 notebookTree.setIcons(icons);
1298 if (selectedNotebookGUIDs == null)
1299 selectedNotebookGUIDs = new ArrayList<String>();
1300 List<Notebook> books = conn.getNotebookTable().getAll();
1301 for (int i=books.size()-1; i>=0; i--) {
1302 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1303 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1305 j=listManager.getArchiveNotebookIndex().size();
1311 listManager.countNotebookResults(listManager.getNoteIndex());
1312 notebookTree.blockSignals(true);
1313 notebookTree.load(books, listManager.getLocalNotebooks());
1314 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1315 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1317 selectedNotebookGUIDs.remove(i);
1319 notebookTree.blockSignals(false);
1321 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1323 // Show/Hide note information
1324 private void toggleNotebookWindow() {
1325 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1326 if (notebookTree.isVisible())
1327 notebookTree.hide();
1329 notebookTree.show();
1330 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1331 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1332 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1334 // Add a new notebook
1335 @SuppressWarnings("unused")
1336 private void addNotebook() {
1337 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1338 NotebookEdit edit = new NotebookEdit();
1339 edit.setNotebooks(listManager.getNotebookIndex());
1342 if (!edit.okPressed())
1345 Calendar currentTime = new GregorianCalendar();
1346 Long l = new Long(currentTime.getTimeInMillis());
1347 String randint = new String(Long.toString(l));
1349 Notebook newBook = new Notebook();
1350 newBook.setUpdateSequenceNum(0);
1351 newBook.setGuid(randint);
1352 newBook.setName(edit.getNotebook());
1353 newBook.setServiceCreated(new Date().getTime());
1354 newBook.setServiceUpdated(new Date().getTime());
1355 newBook.setDefaultNotebook(false);
1356 newBook.setPublished(false);
1358 listManager.getNotebookIndex().add(newBook);
1360 listManager.getLocalNotebooks().add(newBook.getGuid());
1361 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1362 notebookIndexUpdated();
1363 listManager.countNotebookResults(listManager.getNoteIndex());
1364 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1365 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1367 // Edit an existing notebook
1368 @SuppressWarnings("unused")
1369 private void stackNotebook() {
1370 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1371 StackNotebook edit = new StackNotebook();
1373 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1374 QTreeWidgetItem currentSelection;
1375 for (int i=0; i<selections.size(); i++) {
1376 currentSelection = selections.get(0);
1377 String guid = currentSelection.text(2);
1378 if (guid.equalsIgnoreCase("")) {
1379 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1382 if (guid.equalsIgnoreCase("STACK")) {
1383 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1388 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1393 if (!edit.okPressed())
1396 String stack = edit.getStackName();
1398 for (int i=0; i<selections.size(); i++) {
1399 currentSelection = selections.get(i);
1400 String guid = currentSelection.text(2);
1401 listManager.updateNotebookStack(guid, stack);
1403 notebookIndexUpdated();
1404 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1406 // Edit an existing notebook
1407 @SuppressWarnings("unused")
1408 private void editNotebook() {
1409 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1410 NotebookEdit edit = new NotebookEdit();
1412 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1413 QTreeWidgetItem currentSelection;
1414 currentSelection = selections.get(0);
1415 edit.setNotebook(currentSelection.text(0));
1417 String guid = currentSelection.text(2);
1418 if (!guid.equalsIgnoreCase("STACK")) {
1419 edit.setTitle(tr("Edit Notebook"));
1420 edit.setNotebooks(listManager.getNotebookIndex());
1421 edit.setLocalCheckboxEnabled(false);
1422 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1423 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1424 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1425 i=listManager.getNotebookIndex().size();
1429 edit.setTitle(tr("Edit Stack"));
1430 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1431 edit.hideLocalCheckbox();
1432 edit.hideDefaultCheckbox();
1437 if (!edit.okPressed())
1441 if (guid.equalsIgnoreCase("STACK")) {
1442 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1443 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1444 if (listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1445 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1447 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1448 currentSelection.setText(0, edit.getNotebook());
1452 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1453 currentSelection.setText(0, edit.getNotebook());
1455 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1456 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1457 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1458 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1459 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1460 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1461 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1462 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1464 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1465 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1466 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1467 linkedNotebook.setShareName(edit.getNotebook());
1468 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1470 i=listManager.getNotebookIndex().size();
1474 // Build a list of non-closed notebooks
1475 List<Notebook> nbooks = new ArrayList<Notebook>();
1476 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1477 boolean found=false;
1478 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1479 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1483 nbooks.add(listManager.getNotebookIndex().get(i));
1487 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1488 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1489 browserWindow.setNotebookList(filteredBooks);
1490 Iterator<String> set = externalWindows.keySet().iterator();
1491 while(set.hasNext())
1492 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1493 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1495 // Publish a notebook
1496 @SuppressWarnings("unused")
1497 private void publishNotebook() {
1498 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1499 QTreeWidgetItem currentSelection;
1500 currentSelection = selections.get(0);
1501 String guid = currentSelection.text(2);
1503 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1508 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1509 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1510 n = listManager.getNotebookIndex().get(i);
1512 i = listManager.getNotebookIndex().size();
1518 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1521 if (!publish.okClicked())
1524 Publishing p = publish.getPublishing();
1525 boolean isPublished = !publish.isStopPressed();
1526 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1527 n.setPublished(isPublished);
1529 listManager.getNotebookIndex().set(position, n);
1530 notebookIndexUpdated();
1532 // Publish a notebook
1533 @SuppressWarnings("unused")
1534 private void shareNotebook() {
1535 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1536 QTreeWidgetItem currentSelection;
1537 currentSelection = selections.get(0);
1538 String guid = currentSelection.text(2);
1540 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1544 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1545 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1546 n = listManager.getNotebookIndex().get(i);
1547 i = listManager.getNotebookIndex().size();
1551 String authToken = null;
1552 if (syncRunner.isConnected)
1553 authToken = syncRunner.authToken;
1554 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1559 // Delete an existing notebook
1560 @SuppressWarnings("unused")
1561 private void deleteNotebook() {
1562 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1563 boolean stacksFound = false;
1564 boolean notebooksFound = false;
1565 boolean assigned = false;
1566 // Check if any notes have this notebook
1567 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1568 for (int i=0; i<selections.size(); i++) {
1569 QTreeWidgetItem currentSelection;
1570 currentSelection = selections.get(i);
1571 String guid = currentSelection.text(2);
1572 if (!guid.equalsIgnoreCase("STACK")) {
1573 notebooksFound = true;
1574 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1575 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1576 if (noteGuid.equals(guid)) {
1578 j=listManager.getNoteIndex().size();
1579 i=selections.size();
1587 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1588 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1592 if (conn.getNotebookTable().getAll().size() == 1) {
1593 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1597 // If all notebooks are clear, verify the delete
1598 String msg1 = new String(tr("Delete selected notebooks?"));
1599 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1600 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1601 " not deleted unless selected?"));
1603 if (stacksFound && notebooksFound)
1605 if (!stacksFound && notebooksFound)
1607 if (stacksFound && !notebooksFound)
1609 if (QMessageBox.question(this, tr("Confirmation"), msg,
1610 QMessageBox.StandardButton.Yes,
1611 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1615 // If confirmed, delete the notebook
1616 for (int i=selections.size()-1; i>=0; i--) {
1617 QTreeWidgetItem currentSelection;
1618 currentSelection = selections.get(i);
1619 String guid = currentSelection.text(2);
1620 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1621 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1622 listManager.renameStack(currentSelection.text(0), "");
1624 conn.getNotebookTable().expungeNotebook(guid, true);
1625 listManager.deleteNotebook(guid);
1629 notebookIndexUpdated();
1630 // notebookTreeSelection();
1631 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1632 // listManager.countNotebookResults(listManager.getNoteIndex());
1633 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1635 // A note's notebook has been updated
1636 @SuppressWarnings("unused")
1637 private void updateNoteNotebook(String guid, String notebookGuid) {
1639 // Update the list manager
1640 listManager.updateNoteNotebook(guid, notebookGuid);
1641 listManager.countNotebookResults(listManager.getNoteIndex());
1642 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1644 // Find the name of the notebook
1645 String notebookName = null;
1646 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1647 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1648 notebookName = listManager.getNotebookIndex().get(i).getName();
1653 // If we found the name, update the browser window
1654 if (notebookName != null) {
1655 updateListNoteNotebook(guid, notebookName);
1656 if (guid.equals(currentNoteGuid)) {
1657 int pos = browserWindow.notebookBox.findText(notebookName);
1659 browserWindow.notebookBox.setCurrentIndex(pos);
1663 // If we're dealing with the current note, then we need to be sure and update the notebook there
1664 if (guid.equals(currentNoteGuid)) {
1665 if (currentNote != null) {
1666 currentNote.setNotebookGuid(notebookGuid);
1670 // Open/close notebooks
1671 @SuppressWarnings("unused")
1672 private void closeNotebooks() {
1673 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1675 if (!na.okClicked())
1679 listManager.getArchiveNotebookIndex().clear();
1681 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1682 String text = na.getClosedBookList().takeItem(i).text();
1683 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1684 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1685 Notebook n = listManager.getNotebookIndex().get(j);
1686 conn.getNotebookTable().setArchived(n.getGuid(),true);
1687 listManager.getArchiveNotebookIndex().add(n);
1688 j=listManager.getNotebookIndex().size();
1693 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1694 String text = na.getOpenBookList().takeItem(i).text();
1695 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1696 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1697 Notebook n = listManager.getNotebookIndex().get(j);
1698 conn.getNotebookTable().setArchived(n.getGuid(),false);
1699 j=listManager.getNotebookIndex().size();
1703 notebookTreeSelection();
1704 listManager.loadNotesIndex();
1705 notebookIndexUpdated();
1706 noteIndexUpdated(false);
1707 reloadTagTree(true);
1708 // noteIndexUpdated(false);
1710 // Build a list of non-closed notebooks
1711 List<Notebook> nbooks = new ArrayList<Notebook>();
1712 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1713 boolean found=false;
1714 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1715 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1719 nbooks.add(listManager.getNotebookIndex().get(i));
1722 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1723 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1724 browserWindow.setNotebookList(filteredBooks);
1726 // Update any external windows
1727 Iterator<String> set = externalWindows.keySet().iterator();
1728 while(set.hasNext())
1729 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1733 // Change the notebook's icon
1734 @SuppressWarnings("unused")
1735 private void setNotebookIcon() {
1736 boolean stackSelected = false;
1737 boolean allNotebookSelected = false;
1739 QTreeWidgetItem currentSelection;
1740 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1741 if (selections.size() == 0)
1744 currentSelection = selections.get(0);
1745 String guid = currentSelection.text(2);
1746 if (guid.equalsIgnoreCase(""))
1747 allNotebookSelected = true;
1748 if (guid.equalsIgnoreCase("STACK"))
1749 stackSelected = true;
1751 QIcon currentIcon = currentSelection.icon(0);
1755 if (!stackSelected && !allNotebookSelected) {
1756 icon = conn.getNotebookTable().getIcon(guid);
1758 dialog = new SetIcon(currentIcon, saveLastPath);
1759 dialog.setUseDefaultIcon(true);
1761 dialog = new SetIcon(icon, saveLastPath);
1762 dialog.setUseDefaultIcon(false);
1765 if (stackSelected) {
1766 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1768 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1771 dialog = new SetIcon(currentIcon, saveLastPath);
1772 dialog.setUseDefaultIcon(true);
1774 dialog = new SetIcon(icon, saveLastPath);
1775 dialog.setUseDefaultIcon(false);
1779 if (dialog.okPressed()) {
1780 saveLastPath = dialog.getPath();
1782 QIcon newIcon = dialog.getIcon();
1783 if (stackSelected) {
1784 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1785 if (newIcon == null) {
1786 newIcon = new QIcon(iconPath+"books2.png");
1788 currentSelection.setIcon(0,newIcon);
1791 if (allNotebookSelected) {
1792 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1793 if (newIcon == null) {
1794 newIcon = new QIcon(iconPath+"notebook-green.png");
1796 currentSelection.setIcon(0,newIcon);
1799 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1800 if (newIcon == null) {
1801 boolean isPublished = false;;
1802 boolean found = false;
1803 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1804 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1805 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1809 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1811 currentSelection.setIcon(0, newIcon);
1817 //***************************************************************
1818 //***************************************************************
1819 //** These functions deal with Tag menu items
1820 //***************************************************************
1821 //***************************************************************
1822 // Add a new notebook
1823 @SuppressWarnings("unused")
1824 private void addTag() {
1825 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1826 TagEdit edit = new TagEdit();
1827 edit.setTagList(listManager.getTagIndex());
1830 if (!edit.okPressed())
1833 Calendar currentTime = new GregorianCalendar();
1834 Long l = new Long(currentTime.getTimeInMillis());
1835 String randint = new String(Long.toString(l));
1837 Tag newTag = new Tag();
1838 newTag.setUpdateSequenceNum(0);
1839 newTag.setGuid(randint);
1840 newTag.setName(edit.getTag());
1841 conn.getTagTable().addTag(newTag, true);
1842 listManager.getTagIndex().add(newTag);
1843 reloadTagTree(true);
1845 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1847 @SuppressWarnings("unused")
1848 private void reloadTagTree() {
1849 reloadTagTree(false);
1851 private void reloadTagTree(boolean reload) {
1852 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1853 tagIndexUpdated(reload);
1854 boolean filter = false;
1855 listManager.countTagResults(listManager.getNoteIndex());
1856 if (notebookTree.selectedItems().size() > 0
1857 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1859 if (tagTree.selectedItems().size() > 0)
1861 tagTree.showAllTags(!filter);
1862 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1864 // Edit an existing tag
1865 @SuppressWarnings("unused")
1866 private void editTag() {
1867 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1868 TagEdit edit = new TagEdit();
1869 edit.setTitle("Edit Tag");
1870 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1871 QTreeWidgetItem currentSelection;
1872 currentSelection = selections.get(0);
1873 edit.setTag(currentSelection.text(0));
1874 edit.setTagList(listManager.getTagIndex());
1877 if (!edit.okPressed())
1880 String guid = currentSelection.text(2);
1881 currentSelection.setText(0,edit.getTag());
1883 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1884 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1885 listManager.getTagIndex().get(i).setName(edit.getTag());
1886 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1887 updateListTagName(guid);
1888 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1889 browserWindow.setTag(getTagNamesForNote(currentNote));
1890 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1894 browserWindow.setTag(getTagNamesForNote(currentNote));
1895 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1897 // Delete an existing tag
1898 @SuppressWarnings("unused")
1899 private void deleteTag() {
1900 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1902 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1903 QMessageBox.StandardButton.Yes,
1904 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1908 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1909 for (int i=selections.size()-1; i>=0; i--) {
1910 QTreeWidgetItem currentSelection;
1911 currentSelection = selections.get(i);
1912 removeTagItem(currentSelection.text(2));
1914 tagIndexUpdated(true);
1916 listManager.countTagResults(listManager.getNoteIndex());
1917 // tagTree.updateCounts(listManager.getTagCounter());
1918 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1920 // Remove a tag tree item. Go recursively down & remove the children too
1921 private void removeTagItem(String guid) {
1922 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1923 String parent = listManager.getTagIndex().get(j).getParentGuid();
1924 if (parent != null && parent.equals(guid)) {
1925 //Remove this tag's children
1926 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1929 //Now, remove this tag
1930 removeListTagName(guid);
1931 conn.getTagTable().expungeTag(guid, true);
1932 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1933 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1934 listManager.getTagIndex().remove(a);
1939 // Setup the tree containing the user's tags
1940 private void initializeTagTree() {
1941 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1942 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1943 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
1944 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1945 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1946 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1948 // Listener when a tag is selected
1949 private void tagTreeSelection() {
1950 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1953 clearAttributeFilter();
1954 clearSavedSearchFilter();
1956 menuBar.noteRestoreAction.setVisible(false);
1958 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1959 QTreeWidgetItem currentSelection;
1960 selectedTagGUIDs.clear();
1961 for (int i=0; i<selections.size(); i++) {
1962 currentSelection = selections.get(i);
1963 selectedTagGUIDs.add(currentSelection.text(2));
1965 if (selections.size() > 0) {
1966 menuBar.tagEditAction.setEnabled(true);
1967 menuBar.tagDeleteAction.setEnabled(true);
1968 menuBar.tagIconAction.setEnabled(true);
1971 menuBar.tagEditAction.setEnabled(false);
1972 menuBar.tagDeleteAction.setEnabled(false);
1973 menuBar.tagIconAction.setEnabled(true);
1975 listManager.setSelectedTags(selectedTagGUIDs);
1976 listManager.loadNotesIndex();
1977 noteIndexUpdated(false);
1978 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1980 // trigger the tag index to be refreshed
1981 @SuppressWarnings("unused")
1982 private void tagIndexUpdated() {
1983 tagIndexUpdated(true);
1985 private void tagIndexUpdated(boolean reload) {
1986 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
1987 if (selectedTagGUIDs == null)
1988 selectedTagGUIDs = new ArrayList<String>();
1990 listManager.reloadTagIndex();
1992 tagTree.blockSignals(true);
1994 tagTree.setIcons(conn.getTagTable().getAllIcons());
1995 tagTree.load(listManager.getTagIndex());
1997 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
1998 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2000 selectedTagGUIDs.remove(i);
2002 tagTree.blockSignals(false);
2004 browserWindow.setTag(getTagNamesForNote(currentNote));
2005 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2007 // Show/Hide note information
2008 private void toggleTagWindow() {
2009 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2010 if (tagTree.isVisible())
2014 menuBar.hideTags.setChecked(tagTree.isVisible());
2015 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2016 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2018 // A note's tags have been updated
2019 @SuppressWarnings("unused")
2020 private void updateNoteTags(String guid, List<String> tags) {
2021 // Save any new tags. We'll need them later.
2022 List<String> newTags = new ArrayList<String>();
2023 for (int i=0; i<tags.size(); i++) {
2024 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2025 newTags.add(tags.get(i));
2028 listManager.saveNoteTags(guid, tags);
2029 listManager.countTagResults(listManager.getNoteIndex());
2030 StringBuffer names = new StringBuffer("");
2031 for (int i=0; i<tags.size(); i++) {
2032 names = names.append(tags.get(i));
2033 if (i<tags.size()-1) {
2034 names.append(Global.tagDelimeter + " ");
2037 browserWindow.setTag(names.toString());
2040 // Now, we need to add any new tags to the tag tree
2041 for (int i=0; i<newTags.size(); i++)
2042 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2044 // Get a string containing all tag names for a note
2045 private String getTagNamesForNote(Note n) {
2046 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2047 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2049 StringBuffer buffer = new StringBuffer(100);
2050 Vector<String> v = new Vector<String>();
2051 List<String> guids = n.getTagGuids();
2056 for (int i=0; i<guids.size(); i++) {
2057 v.add(listManager.getTagNameByGuid(guids.get(i)));
2059 Comparator<String> comparator = Collections.reverseOrder();
2060 Collections.sort(v,comparator);
2061 Collections.reverse(v);
2063 for (int i = 0; i<v.size(); i++) {
2065 buffer.append(", ");
2066 buffer.append(v.get(i));
2069 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2070 return buffer.toString();
2072 // Tags were added via dropping notes from the note list
2073 @SuppressWarnings("unused")
2074 private void tagsAdded(String noteGuid, String tagGuid) {
2075 String tagName = null;
2076 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2077 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2078 tagName = listManager.getTagIndex().get(i).getName();
2079 i=listManager.getTagIndex().size();
2082 if (tagName == null)
2085 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2086 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2087 List<String> tagNames = new ArrayList<String>();
2088 tagNames.add(new String(tagName));
2089 Note n = listManager.getMasterNoteIndex().get(i);
2090 for (int j=0; j<n.getTagNames().size(); j++) {
2091 tagNames.add(new String(n.getTagNames().get(j)));
2093 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2094 if (n.getGuid().equals(currentNoteGuid)) {
2095 Collections.sort(tagNames);
2096 String display = "";
2097 for (int j=0; j<tagNames.size(); j++) {
2098 display = display+tagNames.get(j);
2099 if (j+2<tagNames.size())
2100 display = display+Global.tagDelimeter+" ";
2102 browserWindow.setTag(display);
2104 i=listManager.getMasterNoteIndex().size();
2109 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2111 private void clearTagFilter() {
2112 tagTree.blockSignals(true);
2113 tagTree.clearSelection();
2114 menuBar.noteRestoreAction.setVisible(false);
2115 menuBar.tagEditAction.setEnabled(false);
2116 menuBar.tagDeleteAction.setEnabled(false);
2117 menuBar.tagIconAction.setEnabled(false);
2118 selectedTagGUIDs.clear();
2119 listManager.setSelectedTags(selectedTagGUIDs);
2120 tagTree.blockSignals(false);
2122 // Change the icon for a tag
2123 @SuppressWarnings("unused")
2124 private void setTagIcon() {
2125 QTreeWidgetItem currentSelection;
2126 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2127 if (selections.size() == 0)
2130 currentSelection = selections.get(0);
2131 String guid = currentSelection.text(2);
2133 QIcon currentIcon = currentSelection.icon(0);
2134 QIcon icon = conn.getTagTable().getIcon(guid);
2137 dialog = new SetIcon(currentIcon, saveLastPath);
2138 dialog.setUseDefaultIcon(true);
2140 dialog = new SetIcon(icon, saveLastPath);
2141 dialog.setUseDefaultIcon(false);
2144 if (dialog.okPressed()) {
2145 saveLastPath = dialog.getPath();
2146 QIcon newIcon = dialog.getIcon();
2147 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2148 if (newIcon == null)
2149 newIcon = new QIcon(iconPath+"tag.png");
2150 currentSelection.setIcon(0, newIcon);
2156 //***************************************************************
2157 //***************************************************************
2158 //** These functions deal with Saved Search menu items
2159 //***************************************************************
2160 //***************************************************************
2161 // Add a new notebook
2162 @SuppressWarnings("unused")
2163 private void addSavedSearch() {
2164 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2165 SavedSearchEdit edit = new SavedSearchEdit();
2166 edit.setSearchList(listManager.getSavedSearchIndex());
2169 if (!edit.okPressed())
2172 Calendar currentTime = new GregorianCalendar();
2173 Long l = new Long(currentTime.getTimeInMillis());
2174 String randint = new String(Long.toString(l));
2176 SavedSearch search = new SavedSearch();
2177 search.setUpdateSequenceNum(0);
2178 search.setGuid(randint);
2179 search.setName(edit.getName());
2180 search.setQuery(edit.getQuery());
2181 search.setFormat(QueryFormat.USER);
2182 listManager.getSavedSearchIndex().add(search);
2183 conn.getSavedSearchTable().addSavedSearch(search, true);
2184 savedSearchIndexUpdated();
2185 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2187 // Edit an existing tag
2188 @SuppressWarnings("unused")
2189 private void editSavedSearch() {
2190 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2191 SavedSearchEdit edit = new SavedSearchEdit();
2192 edit.setTitle(tr("Edit Search"));
2193 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2194 QTreeWidgetItem currentSelection;
2195 currentSelection = selections.get(0);
2196 String guid = currentSelection.text(1);
2197 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2198 edit.setName(currentSelection.text(0));
2199 edit.setQuery(s.getQuery());
2200 edit.setSearchList(listManager.getSavedSearchIndex());
2203 if (!edit.okPressed())
2206 List<SavedSearch> list = listManager.getSavedSearchIndex();
2207 SavedSearch search = null;
2208 boolean found = false;
2209 for (int i=0; i<list.size(); i++) {
2210 search = list.get(i);
2211 if (search.getGuid().equals(guid)) {
2218 search.setName(edit.getName());
2219 search.setQuery(edit.getQuery());
2220 conn.getSavedSearchTable().updateSavedSearch(search, true);
2221 savedSearchIndexUpdated();
2222 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2224 // Delete an existing tag
2225 @SuppressWarnings("unused")
2226 private void deleteSavedSearch() {
2227 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2229 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2230 QMessageBox.StandardButton.Yes,
2231 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2235 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2236 for (int i=selections.size()-1; i>=0; i--) {
2237 QTreeWidgetItem currentSelection;
2238 currentSelection = selections.get(i);
2239 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2240 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2241 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2242 listManager.getSavedSearchIndex().remove(j);
2243 j=listManager.getSavedSearchIndex().size()+1;
2246 selections.remove(i);
2248 savedSearchIndexUpdated();
2249 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2251 // Setup the tree containing the user's tags
2252 private void initializeSavedSearchTree() {
2253 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2254 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2255 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2257 // Listener when a tag is selected
2258 @SuppressWarnings("unused")
2259 private void savedSearchTreeSelection() {
2260 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2262 clearNotebookFilter();
2265 clearAttributeFilter();
2267 String currentGuid = selectedSavedSearchGUID;
2268 menuBar.savedSearchEditAction.setEnabled(true);
2269 menuBar.savedSearchDeleteAction.setEnabled(true);
2270 menuBar.savedSearchIconAction.setEnabled(true);
2271 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2272 QTreeWidgetItem currentSelection;
2273 selectedSavedSearchGUID = "";
2274 for (int i=0; i<selections.size(); i++) {
2275 currentSelection = selections.get(i);
2276 if (currentSelection.text(1).equals(currentGuid)) {
2277 currentSelection.setSelected(false);
2279 selectedSavedSearchGUID = currentSelection.text(1);
2281 // i = selections.size() +1;
2284 // There is the potential for no notebooks to be selected if this
2285 // happens then we make it look like all notebooks were selecetd.
2286 // If that happens, just select the "all notebooks"
2287 if (selections.size()==0) {
2288 clearSavedSearchFilter();
2290 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2292 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2294 private void clearSavedSearchFilter() {
2295 menuBar.savedSearchEditAction.setEnabled(false);
2296 menuBar.savedSearchDeleteAction.setEnabled(false);
2297 menuBar.savedSearchIconAction.setEnabled(false);
2298 savedSearchTree.blockSignals(true);
2299 savedSearchTree.clearSelection();
2300 savedSearchTree.blockSignals(false);
2301 selectedSavedSearchGUID = "";
2302 searchField.setEditText("");
2303 searchPerformed = false;
2304 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2306 // trigger the tag index to be refreshed
2307 private void savedSearchIndexUpdated() {
2308 if (selectedSavedSearchGUID == null)
2309 selectedSavedSearchGUID = new String();
2310 savedSearchTree.blockSignals(true);
2311 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2312 savedSearchTree.load(listManager.getSavedSearchIndex());
2313 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2314 savedSearchTree.blockSignals(false);
2316 // trigger when the saved search selection changes
2317 @SuppressWarnings("unused")
2318 private void updateSavedSearchSelection() {
2319 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2321 menuBar.savedSearchEditAction.setEnabled(true);
2322 menuBar.savedSearchDeleteAction.setEnabled(true);
2323 menuBar.savedSearchIconAction.setEnabled(true);
2324 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2326 if (selections.size() > 0) {
2327 menuBar.savedSearchEditAction.setEnabled(true);
2328 menuBar.savedSearchDeleteAction.setEnabled(true);
2329 menuBar.savedSearchIconAction.setEnabled(true);
2330 selectedSavedSearchGUID = selections.get(0).text(1);
2331 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2332 searchField.setEditText(s.getQuery());
2334 menuBar.savedSearchEditAction.setEnabled(false);
2335 menuBar.savedSearchDeleteAction.setEnabled(false);
2336 menuBar.savedSearchIconAction.setEnabled(false);
2337 selectedSavedSearchGUID = "";
2338 searchField.setEditText("");
2340 searchFieldChanged();
2342 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2346 // Show/Hide note information
2347 private void toggleSavedSearchWindow() {
2348 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2349 if (savedSearchTree.isVisible())
2350 savedSearchTree.hide();
2352 savedSearchTree.show();
2353 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2355 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2356 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2358 // Change the icon for a saved search
2359 @SuppressWarnings("unused")
2360 private void setSavedSearchIcon() {
2361 QTreeWidgetItem currentSelection;
2362 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2363 if (selections.size() == 0)
2366 currentSelection = selections.get(0);
2367 String guid = currentSelection.text(1);
2369 QIcon currentIcon = currentSelection.icon(0);
2370 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2373 dialog = new SetIcon(currentIcon, saveLastPath);
2374 dialog.setUseDefaultIcon(true);
2376 dialog = new SetIcon(icon, saveLastPath);
2377 dialog.setUseDefaultIcon(false);
2380 if (dialog.okPressed()) {
2381 saveLastPath = dialog.getPath();
2382 QIcon newIcon = dialog.getIcon();
2383 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2384 if (newIcon == null)
2385 newIcon = new QIcon(iconPath+"search.png");
2386 currentSelection.setIcon(0, newIcon);
2394 //***************************************************************
2395 //***************************************************************
2396 //** These functions deal with Help menu & tool menu items
2397 //***************************************************************
2398 //***************************************************************
2399 // Show database status
2400 @SuppressWarnings("unused")
2401 private void databaseStatus() {
2403 indexRunner.interrupt = true;
2404 thumbnailRunner.interrupt = true;
2405 int dirty = conn.getNoteTable().getDirtyCount();
2406 int unindexed = conn.getNoteTable().getUnindexedCount();
2407 DatabaseStatus status = new DatabaseStatus();
2408 status.setUnsynchronized(dirty);
2409 status.setUnindexed(unindexed);
2410 status.setNoteCount(conn.getNoteTable().getNoteCount());
2411 status.setNotebookCount(listManager.getNotebookIndex().size());
2412 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2413 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2414 status.setTagCount(listManager.getTagIndex().size());
2415 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2416 status.setWordCount(conn.getWordsTable().getWordCount());
2420 // Compact the database
2421 @SuppressWarnings("unused")
2422 private void compactDatabase() {
2423 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2424 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2425 "but please be aware that depending upon the size of your database this can be time consuming " +
2426 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2427 QMessageBox.StandardButton.Yes,
2428 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2431 setMessage("Compacting database.");
2433 listManager.compactDatabase();
2435 setMessage("Database compact is complete.");
2436 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2438 @SuppressWarnings("unused")
2439 private void accountInformation() {
2440 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2441 AccountDialog dialog = new AccountDialog();
2443 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2445 @SuppressWarnings("unused")
2446 private void releaseNotes() {
2447 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2448 QDialog dialog = new QDialog(this);
2449 QHBoxLayout layout = new QHBoxLayout();
2450 QTextEdit textBox = new QTextEdit();
2451 layout.addWidget(textBox);
2452 textBox.setReadOnly(true);
2453 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2454 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2455 QIODevice.OpenModeFlag.Text)))
2457 textBox.setText(file.readAll().toString());
2459 dialog.setWindowTitle(tr("Release Notes"));
2460 dialog.setLayout(layout);
2462 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2464 // Called when user picks Log from the help menu
2465 @SuppressWarnings("unused")
2466 private void logger() {
2467 logger.log(logger.HIGH, "Entering NeverNote.logger");
2468 QDialog dialog = new QDialog(this);
2469 QHBoxLayout layout = new QHBoxLayout();
2470 QListWidget textBox = new QListWidget();
2471 layout.addWidget(textBox);
2472 textBox.addItems(emitLog);
2474 dialog.setLayout(layout);
2475 dialog.setWindowTitle(tr("Mesasge Log"));
2477 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2479 // Menu option "help/about" was selected
2480 @SuppressWarnings("unused")
2481 private void about() {
2482 logger.log(logger.HIGH, "Entering NeverNote.about");
2483 QMessageBox.about(this,
2484 tr("About NeverNote"),
2485 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2487 +tr("<hr></center>Evernote"
2488 +"An Open Source Evernote Client.<br><br>"
2489 +"Licensed under GPL v2. <br><hr><br>"
2490 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2491 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2492 +"PDFRenderer is licened under the LGPL<br>"
2493 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2494 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2495 +"Jazzy is licened under the LGPL<br>"
2496 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2497 logger.log(logger.HIGH, "Leaving NeverNote.about");
2499 // Hide the entire left hand side
2500 @SuppressWarnings("unused")
2501 private void toggleLeftSide() {
2504 hidden = !menuBar.hideLeftSide.isChecked();
2505 menuBar.hideLeftSide.setChecked(!hidden);
2507 if (notebookTree.isVisible() != hidden)
2508 toggleNotebookWindow();
2509 if (savedSearchTree.isVisible() != hidden)
2510 toggleSavedSearchWindow();
2511 if (tagTree.isVisible() != hidden)
2513 if (attributeTree.isVisible() != hidden)
2514 toggleAttributesWindow();
2515 if (trashTree.isVisible() != hidden)
2516 toggleTrashWindow();
2518 Global.saveWindowVisible("leftPanel", hidden);
2521 public void checkForUpdates() {
2522 // Send off thread to check for a new version
2523 versionChecker = new QNetworkAccessManager(this);
2524 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2525 QNetworkRequest request = new QNetworkRequest();
2526 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2527 versionChecker.get(request);
2529 @SuppressWarnings("unused")
2530 private void upgradeFileRead(QNetworkReply reply) {
2531 if (!reply.isReadable())
2534 String winVersion = Global.version;
2535 String osxVersion = Global.version;
2536 String linuxVersion = Global.version;
2537 String linux64Version = Global.version;
2538 String version = Global.version;
2540 // Determine the versions available
2541 QByteArray data = reply.readLine();
2542 while (data != null && !reply.atEnd()) {
2543 String line = data.toString();
2545 if (line.contains(":"))
2546 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2549 if (line.toLowerCase().contains("windows"))
2550 winVersion = lineVersion;
2551 else if (line.toLowerCase().contains("os-x"))
2552 osxVersion = lineVersion;
2553 else if (line.toLowerCase().contains("linux amd64"))
2554 linux64Version = lineVersion;
2555 else if (line.toLowerCase().contains("linux i386"))
2556 linuxVersion = lineVersion;
2557 else if (line.toLowerCase().contains("default"))
2558 version = lineVersion;
2560 // Read the next line
2561 data = reply.readLine();
2564 // Now we need to determine what system we are on.
2565 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2566 version = winVersion;
2567 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2568 version = osxVersion;
2569 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2570 if (System.getProperty("os.arch").contains("amd64") ||
2571 System.getProperty("os.arch").contains("x86_64"))
2572 version = linux64Version;
2574 version = linuxVersion;
2578 if (Global.version.equals(version))
2581 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2583 if (dialog.remindMe())
2584 Global.setCheckVersionUpgrade(true);
2586 Global.setCheckVersionUpgrade(false);
2590 //***************************************************************
2591 //***************************************************************
2592 //** These functions deal with the Toolbar
2593 //***************************************************************
2594 //***************************************************************
2595 // Text in the search bar has been cleared
2596 private void searchFieldCleared() {
2599 // This is done because we want to force a reload of
2600 // images. Some images we may want to highlight the text.
2601 readOnlyCache.clear();
2602 inkNoteCache.clear();
2604 QWebSettings.setMaximumPagesInCache(0);
2605 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2607 searchField.setEditText("");
2608 saveNoteColumnPositions();
2609 saveNoteIndexWidth();
2610 noteIndexUpdated(true);
2611 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2612 currentNote = listManager.getNoteIndex().get(0);
2613 currentNoteGuid = currentNote.getGuid();
2615 if (currentNote != null)
2616 loadNoteBrowserInformation(browserWindow);
2618 // text in the search bar changed. We only use this to tell if it was cleared,
2619 // otherwise we trigger off searchFieldChanged.
2620 @SuppressWarnings("unused")
2621 private void searchFieldTextChanged(String text) {
2622 QWebSettings.setMaximumPagesInCache(0);
2623 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2625 if (text.trim().equals("")) {
2626 searchFieldCleared();
2627 if (searchPerformed) {
2629 // This is done because we want to force a reload of
2630 // images. Some images we may want to highlight the text.
2632 readOnlyCache.clear();
2633 inkNoteCache.clear();
2635 listManager.setEnSearch("");
2636 listManager.loadNotesIndex();
2637 refreshEvernoteNote(true);
2638 noteIndexUpdated(false);
2640 searchPerformed = false;
2643 // Text in the toolbar has changed
2644 private void searchFieldChanged() {
2645 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2647 readOnlyCache.clear();
2648 inkNoteCache.clear();
2649 saveNoteColumnPositions();
2650 saveNoteIndexWidth();
2651 String text = searchField.currentText();
2652 listManager.setEnSearch(text.trim());
2653 listManager.loadNotesIndex();
2654 //--->>> noteIndexUpdated(true);
2655 noteIndexUpdated(false);
2656 refreshEvernoteNote(true);
2657 searchPerformed = true;
2658 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2661 // Build the window tool bar
2662 private void setupToolBar() {
2663 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2664 toolBar = addToolBar(tr("Tool Bar"));
2665 menuBar.setupToolBarVisible();
2666 if (!Global.isWindowVisible("toolBar"))
2667 toolBar.setVisible(false);
2669 toolBar.setVisible(true);
2671 prevButton = toolBar.addAction("Previous");
2672 QIcon prevIcon = new QIcon(iconPath+"back.png");
2673 prevButton.setIcon(prevIcon);
2674 prevButton.triggered.connect(this, "previousViewedAction()");
2675 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2677 nextButton = toolBar.addAction("Next");
2678 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2679 nextButton.setIcon(nextIcon);
2680 nextButton.triggered.connect(this, "nextViewedAction()");
2681 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2683 upButton = toolBar.addAction("Up");
2684 QIcon upIcon = new QIcon(iconPath+"up.png");
2685 upButton.setIcon(upIcon);
2686 upButton.triggered.connect(this, "upAction()");
2687 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2690 downButton = toolBar.addAction("Down");
2691 QIcon downIcon = new QIcon(iconPath+"down.png");
2692 downButton.setIcon(downIcon);
2693 downButton.triggered.connect(this, "downAction()");
2694 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2696 synchronizeButton = toolBar.addAction("Synchronize");
2697 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2698 synchronizeIconAngle = 0;
2699 synchronizeButton.triggered.connect(this, "evernoteSync()");
2700 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2702 printButton = toolBar.addAction("Print");
2703 QIcon printIcon = new QIcon(iconPath+"print.png");
2704 printButton.setIcon(printIcon);
2705 printButton.triggered.connect(this, "printNote()");
2706 togglePrintButton(Global.isToolbarButtonVisible("print"));
2708 tagButton = toolBar.addAction("Tag");
2709 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2710 tagButton.setIcon(tagIcon);
2711 tagButton.triggered.connect(browserWindow, "modifyTags()");
2712 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2714 attributeButton = toolBar.addAction("Attributes");
2715 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2716 attributeButton.setIcon(attributeIcon);
2717 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2718 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2720 emailButton = toolBar.addAction("Email");
2721 QIcon emailIcon = new QIcon(iconPath+"email.png");
2722 emailButton.setIcon(emailIcon);
2723 emailButton.triggered.connect(this, "emailNote()");
2724 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2726 deleteButton = toolBar.addAction("Delete");
2727 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2728 deleteButton.setIcon(deleteIcon);
2729 deleteButton.triggered.connect(this, "deleteNote()");
2730 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2732 newButton = toolBar.addAction("New");
2733 QIcon newIcon = new QIcon(iconPath+"new.png");
2734 newButton.triggered.connect(this, "addNote()");
2735 newButton.setIcon(newIcon);
2736 toggleNewButton(Global.isToolbarButtonVisible("new"));
2738 allNotesButton = toolBar.addAction("All Notes");
2739 QIcon allIcon = new QIcon(iconPath+"books.png");
2740 allNotesButton.triggered.connect(this, "allNotes()");
2741 allNotesButton.setIcon(allIcon);
2742 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2744 toolBar.addSeparator();
2745 toolBar.addWidget(new QLabel(tr("Quota:")));
2746 toolBar.addWidget(quotaBar);
2747 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2749 toolBar.addSeparator();
2752 zoomSpinner = new QSpinBox();
2753 zoomSpinner.setMinimum(10);
2754 zoomSpinner.setMaximum(1000);
2755 zoomSpinner.setAccelerated(true);
2756 zoomSpinner.setSingleStep(10);
2757 zoomSpinner.setValue(100);
2758 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2759 toolBar.addWidget(new QLabel(tr("Zoom")));
2760 toolBar.addWidget(zoomSpinner);
2762 //toolBar.addWidget(new QLabel(" "));
2763 toolBar.addSeparator();
2764 toolBar.addWidget(new QLabel(tr(" Search:")));
2765 toolBar.addWidget(searchField);
2766 QSizePolicy sizePolicy = new QSizePolicy();
2767 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2768 searchField.setSizePolicy(sizePolicy);
2769 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2771 searchClearButton = toolBar.addAction("Search Clear");
2772 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2773 searchClearButton.setIcon(searchClearIcon);
2774 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2775 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2777 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2779 // Update the sychronize button picture
2781 public QMenu createPopupMenu() {
2782 QMenu contextMenu = super.createPopupMenu();
2784 contextMenu.addSeparator();
2785 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2786 contextMenu.addAction(prevAction);
2787 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2789 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2790 contextMenu.addAction(nextAction);
2791 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2793 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2794 contextMenu.addAction(upAction);
2795 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2797 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2798 contextMenu.addAction(downAction);
2799 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2801 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2802 contextMenu.addAction(synchronizeAction);
2803 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2805 QAction printAction = addContextAction("print", tr("Print"));
2806 contextMenu.addAction(printAction);
2807 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2809 QAction tagAction = addContextAction("tag", tr("Tag"));
2810 contextMenu.addAction(tagAction);
2811 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2813 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2814 contextMenu.addAction(attributeAction);
2815 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2817 QAction emailAction = addContextAction("email", tr("Email"));
2818 contextMenu.addAction(emailAction);
2819 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2821 QAction deleteAction = addContextAction("delete", tr("Delete"));
2822 contextMenu.addAction(deleteAction);
2823 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2825 QAction newAction = addContextAction("new", tr("Add"));
2826 contextMenu.addAction(newAction);
2827 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2829 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2830 contextMenu.addAction(allNotesAction);
2831 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2833 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2834 contextMenu.addAction(searchClearAction);
2835 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2840 private QAction addContextAction(String config, String name) {
2841 QAction newAction = new QAction(this);
2842 newAction.setText(name);
2843 newAction.setCheckable(true);
2844 newAction.setChecked(Global.isToolbarButtonVisible(config));
2847 private void togglePrevArrowButton(Boolean toggle) {
2848 prevButton.setVisible(toggle);
2849 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2851 private void toggleNextArrowButton(Boolean toggle) {
2852 nextButton.setVisible(toggle);
2853 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2855 private void toggleUpArrowButton(Boolean toggle) {
2856 upButton.setVisible(toggle);
2857 Global.saveToolbarButtonsVisible("upArrow", toggle);
2859 private void toggleDownArrowButton(Boolean toggle) {
2860 downButton.setVisible(toggle);
2861 Global.saveToolbarButtonsVisible("downArrow", toggle);
2863 private void toggleSynchronizeButton(Boolean toggle) {
2864 synchronizeButton.setVisible(toggle);
2865 Global.saveToolbarButtonsVisible("synchronize", toggle);
2867 private void togglePrintButton(Boolean toggle) {
2868 printButton.setVisible(toggle);
2869 Global.saveToolbarButtonsVisible("print", toggle);
2871 private void toggleTagButton(Boolean toggle) {
2872 tagButton.setVisible(toggle);
2873 Global.saveToolbarButtonsVisible("tag", toggle);
2875 private void toggleAttributeButton(Boolean toggle) {
2876 attributeButton.setVisible(toggle);
2877 Global.saveToolbarButtonsVisible("attribute", toggle);
2879 private void toggleEmailButton(Boolean toggle) {
2880 emailButton.setVisible(toggle);
2881 Global.saveToolbarButtonsVisible("email", toggle);
2883 private void toggleDeleteButton(Boolean toggle) {
2884 deleteButton.setVisible(toggle);
2885 Global.saveToolbarButtonsVisible("delete", toggle);
2887 private void toggleNewButton(Boolean toggle) {
2888 newButton.setVisible(toggle);
2889 Global.saveToolbarButtonsVisible("new", toggle);
2891 private void toggleAllNotesButton(Boolean toggle) {
2892 allNotesButton.setVisible(toggle);
2893 Global.saveToolbarButtonsVisible("allNotes", toggle);
2895 private void toggleSearchClearButton(Boolean toggle) {
2896 searchClearButton.setVisible(toggle);
2897 Global.saveToolbarButtonsVisible("searchClear", toggle);
2904 @SuppressWarnings("unused")
2905 private void updateSyncButton() {
2907 if (syncIcons == null) {
2908 syncIcons = new ArrayList<QPixmap>();
2910 synchronizeIconAngle = 0;
2911 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2913 for (int i=0; i<=360; i++) {
2914 QPixmap rotatedPix = new QPixmap(pix.size());
2915 QPainter p = new QPainter(rotatedPix);
2916 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2917 QSize size = pix.size();
2918 p.translate(size.width()/2, size.height()/2);
2921 p.setBackgroundMode(BGMode.OpaqueMode);
2922 p.translate(-size.width()/2, -size.height()/2);
2923 p.drawPixmap(0,0, pix);
2925 syncIcons.add(rotatedPix);
2929 synchronizeIconAngle++;
2930 if (synchronizeIconAngle > 359)
2931 synchronizeIconAngle=0;
2932 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2935 // Synchronize with Evernote
2936 @SuppressWarnings("unused")
2937 private void evernoteSync() {
2938 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2939 if (!Global.isConnected)
2941 if (Global.isConnected)
2942 synchronizeAnimationTimer.start(5);
2943 // synchronizeAnimationTimer.start(200);
2945 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2947 private void updateQuotaBar() {
2948 long limit = Global.getUploadLimit();
2949 long amount = Global.getUploadAmount();
2950 if (amount>0 && limit>0) {
2951 int percent =(int)(amount*100/limit);
2952 quotaBar.setValue(percent);
2954 quotaBar.setValue(0);
2957 @SuppressWarnings("unused")
2958 private void zoomChanged() {
2959 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2962 //****************************************************************
2963 //****************************************************************
2964 //* System Tray functions
2965 //****************************************************************
2966 //****************************************************************
2967 private void trayToggleVisible() {
2972 if (windowMaximized)
2979 @SuppressWarnings("unused")
2980 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2981 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2982 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2983 trayToggleVisible();
2988 //***************************************************************
2989 //***************************************************************
2990 //** These functions deal with the trash tree
2991 //***************************************************************
2992 //***************************************************************
2993 // Setup the tree containing the trash.
2994 @SuppressWarnings("unused")
2995 private void trashTreeSelection() {
2996 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
2998 clearNotebookFilter();
3000 clearAttributeFilter();
3001 clearSavedSearchFilter();
3003 String tempGuid = currentNoteGuid;
3005 // currentNoteGuid = "";
3006 currentNote = new Note();
3007 selectedNoteGUIDs.clear();
3008 listManager.getSelectedNotebooks().clear();
3009 listManager.getSelectedTags().clear();
3010 listManager.setSelectedSavedSearch("");
3011 browserWindow.clear();
3013 // toggle the add buttons
3014 newButton.setEnabled(!newButton.isEnabled());
3015 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3016 menuBar.noteAdd.setVisible(true);
3018 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3019 if (selections.size() == 0) {
3020 currentNoteGuid = trashNoteGuid;
3021 trashNoteGuid = tempGuid;
3022 Global.showDeleted = false;
3023 menuBar.noteRestoreAction.setEnabled(false);
3024 menuBar.noteRestoreAction.setVisible(false);
3027 currentNoteGuid = trashNoteGuid;
3028 trashNoteGuid = tempGuid;
3029 menuBar.noteRestoreAction.setEnabled(true);
3030 menuBar.noteRestoreAction.setVisible(true);
3031 Global.showDeleted = true;
3033 listManager.loadNotesIndex();
3034 noteIndexUpdated(false);
3035 //// browserWindow.setEnabled(newButton.isEnabled());
3036 browserWindow.setReadOnly(!newButton.isEnabled());
3037 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3039 // Empty the trash file
3040 @SuppressWarnings("unused")
3041 private void emptyTrash() {
3042 // browserWindow.clear();
3043 listManager.emptyTrash();
3044 if (trashTree.selectedItems().size() > 0) {
3045 listManager.getSelectedNotebooks().clear();
3046 listManager.getSelectedTags().clear();
3047 listManager.setSelectedSavedSearch("");
3048 newButton.setEnabled(!newButton.isEnabled());
3049 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3050 menuBar.noteAdd.setVisible(true);
3051 browserWindow.clear();
3054 clearNotebookFilter();
3055 clearSavedSearchFilter();
3056 clearAttributeFilter();
3058 Global.showDeleted = false;
3059 menuBar.noteRestoreAction.setEnabled(false);
3060 menuBar.noteRestoreAction.setVisible(false);
3062 listManager.loadNotesIndex();
3063 //--->>> noteIndexUpdated(true);
3064 noteIndexUpdated(false);
3067 // Show/Hide trash window
3068 private void toggleTrashWindow() {
3069 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3070 if (trashTree.isVisible())
3074 menuBar.hideTrash.setChecked(trashTree.isVisible());
3076 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3077 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3079 private void clearTrashFilter() {
3080 Global.showDeleted = false;
3081 newButton.setEnabled(true);
3082 menuBar.noteAdd.setEnabled(true);
3083 menuBar.noteAdd.setVisible(true);
3084 trashTree.blockSignals(true);
3085 trashTree.clearSelection();
3086 trashTree.blockSignals(false);
3091 //***************************************************************
3092 //***************************************************************
3093 //** These functions deal with connection settings
3094 //***************************************************************
3095 //***************************************************************
3096 // SyncRunner had a problem and things are disconnected
3097 @SuppressWarnings("unused")
3098 private void remoteErrorDisconnect() {
3099 menuBar.connectAction.setText(tr("Connect"));
3100 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3101 menuBar.synchronizeAction.setEnabled(false);
3102 Global.isConnected = false;
3103 synchronizeAnimationTimer.stop();
3106 // Do a manual connect/disconnect
3107 private void remoteConnect() {
3108 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3110 if (Global.isConnected) {
3111 Global.isConnected = false;
3112 syncRunner.enDisconnect();
3113 setupConnectMenuOptions();
3118 AESEncrypter aes = new AESEncrypter();
3120 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3121 } catch (FileNotFoundException e) {
3122 // File not found, so we'll just get empty strings anyway.
3124 String userid = aes.getUserid();
3125 String password = aes.getPassword();
3126 if (!userid.equals("") && !password.equals("")) {
3127 Global.username = userid;
3128 Global.password = password;
3131 // Show the login dialog box
3132 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3133 LoginDialog login = new LoginDialog();
3136 if (!login.okPressed()) {
3140 Global.username = login.getUserid();
3141 Global.password = login.getPassword();
3143 syncRunner.username = Global.username;
3144 syncRunner.password = Global.password;
3145 syncRunner.userStoreUrl = Global.userStoreUrl;
3146 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3147 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3149 if (Global.getProxyValue("url").equals("")) {
3150 System.setProperty("http.proxyHost","") ;
3151 System.setProperty("http.proxyPort", "") ;
3152 System.setProperty("https.proxyHost","") ;
3153 System.setProperty("https.proxyPort", "") ;
3156 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3157 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3158 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3159 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3161 if (Global.getProxyValue("userid").equals("")) {
3162 Authenticator.setDefault(new Authenticator() {
3164 protected PasswordAuthentication getPasswordAuthentication() {
3166 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3172 syncRunner.enConnect();
3173 Global.isConnected = syncRunner.isConnected;
3175 setupConnectMenuOptions();
3176 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3178 private void setupConnectMenuOptions() {
3179 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3180 if (!Global.isConnected) {
3181 menuBar.connectAction.setText(tr("Connect"));
3182 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3183 menuBar.synchronizeAction.setEnabled(false);
3185 menuBar.connectAction.setText(tr("Disconnect"));
3186 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3187 menuBar.synchronizeAction.setEnabled(true);
3189 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3194 //***************************************************************
3195 //***************************************************************
3196 //** These functions deal with the GUI Attribute tree
3197 //***************************************************************
3198 //***************************************************************
3199 @SuppressWarnings("unused")
3200 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3202 // clearTagFilter();
3203 // clearNotebookFilter();
3205 // clearSavedSearchFilter();
3207 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3208 if (item.childCount() > 0) {
3209 item.setSelected(false);
3211 Global.createdBeforeFilter.reset();
3212 Global.createdSinceFilter.reset();
3213 Global.changedBeforeFilter.reset();
3214 Global.changedSinceFilter.reset();
3215 Global.containsFilter.reset();
3216 attributeTreeSelected = item;
3217 DateAttributeFilterTable f = null;
3218 f = findDateAttributeFilterTable(item.parent());
3220 f.select(item.parent().indexOfChild(item));
3222 Global.containsFilter.select(item.parent().indexOfChild(item));
3225 listManager.loadNotesIndex();
3226 noteIndexUpdated(false);
3229 attributeTreeSelected = null;
3230 item.setSelected(false);
3231 Global.createdBeforeFilter.reset();
3232 Global.createdSinceFilter.reset();
3233 Global.changedBeforeFilter.reset();
3234 Global.changedSinceFilter.reset();
3235 Global.containsFilter.reset();
3236 listManager.loadNotesIndex();
3237 noteIndexUpdated(false);
3239 // This determines what attribute filter we need, depending upon the selection
3240 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3241 if (w.parent() != null && w.childCount() > 0) {
3242 QTreeWidgetItem parent = w.parent();
3243 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3244 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3245 return Global.createdSinceFilter;
3246 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3247 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3248 return Global.createdBeforeFilter;
3249 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3250 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3251 return Global.changedSinceFilter;
3252 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3253 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3254 return Global.changedBeforeFilter;
3259 // Show/Hide attribute search window
3260 private void toggleAttributesWindow() {
3261 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3262 if (attributeTree.isVisible())
3263 attributeTree.hide();
3265 attributeTree.show();
3266 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3268 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3269 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3271 private void clearAttributeFilter() {
3272 Global.createdBeforeFilter.reset();
3273 Global.createdSinceFilter.reset();
3274 Global.changedBeforeFilter.reset();
3275 Global.changedSinceFilter.reset();
3276 Global.containsFilter.reset();
3277 attributeTreeSelected = null;
3278 attributeTree.blockSignals(true);
3279 attributeTree.clearSelection();
3280 attributeTree.blockSignals(false);
3284 //***************************************************************
3285 //***************************************************************
3286 //** These functions deal with the GUI Note index table
3287 //***************************************************************
3288 //***************************************************************
3289 // Initialize the note list table
3290 private void initializeNoteTable() {
3291 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3292 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3293 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3294 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3296 // Show/Hide trash window
3297 @SuppressWarnings("unused")
3298 private void toggleNoteListWindow() {
3299 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3300 if (noteTableView.isVisible())
3301 noteTableView.hide();
3303 noteTableView.show();
3304 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3306 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3307 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3309 // Handle the event that a user selects a note from the table
3310 @SuppressWarnings("unused")
3311 private void noteTableSelection() {
3312 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3314 if (historyGuids.size() == 0) {
3315 historyGuids.add(currentNoteGuid);
3316 historyPosition = 1;
3318 noteTableView.showColumn(Global.noteTableGuidPosition);
3320 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3321 if (!Global.isColumnVisible("guid"))
3322 noteTableView.hideColumn(Global.noteTableGuidPosition);
3324 if (selections.size() > 0) {
3326 menuBar.noteDuplicateAction.setEnabled(true);
3327 menuBar.noteOnlineHistoryAction.setEnabled(true);
3328 menuBar.noteMergeAction.setEnabled(true);
3329 selectedNoteGUIDs.clear();
3330 if (selections.size() != 1 || Global.showDeleted) {
3331 menuBar.noteDuplicateAction.setEnabled(false);
3333 if (selections.size() != 1 || !Global.isConnected) {
3334 menuBar.noteOnlineHistoryAction.setEnabled(false);
3336 if (selections.size() == 1) {
3337 menuBar.noteMergeAction.setEnabled(false);
3339 for (int i=0; i<selections.size(); i++) {
3340 int row = selections.get(i).row();
3342 upButton.setEnabled(false);
3344 upButton.setEnabled(true);
3345 if (row < listManager.getNoteTableModel().rowCount()-1)
3346 downButton.setEnabled(true);
3348 downButton.setEnabled(false);
3349 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3350 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3351 currentNoteGuid = (String)ix.values().toArray()[0];
3352 selectedNoteGUIDs.add(currentNoteGuid);
3356 nextButton.setEnabled(true);
3357 prevButton.setEnabled(true);
3359 int endPosition = historyGuids.size()-1;
3360 for (int j=historyPosition; j<=endPosition; j++) {
3361 historyGuids.remove(historyGuids.size()-1);
3363 historyGuids.add(currentNoteGuid);
3364 historyPosition = historyGuids.size();
3366 if (historyPosition <= 1)
3367 prevButton.setEnabled(false);
3368 if (historyPosition == historyGuids.size())
3369 nextButton.setEnabled(false);
3371 fromHistory = false;
3372 scrollToGuid(currentNoteGuid);
3373 refreshEvernoteNote(true);
3374 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3376 // Trigger a refresh when the note db has been updated
3377 private void noteIndexUpdated(boolean reload) {
3378 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3380 refreshEvernoteNoteList();
3381 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3382 noteTableView.load(reload);
3383 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3385 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3386 pos = noteTableView.proxyModel.rowCount();
3389 if (noteTableView.proxyModel.rowCount() == 0)
3392 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3394 currentNoteGuid = (String)i.data();
3395 noteTableView.selectRow(pos-1);
3400 scrollToGuid(currentNoteGuid);
3401 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3403 // Called when the list of notes is updated
3404 private void refreshEvernoteNoteList() {
3405 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3406 browserWindow.setDisabled(false);
3407 if (selectedNoteGUIDs == null)
3408 selectedNoteGUIDs = new ArrayList<String>();
3409 selectedNoteGUIDs.clear(); // clear out old entries
3411 String saveCurrentNoteGuid = new String();
3412 String tempNoteGuid = new String();
3414 historyGuids.clear();
3415 historyPosition = 0;
3416 prevButton.setEnabled(false);
3417 nextButton.setEnabled(false);
3419 if (currentNoteGuid == null)
3420 currentNoteGuid = new String();
3422 //determine current note guid
3423 for (Note note : listManager.getNoteIndex()) {
3424 tempNoteGuid = note.getGuid();
3425 if (currentNoteGuid.equals(tempNoteGuid)) {
3426 saveCurrentNoteGuid = tempNoteGuid;
3430 if (listManager.getNoteIndex().size() == 0) {
3431 currentNoteGuid = "";
3433 browserWindow.clear();
3434 browserWindow.setDisabled(true);
3437 if (!saveCurrentNoteGuid.equals("")) {
3438 refreshEvernoteNote(false);
3440 currentNoteGuid = "";
3442 reloadTagTree(false);
3444 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3446 // Called when the previous arrow button is clicked
3447 @SuppressWarnings("unused")
3448 private void previousViewedAction() {
3449 if (!prevButton.isEnabled())
3451 if (historyPosition == 0)
3454 if (historyPosition <= 0)
3456 String historyGuid = historyGuids.get(historyPosition-1);
3458 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3459 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3460 if (modelIndex != null) {
3461 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3462 String tableGuid = (String)ix.values().toArray()[0];
3463 if (tableGuid.equals(historyGuid)) {
3464 noteTableView.selectRow(i);
3470 @SuppressWarnings("unused")
3471 private void nextViewedAction() {
3472 if (!nextButton.isEnabled())
3474 String historyGuid = historyGuids.get(historyPosition);
3477 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3478 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3479 if (modelIndex != null) {
3480 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3481 String tableGuid = (String)ix.values().toArray()[0];
3482 if (tableGuid.equals(historyGuid)) {
3483 noteTableView.selectRow(i);
3489 // Called when the up arrow is clicked
3490 @SuppressWarnings("unused")
3491 private void upAction() {
3492 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3493 int row = selections.get(0).row();
3495 noteTableView.selectRow(row-1);
3498 // Called when the down arrow is clicked
3499 @SuppressWarnings("unused")
3500 private void downAction() {
3501 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3502 int row = selections.get(0).row();
3503 int max = listManager.getNoteTableModel().rowCount();
3505 noteTableView.selectRow(row+1);
3508 // Update a tag string for a specific note in the list
3509 @SuppressWarnings("unused")
3510 private void updateListTags(String guid, List<String> tags) {
3511 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3512 StringBuffer tagBuffer = new StringBuffer();
3513 for (int i=0; i<tags.size(); i++) {
3514 tagBuffer.append(tags.get(i));
3515 if (i<tags.size()-1)
3516 tagBuffer.append(", ");
3519 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3520 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3521 if (modelIndex != null) {
3522 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3523 String tableGuid = (String)ix.values().toArray()[0];
3524 if (tableGuid.equals(guid)) {
3525 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3526 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3527 noteTableView.proxyModel.invalidate();
3532 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3534 // Update a title for a specific note in the list
3535 @SuppressWarnings("unused")
3536 private void updateListAuthor(String guid, String author) {
3537 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3539 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3540 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3541 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3542 if (modelIndex != null) {
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.noteTableAuthorPosition,author);
3547 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3548 noteTableView.proxyModel.invalidate();
3554 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3556 private void updateListNoteNotebook(String guid, String notebook) {
3557 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3558 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3559 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3561 // Update a title for a specific note in the list
3562 @SuppressWarnings("unused")
3563 private void updateListSourceUrl(String guid, String url) {
3564 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3566 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3567 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3568 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3569 if (modelIndex != null) {
3570 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3571 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3572 String tableGuid = (String)ix.values().toArray()[0];
3573 if (tableGuid.equals(guid)) {
3574 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3575 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3576 noteTableView.proxyModel.invalidate();
3581 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3583 @SuppressWarnings("unused")
3584 private void updateListGuid(String oldGuid, String newGuid) {
3585 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3587 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3588 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3589 if (modelIndex != null) {
3590 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3591 String tableGuid = (String)ix.values().toArray()[0];
3592 if (tableGuid.equals(oldGuid)) {
3593 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3594 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3599 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3601 private void updateListTagName(String guid) {
3602 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3604 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3605 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3606 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3608 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3609 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3610 if (modelIndex != null) {
3611 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3612 String noteGuid = (String)ix.values().toArray()[0];
3613 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3614 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3615 i=listManager.getNoteTableModel().rowCount();
3621 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3623 private void removeListTagName(String guid) {
3624 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3626 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3627 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3628 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3629 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3630 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3633 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3634 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3635 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3636 if (modelIndex != null) {
3637 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3638 String noteGuid = (String)ix.values().toArray()[0];
3639 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3640 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3641 i=listManager.getNoteTableModel().rowCount();
3647 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3649 private void updateListNotebookName(String oldName, String newName) {
3650 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3652 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3653 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3654 if (modelIndex != null) {
3655 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3656 String tableName = (String)ix.values().toArray()[0];
3657 if (tableName.equalsIgnoreCase(oldName)) {
3658 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3662 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3664 @SuppressWarnings("unused")
3665 private void updateListDateCreated(String guid, QDateTime date) {
3666 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3668 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3669 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3670 if (modelIndex != null) {
3671 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3672 String tableGuid = (String)ix.values().toArray()[0];
3673 if (tableGuid.equals(guid)) {
3674 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3675 noteTableView.proxyModel.invalidate();
3680 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3682 @SuppressWarnings("unused")
3683 private void updateListDateSubject(String guid, QDateTime date) {
3684 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3686 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3687 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3688 if (modelIndex != null) {
3689 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3690 String tableGuid = (String)ix.values().toArray()[0];
3691 if (tableGuid.equals(guid)) {
3692 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3693 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3694 noteTableView.proxyModel.invalidate();
3699 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3701 private void updateListDateChanged(String guid, QDateTime date) {
3702 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3704 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3705 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3706 if (modelIndex != null) {
3707 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3708 String tableGuid = (String)ix.values().toArray()[0];
3709 if (tableGuid.equals(guid)) {
3710 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3711 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3716 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3718 private void updateListDateChanged() {
3719 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3720 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3721 updateListDateChanged(currentNoteGuid, date);
3722 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3725 private void scrollToCurrentGuid() {
3726 //scrollToGuid(currentNoteGuid);
3727 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3728 if (selections.size() == 0)
3730 QModelIndex index = selections.get(0);
3731 int row = selections.get(0).row();
3732 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3735 // Scroll to a particular index item
3736 private void scrollToGuid(String guid) {
3737 if (currentNote == null || guid == null)
3739 if (currentNote.isActive() && Global.showDeleted) {
3740 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3741 if (!listManager.getNoteIndex().get(i).isActive()) {
3742 currentNote = listManager.getNoteIndex().get(i);
3743 currentNoteGuid = currentNote.getGuid();
3744 i = listManager.getNoteIndex().size();
3749 if (!currentNote.isActive() && !Global.showDeleted) {
3750 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3751 if (listManager.getNoteIndex().get(i).isActive()) {
3752 currentNote = listManager.getNoteIndex().get(i);
3753 currentNoteGuid = currentNote.getGuid();
3754 i = listManager.getNoteIndex().size();
3760 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3761 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3762 if (currentNoteGuid.equals(index.data())) {
3763 // noteTableView.setCurrentIndex(index);
3764 noteTableView.selectRow(i);
3765 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3766 i=listManager.getNoteTableModel().rowCount();
3769 noteTableView.repaint();
3771 // Show/Hide columns
3772 private void showColumns() {
3773 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3774 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3775 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3776 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3777 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3778 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3779 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3780 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3781 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3782 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3783 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3785 // Title color has changed
3786 @SuppressWarnings("unused")
3787 private void titleColorChanged(Integer color) {
3788 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3790 QColor backgroundColor = new QColor();
3791 QColor foregroundColor = new QColor(QColor.black);
3792 backgroundColor.setRgb(color);
3794 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3795 foregroundColor.setRgb(QColor.white.rgb());
3797 if (selectedNoteGUIDs.size() == 0)
3798 selectedNoteGUIDs.add(currentNoteGuid);
3800 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3801 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3802 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3803 if (modelIndex != null) {
3804 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3805 String tableGuid = (String)ix.values().toArray()[0];
3806 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3807 for (int k=0; k<Global.noteTableColumnCount; k++) {
3808 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3809 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3810 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3812 i=listManager.getNoteTableModel().rowCount();
3817 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3819 // Wide list was chosen
3820 public void narrowListView() {
3821 saveNoteColumnPositions();
3822 saveNoteIndexWidth();
3824 int sortCol = noteTableView.proxyModel.sortColumn();
3825 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3826 Global.setSortColumn(sortCol);
3827 Global.setSortOrder(sortOrder);
3829 Global.setListView(Global.View_List_Narrow);
3831 menuBar.wideListView.blockSignals(true);
3832 menuBar.narrowListView.blockSignals(true);
3834 menuBar.wideListView.setChecked(false);
3835 menuBar.narrowListView.setChecked(true);
3837 menuBar.wideListView.blockSignals(false);
3838 menuBar.narrowListView.blockSignals(false);
3840 mainLeftRightSplitter.addWidget(noteTableView);
3841 mainLeftRightSplitter.addWidget(browserWindow);
3842 restoreWindowState(false);
3843 noteTableView.repositionColumns();
3844 noteTableView.resizeColumnWidths();
3845 noteTableView.resizeRowHeights();
3847 sortCol = Global.getSortColumn();
3848 sortOrder = Global.getSortOrder();
3849 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3852 noteTableView.load(false);
3853 scrollToCurrentGuid();
3855 public void wideListView() {
3856 int sortCol = noteTableView.proxyModel.sortColumn();
3857 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3858 Global.setSortColumn(sortCol);
3859 Global.setSortOrder(sortOrder);
3862 saveNoteColumnPositions();
3863 saveNoteIndexWidth();
3864 Global.setListView(Global.View_List_Wide);
3866 menuBar.wideListView.blockSignals(true);
3867 menuBar.narrowListView.blockSignals(true);
3869 menuBar.wideListView.setChecked(true);
3870 menuBar.narrowListView.setChecked(false);
3872 menuBar.wideListView.blockSignals(false);
3873 menuBar.narrowListView.blockSignals(false);
3874 browserIndexSplitter.setVisible(true);
3875 browserIndexSplitter.addWidget(noteTableView);
3876 browserIndexSplitter.addWidget(browserWindow);
3877 restoreWindowState(false);
3878 noteTableView.repositionColumns();
3879 noteTableView.resizeColumnWidths();
3880 noteTableView.resizeRowHeights();
3882 sortCol = Global.getSortColumn();
3883 sortOrder = Global.getSortOrder();
3884 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3887 noteTableView.load(false);
3888 scrollToCurrentGuid();
3892 //***************************************************************
3893 //***************************************************************
3894 //** External editor window functions
3895 //***************************************************************
3896 //***************************************************************
3897 private void listDoubleClick() {
3899 if (externalWindows.containsKey(currentNoteGuid)) {
3900 externalWindows.get(currentNoteGuid).raise();
3903 // We have a new external editor to create
3904 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3905 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3906 newBrowser.setWindowIcon(appIcon);
3907 externalWindows.put(currentNoteGuid, newBrowser);
3908 showEditorButtons(newBrowser.getBrowserWindow());
3909 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3910 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3911 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3912 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3913 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3914 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3916 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3917 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3918 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3922 @SuppressWarnings("unused")
3923 private void externalWindowTitleEdited(String guid, String text) {
3924 if (guid.equals(currentNoteGuid)) {
3925 browserWindow.setTitle(text);
3928 @SuppressWarnings({ "rawtypes", "unused" })
3929 private void externalWindowTagsEdited(String guid, List values) {
3930 StringBuffer line = new StringBuffer(100);
3931 for (int i=0; i<values.size(); i++) {
3933 line.append(Global.tagDelimeter+" ");
3934 line.append(values.get(i));
3936 if (guid.equals(currentNoteGuid)) {
3937 browserWindow.setTag(line.toString());
3940 @SuppressWarnings("unused")
3941 private void externalWindowClosing(String guid) {
3942 externalWindows.remove(guid);
3947 //***************************************************************
3948 //***************************************************************
3949 //** These functions deal with Note specific things
3950 //***************************************************************
3951 //***************************************************************
3952 @SuppressWarnings("unused")
3953 private void setNoteDirty() {
3954 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
3955 // Interrupt indexing & thumbnails to improve performance
3956 indexRunner.interrupt = true;
3957 thumbnailRunner.interrupt = true;
3959 // Find if the note is being edited externally. If it is, update it.
3960 if (externalWindows.containsKey(currentNoteGuid)) {
3961 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3962 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
3963 ExternalBrowse window = externalWindows.get(currentNoteGuid);
3964 window.getBrowserWindow().getBrowser().setContent(unicode);
3967 // If the note is dirty, then it is unsynchronized by default.
3971 // Set the note as dirty and check if its status is synchronized in the display table
3973 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
3974 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
3978 // If this wasn't already marked as unsynchronized, then we need to update the table
3979 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
3980 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
3981 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3982 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3983 if (modelIndex != null) {
3984 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3985 String tableGuid = (String)ix.values().toArray()[0];
3986 if (tableGuid.equals(currentNoteGuid)) {
3987 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3993 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
3995 @SuppressWarnings("unused")
3996 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
3997 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3998 QByteArray unicode = codec.fromUnicode(content);
3999 noteCache.remove(guid);
4000 noteCache.put(guid, unicode.toString());
4001 if (guid.equals(currentNoteGuid)) {
4003 browserWindow.getBrowser().setContent(unicode);
4006 thumbnailRunner.addWork("GENERATE "+ guid);
4007 saveNote(guid, browser);
4011 private void saveNote() {
4013 saveNote(currentNoteGuid, browserWindow);
4014 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4018 private void saveNote(String guid, BrowserWindow window) {
4019 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4020 logger.log(logger.EXTREME, "Note is dirty.");
4023 logger.log(logger.EXTREME, "Saving to cache");
4024 QTextCodec codec = QTextCodec.codecForLocale();
4025 // QTextDecoder decoder = codec.makeDecoder();
4026 codec = QTextCodec.codecForName("UTF-8");
4027 QByteArray unicode = codec.fromUnicode(window.getContent());
4028 noteCache.put(guid, unicode.toString());
4030 logger.log(logger.EXTREME, "updating list manager");
4031 listManager.updateNoteContent(guid, window.getContent());
4032 logger.log(logger.EXTREME, "Updating title");
4033 listManager.updateNoteTitle(guid, window.getTitle());
4034 updateListDateChanged();
4036 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4037 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4038 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4039 currentNote = listManager.getNoteIndex().get(i);
4040 i = listManager.getNoteIndex().size();
4045 // Get a note from Evernote (and put it in the browser)
4046 private void refreshEvernoteNote(boolean reload) {
4047 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4049 if (Global.disableViewing) {
4050 browserWindow.setEnabled(false);
4055 if (Global.showDeleted)
4057 Global.cryptCounter =0;
4058 if (currentNoteGuid.equals("")) {
4059 browserWindow.setReadOnly(true);
4067 browserWindow.loadingData(true);
4069 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4070 if (currentNote == null)
4073 loadNoteBrowserInformation(browserWindow);
4076 private void loadNoteBrowserInformation(BrowserWindow browser) {
4077 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4078 formatter.setNote(currentNote, Global.pdfPreview());
4079 formatter.setHighlight(listManager.getEnSearch());
4081 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4082 js = new QByteArray();
4083 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4084 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4085 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>");
4086 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4087 js.append("<style> img { max-width:100%; }</style>");
4088 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4089 js.append("</head>");
4090 formatter.setNote(currentNote, Global.pdfPreview());
4091 js.append(formatter.rebuildNoteHTML());
4092 js.append("</HTML>");
4093 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4094 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4095 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4096 browser.getBrowser().setContent(js);
4097 noteCache.put(currentNoteGuid, js.toString());
4099 if (formatter.resourceError)
4100 resourceErrorMessage();
4101 readOnly = formatter.readOnly;
4102 inkNote = formatter.inkNote;
4104 readOnlyCache.put(currentNoteGuid, true);
4106 inkNoteCache.put(currentNoteGuid, true);
4108 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4109 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4110 js = new QByteArray(cachedContent);
4111 browser.getBrowser().setContent(js);
4112 if (readOnlyCache.containsKey(currentNoteGuid))
4114 if (inkNoteCache.containsKey(currentNoteGuid))
4117 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4118 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4121 if (readOnly || inkNote)
4122 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4124 browser.getBrowser().page().setContentEditable(true);
4125 browser.setReadOnly(readOnly);
4126 deleteButton.setEnabled(!readOnly);
4127 tagButton.setEnabled(!readOnly);
4128 menuBar.noteDelete.setEnabled(!readOnly);
4129 menuBar.noteTags.setEnabled(!readOnly);
4130 browser.setNote(currentNote);
4132 if (conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4133 deleteButton.setEnabled(false);
4134 menuBar.notebookDeleteAction.setEnabled(false);
4136 deleteButton.setEnabled(true);
4137 menuBar.notebookDeleteAction.setEnabled(true);
4140 // Build a list of non-closed notebooks
4141 List<Notebook> nbooks = new ArrayList<Notebook>();
4142 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4143 boolean found=false;
4144 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4145 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4149 nbooks.add(listManager.getNotebookIndex().get(i));
4152 browser.setTitle(currentNote.getTitle());
4153 browser.setTag(getTagNamesForNote(currentNote));
4154 browser.setAuthor(currentNote.getAttributes().getAuthor());
4156 browser.setAltered(currentNote.getUpdated());
4157 browser.setCreation(currentNote.getCreated());
4158 if (currentNote.getAttributes().getSubjectDate() > 0)
4159 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4161 browser.setSubjectDate(currentNote.getCreated());
4162 browser.setUrl(currentNote.getAttributes().getSourceURL());
4164 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4165 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4166 browser.setAllTags(tagList);
4168 browser.setCurrentTags(currentNote.getTagNames());
4170 scrollToGuid(currentNoteGuid);
4172 browser.loadingData(false);
4173 if (thumbnailViewer.isActiveWindow())
4176 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4177 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4180 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4182 // Save a generated thumbnail
4183 private void toggleNoteInformation() {
4184 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4185 browserWindow.toggleInformation();
4186 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4187 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4188 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4190 // Listener triggered when a print button is pressed
4191 @SuppressWarnings("unused")
4192 private void printNote() {
4193 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4195 QPrintDialog dialog = new QPrintDialog();
4196 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4197 QPrinter printer = dialog.printer();
4198 browserWindow.getBrowser().print(printer);
4200 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4203 // Listener triggered when the email button is pressed
4204 @SuppressWarnings("unused")
4205 private void emailNote() {
4206 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4208 if (Desktop.isDesktopSupported()) {
4209 Desktop desktop = Desktop.getDesktop();
4211 String text2 = browserWindow.getContentsToEmail();
4212 QUrl url = new QUrl("mailto:");
4213 url.addQueryItem("subject", currentNote.getTitle());
4214 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4215 url.addQueryItem("body", text2);
4216 QDesktopServices.openUrl(url);
4220 if (desktop.isSupported(Desktop.Action.MAIL)) {
4221 URI uriMailTo = null;
4223 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4224 String text = browserWindow.getContentsToEmail();
4225 //text = "<b>" +text +"</b>";
4226 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4227 +"&BODY=" +text, null);
4228 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4229 +"&ATTACHMENT=d:/test.pdf", null);
4230 desktop.mail(uriMailTo);
4231 } catch (URISyntaxException e) {
4232 e.printStackTrace();
4233 } catch (IOException e) {
4234 e.printStackTrace();
4241 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4243 // Reindex all notes
4244 @SuppressWarnings("unused")
4245 private void fullReindex() {
4246 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4247 indexRunner.addWork("REINDEXALL");
4248 setMessage(tr("Database will be reindexed."));
4249 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4251 // Listener when a user wants to reindex a specific note
4252 @SuppressWarnings("unused")
4253 private void reindexNote() {
4254 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4255 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4256 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4258 if (selectedNotebookGUIDs.size() > 1)
4259 setMessage(tr("Notes will be reindexed."));
4261 setMessage(tr("Note will be reindexed."));
4262 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4265 @SuppressWarnings("unused")
4266 private void deleteNote() {
4267 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4268 if (currentNote == null)
4270 if (currentNoteGuid.equals(""))
4273 // If we are deleting non-trash notes
4274 if (currentNote.isActive()) {
4275 if (Global.verifyDelete()) {
4276 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4277 QMessageBox.StandardButton.Yes,
4278 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4282 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4283 selectedNoteGUIDs.add(currentNoteGuid);
4284 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4285 listManager.deleteNote(selectedNoteGUIDs.get(i));
4288 // If we are deleting from the trash.
4289 if (Global.verifyDelete()) {
4290 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4291 QMessageBox.StandardButton.Yes,
4292 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4296 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4297 selectedNoteGUIDs.add(currentNoteGuid);
4298 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4299 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4300 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4301 if (modelIndex != null) {
4302 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4303 String tableGuid = (String)ix.values().toArray()[0];
4304 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4305 listManager.getNoteTableModel().removeRow(j);
4310 listManager.expungeNote(selectedNoteGUIDs.get(i));
4313 currentNoteGuid = "";
4314 listManager.loadNotesIndex();
4315 noteIndexUpdated(false);
4316 refreshEvernoteNote(true);
4317 scrollToGuid(currentNoteGuid);
4318 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4321 @SuppressWarnings("unused")
4322 private void addNote() {
4323 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4324 // browserWindow.setEnabled(true);
4325 browserWindow.setReadOnly(false);
4327 Calendar currentTime = new GregorianCalendar();
4328 StringBuffer noteString = new StringBuffer(100);
4329 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4330 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4333 if (Global.overrideDefaultFont()) {
4334 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4335 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4336 noteString.append("<br clear=\"none\" />\n");
4337 noteString.append("</span>\n</font>\n");
4339 noteString.append("<br clear=\"none\" />\n");
4340 noteString.append("</en-note>");
4342 Long l = new Long(currentTime.getTimeInMillis());
4343 String randint = new String(Long.toString(l));
4345 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4347 // for the first non-archived notebook. Finally, if nothing else we
4348 // pick the first notebook in the list.
4349 String notebook = null;
4350 listManager.getNotebookIndex().get(0).getGuid();
4351 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4352 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4353 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4354 notebook = currentSelectedNotebook.text(2);
4356 boolean found = false;
4357 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4358 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4359 boolean match = false;
4360 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4361 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4363 j = listManager.getArchiveNotebookIndex().size();
4367 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4369 // Now we have a list of good notebooks, so we can look for the default
4371 for (int i=0; i<goodNotebooks.size(); i++) {
4372 if (goodNotebooks.get(i).isDefaultNotebook()) {
4373 notebook = goodNotebooks.get(i).getGuid();
4375 i = goodNotebooks.size();
4379 if (goodNotebooks.size() > 0 && !found)
4380 notebook = goodNotebooks.get(0).getGuid();
4383 notebook = listManager.getNotebookIndex().get(0).getGuid();
4386 Note newNote = new Note();
4387 newNote.setUpdateSequenceNum(0);
4388 newNote.setGuid(randint);
4389 newNote.setNotebookGuid(notebook);
4390 newNote.setTitle("");
4391 newNote.setContent(noteString.toString());
4392 newNote.setDeleted(0);
4393 newNote.setCreated(System.currentTimeMillis());
4394 newNote.setUpdated(System.currentTimeMillis());
4395 newNote.setActive(true);
4396 NoteAttributes na = new NoteAttributes();
4397 na.setLatitude(0.0);
4398 na.setLongitude(0.0);
4399 na.setAltitude(0.0);
4400 newNote.setAttributes(new NoteAttributes());
4401 newNote.setTagGuids(new ArrayList<String>());
4402 newNote.setTagNames(new ArrayList<String>());
4404 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4405 if (Global.newNoteWithSelectedTags()) {
4406 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4407 QTreeWidgetItem currentSelection;
4408 for (int i=0; i<selections.size(); i++) {
4409 currentSelection = selections.get(i);
4410 newNote.getTagGuids().add(currentSelection.text(2));
4411 newNote.getTagNames().add(currentSelection.text(0));
4415 conn.getNoteTable().addNote(newNote, true);
4416 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4417 listManager.addNote(newNote);
4418 // noteTableView.insertRow(newNote, true, -1);
4420 currentNote = newNote;
4421 currentNoteGuid = currentNote.getGuid();
4422 refreshEvernoteNote(true);
4423 listManager.countNotebookResults(listManager.getNoteIndex());
4424 browserWindow.titleLabel.setFocus();
4425 browserWindow.titleLabel.selectAll();
4426 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4428 // If the window is hidden, then we want to popup this in an external window &
4431 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4433 // Restore a note from the trash;
4434 @SuppressWarnings("unused")
4435 private void restoreNote() {
4437 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4438 selectedNoteGUIDs.add(currentNoteGuid);
4439 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4440 listManager.restoreNote(selectedNoteGUIDs.get(i));
4442 currentNoteGuid = "";
4443 listManager.loadNotesIndex();
4444 noteIndexUpdated(false);
4447 // Search a note for specific txt
4448 @SuppressWarnings("unused")
4449 private void findText() {
4451 find.setFocusOnTextField();
4453 @SuppressWarnings("unused")
4454 private void doFindText() {
4455 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4458 @SuppressWarnings("unused")
4459 private void updateNoteTitle(String guid, String title) {
4460 listManager.setNoteSynchronized(guid, false);
4462 // Signal received that note content has changed. Normally we just need the guid to remove
4463 // it from the cache.
4464 @SuppressWarnings("unused")
4465 private void invalidateNoteCache(String guid, String content) {
4466 String v = noteCache.remove(guid);
4467 // if (guid.equals(currentNoteGuid) && !noteDirty)
4468 refreshEvernoteNote(true);
4470 // Signal received that a note guid has changed
4471 @SuppressWarnings("unused")
4472 private void noteGuidChanged(String oldGuid, String newGuid) {
4473 if (noteCache.containsKey(oldGuid)) {
4474 if (!oldGuid.equals(currentNoteGuid)) {
4475 String cache = noteCache.get(oldGuid);
4476 noteCache.put(newGuid, cache);
4477 noteCache.remove(oldGuid);
4479 noteCache.remove(oldGuid);
4480 noteCache.put(newGuid, browserWindow.getContent());
4484 listManager.updateNoteGuid(oldGuid, newGuid, false);
4485 if (currentNoteGuid.equals(oldGuid)) {
4486 if (currentNote != null)
4487 currentNote.setGuid(newGuid);
4488 currentNoteGuid = newGuid;
4491 if (externalWindows.containsKey(oldGuid)) {
4492 ExternalBrowse b = externalWindows.get(oldGuid);
4493 externalWindows.remove(oldGuid);
4494 b.getBrowserWindow().getNote().setGuid(newGuid);
4495 externalWindows.put(newGuid, b);
4498 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4499 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4500 noteTableView.proxyModel.addGuid(newGuid);
4501 i=listManager.getNoteIndex().size();
4505 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4506 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4507 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4508 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4512 // Toggle the note editor button bar
4513 private void toggleEditorButtonBar() {
4514 if (browserWindow.buttonsVisible) {
4515 browserWindow.hideButtons();
4516 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4517 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4519 browserWindow.buttonsVisible = true;
4520 showEditorButtons(browserWindow);
4522 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4524 // Show editor buttons
4525 private void showEditorButtons(BrowserWindow browser) {
4526 browser.buttonLayout.setVisible(true);
4527 browser.undoAction.setVisible(false);
4529 browser.undoButton.setVisible(false);
4531 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4532 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4533 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4534 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4535 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4536 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4537 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4538 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4539 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4540 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4541 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4542 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4543 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4544 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4545 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4546 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4547 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4548 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4549 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4550 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4551 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4552 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4553 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4555 private void duplicateNote(String guid) {
4557 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
4558 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4559 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4560 oldNote.setResources(resList);
4561 duplicateNote(oldNote);
4563 private void duplicateNote(Note oldNote) {
4565 // Now that we have a good notebook guid, we need to move the conflicting note
4566 // to the local notebook
4567 Calendar currentTime = new GregorianCalendar();
4568 Long l = new Long(currentTime.getTimeInMillis());
4569 String newGuid = new String(Long.toString(l));
4571 Note newNote = oldNote.deepCopy();
4572 newNote.setUpdateSequenceNum(0);
4573 newNote.setGuid(newGuid);
4574 newNote.setDeleted(0);
4575 newNote.setActive(true);
4576 List<Resource> resList = oldNote.getResources();
4577 if (resList == null)
4578 resList = new ArrayList<Resource>();
4580 for (int i=0; i<resList.size(); i++) {
4582 while (l == prevGuid) {
4583 currentTime = new GregorianCalendar();
4584 l = new Long(currentTime.getTimeInMillis());
4587 String newResGuid = new String(Long.toString(l));
4588 resList.get(i).setNoteGuid(newGuid);
4589 resList.get(i).setGuid(newResGuid);
4590 resList.get(i).setUpdateSequenceNum(0);
4591 resList.get(i).setActive(true);
4592 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
4594 newNote.setResources(resList);
4595 listManager.addNote(newNote);
4596 conn.getNoteTable().addNote(newNote, true);
4597 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4598 noteTableView.insertRow(newNote, true, -1);
4599 listManager.countNotebookResults(listManager.getNoteIndex());
4603 @SuppressWarnings("unused")
4604 private void allNotes() {
4605 clearAttributeFilter();
4606 clearNotebookFilter();
4607 clearSavedSearchFilter();
4610 searchField.clear();
4611 if (Global.mimicEvernoteInterface) {
4612 notebookTree.selectGuid("");
4614 notebookTreeSelection();
4617 @SuppressWarnings("unused")
4618 private void mergeNotes() {
4619 logger.log(logger.HIGH, "Merging notes");
4622 String masterGuid = null;
4623 List<String> sources = new ArrayList<String>();
4625 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4626 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4627 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4628 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4630 masterGuid = (String)ix.values().toArray()[0];
4632 sources.add((String)ix.values().toArray()[0]);
4635 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4636 logger.log(logger.EXTREME, "Children count: "+sources.size());
4637 mergeNoteContents(masterGuid, sources);
4638 currentNoteGuid = masterGuid;
4639 noteIndexUpdated(false);
4640 refreshEvernoteNote(true);
4643 private void mergeNoteContents(String targetGuid, List<String> sources) {
4644 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4645 String newContent = target.getContent();
4646 newContent = newContent.replace("</en-note>", "<br></br>");
4648 for (int i=0; i<sources.size(); i++) {
4649 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4650 if (source.isSetTitle()) {
4651 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4653 String sourceContent = source.getContent();
4654 logger.log(logger.EXTREME, "Merging contents into note");
4655 logger.log(logger.EXTREME, sourceContent);
4656 logger.log(logger.EXTREME, "End of content");
4657 int startOfNote = sourceContent.indexOf("<en-note>");
4658 sourceContent = sourceContent.substring(startOfNote+9);
4659 int endOfNote = sourceContent.indexOf("</en-note>");
4660 sourceContent = sourceContent.substring(0,endOfNote);
4661 newContent = newContent + sourceContent;
4662 logger.log(logger.EXTREME, "New note content");
4663 logger.log(logger.EXTREME, newContent);
4664 logger.log(logger.EXTREME, "End of content");
4665 for (int j=0; j<source.getResourcesSize(); j++) {
4666 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4667 Resource r = source.getResources().get(j);
4668 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4670 Calendar currentTime = new GregorianCalendar();
4671 Long l = new Long(currentTime.getTimeInMillis());
4675 while (l == prevGuid) {
4676 currentTime = new GregorianCalendar();
4677 l = new Long(currentTime.getTimeInMillis());
4679 String newResGuid = new String(Long.toString(l));
4680 newRes.setNoteGuid(targetGuid);
4681 newRes.setGuid(newResGuid);
4682 newRes.setUpdateSequenceNum(0);
4683 newRes.setActive(true);
4684 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4687 logger.log(logger.EXTREME, "Updating note");
4688 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4689 for (int i=0; i<sources.size(); i++) {
4690 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4691 listManager.deleteNote(sources.get(i));
4693 logger.log(logger.EXTREME, "Exiting merge note");
4695 // A resource within a note has had a guid change
4696 @SuppressWarnings("unused")
4697 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4698 if (!oldGuid.equals(newGuid))
4699 Global.resourceMap.put(oldGuid, newGuid);
4701 // View a thumbnail of the note
4702 public void thumbnailView() {
4704 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4705 QFile thumbnail = new QFile(thumbnailName);
4706 if (!thumbnail.exists()) {
4708 QImage img = new QImage();
4709 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4710 thumbnailViewer.setThumbnail(img);
4712 thumbnailViewer.setThumbnail(thumbnailName);
4713 if (!thumbnailViewer.isVisible())
4714 thumbnailViewer.showFullScreen();
4716 // An error happened while saving a note. Inform the user
4717 @SuppressWarnings("unused")
4718 private void saveRunnerError(String guid, String msg) {
4720 String title = "*Unknown*";
4721 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4722 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4723 title = listManager.getMasterNoteIndex().get(i).getTitle();
4724 i=listManager.getMasterNoteIndex().size();
4727 msg = "An error has happened while saving the note \"" +title+
4728 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4729 "As a result, changes to the note may not be saved properly in the database."+
4730 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4731 "\nbe lost. Please review the note to recover any critical data before restarting.";
4733 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4736 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4737 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4738 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4739 // Find an idle preview object
4740 for (int i=0; i<thumbGenerators.size(); i++) {
4741 if (thumbGenerators.get(i).mutex.tryLock()) {
4742 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4743 thumbGenerators.get(i).loadContent(guid, html, zoom);
4747 if (thumbGenerators.size() >= 1) {
4748 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4752 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4753 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4754 thumbGenerators.add(preview);
4756 if (preview.mutex.tryLock()) {
4757 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4758 preview.loadContent(guid, html, zoom);
4760 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4765 //**********************************************************
4766 //**********************************************************
4767 //* Online user actions
4768 //**********************************************************
4769 //**********************************************************
4770 private void setupOnlineMenu() {
4771 if (!Global.isConnected) {
4772 menuBar.noteOnlineHistoryAction.setEnabled(false);
4773 menuBar.selectiveSyncAction.setEnabled(false);
4776 menuBar.noteOnlineHistoryAction.setEnabled(true);
4777 menuBar.selectiveSyncAction.setEnabled(true);
4780 @SuppressWarnings("unused")
4781 private void viewNoteHistory() {
4782 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4784 if (currentNote.getUpdateSequenceNum() == 0) {
4785 setMessage(tr("Note has never been synchronized."));
4786 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4790 setMessage(tr("Getting Note History"));
4792 Note currentOnlineNote = null;
4795 if (Global.isPremium())
4796 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4798 versions = new ArrayList<NoteVersionId>();
4799 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4800 } catch (EDAMUserException e) {
4801 setMessage("EDAMUserException: " +e.getMessage());
4803 } catch (EDAMSystemException e) {
4804 setMessage("EDAMSystemException: " +e.getMessage());
4806 } catch (EDAMNotFoundException e) {
4807 setMessage(tr("Note not found on server."));
4808 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4810 } catch (TException e) {
4811 setMessage("EDAMTransactionException: " +e.getMessage());
4815 // If we've gotten this far, we have a good note.
4816 if (historyWindow == null) {
4817 historyWindow = new OnlineNoteHistory(logger, conn);
4818 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4819 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4820 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4822 historyWindow.historyCombo.clear();
4824 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4825 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4827 historyWindow.setCurrent(isDirty);
4829 loadHistoryWindowContent(currentOnlineNote);
4830 historyWindow.load(versions);
4831 setMessage(tr("History retrieved"));
4833 historyWindow.exec();
4835 private Note reloadHistoryWindow(String selection) {
4837 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4838 String dateTimeFormat = new String(fmt);
4839 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4843 for (int i=0; i<versions.size(); i++) {
4844 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4845 if (versionDate.toString().equals(selection))
4849 if (index > -1 || selection.indexOf("Current") > -1) {
4850 Note historyNote = null;
4853 usn = versions.get(index).getUpdateSequenceNum();
4854 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4856 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4857 } catch (EDAMUserException e) {
4858 setMessage("EDAMUserException: " +e.getMessage());
4861 } catch (EDAMSystemException e) {
4862 setMessage("EDAMSystemException: " +e.getMessage());
4865 } catch (EDAMNotFoundException e) {
4866 setMessage("EDAMNotFoundException: " +e.getMessage());
4869 } catch (TException e) {
4870 setMessage("EDAMTransactionException: " +e.getMessage());
4876 if (historyNote != null)
4877 historyWindow.setContent(historyNote);
4883 private void loadHistoryWindowContent(Note note) {
4884 note.setUpdateSequenceNum(0);
4885 historyWindow.setContent(note);
4887 @SuppressWarnings("unused")
4888 private void restoreHistoryNoteAsNew() {
4889 setMessage(tr("Restoring as new note."));
4890 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4891 setMessage(tr("Note has been restored as a new note."));
4893 @SuppressWarnings("unused")
4894 private void restoreHistoryNote() {
4895 setMessage(tr("Restoring note."));
4896 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
4897 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
4900 for (int i=0; i<n.getResourcesSize(); i++) {
4901 n.getResources().get(i).setActive(true);
4902 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
4904 listManager.addNote(n);
4905 conn.getNoteTable().addNote(n, true);
4906 refreshEvernoteNote(true);
4907 setMessage(tr("Note has been restored."));
4909 @SuppressWarnings("unused")
4910 private void setupSelectiveSync() {
4912 // Get a list of valid notebooks
4913 List<Notebook> notebooks = null;
4914 List<Tag> tags = null;
4915 List<LinkedNotebook> linkedNotebooks = null;
4917 notebooks = syncRunner.noteStore.listNotebooks(syncRunner.authToken);
4918 tags = syncRunner.noteStore.listTags(syncRunner.authToken);
4919 linkedNotebooks = syncRunner.noteStore.listLinkedNotebooks(syncRunner.authToken);
4920 } catch (EDAMUserException e) {
4921 setMessage("EDAMUserException: " +e.getMessage());
4923 } catch (EDAMSystemException e) {
4924 setMessage("EDAMSystemException: " +e.getMessage());
4926 } catch (TException e) {
4927 setMessage("EDAMTransactionException: " +e.getMessage());
4929 } catch (EDAMNotFoundException e) {
4930 setMessage("EDAMNotFoundException: " +e.getMessage());
4934 // Split up notebooks into synchronized & non-synchronized
4935 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
4936 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4938 for (int i=notebooks.size()-1; i>=0; i--) {
4939 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
4940 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
4941 ignoredBooks.add(notebooks.get(i));
4942 j=dbIgnoredNotebooks.size();
4947 // split up tags into synchronized & non-synchronized
4948 List<Tag> ignoredTags = new ArrayList<Tag>();
4949 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
4951 for (int i=tags.size()-1; i>=0; i--) {
4952 for (int j=0; j<dbIgnoredTags.size(); j++) {
4953 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
4954 ignoredTags.add(tags.get(i));
4955 j=dbIgnoredTags.size();
4960 // split up linked notebooks into synchronized & non-synchronized
4961 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
4962 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
4963 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
4964 String notebookGuid = linkedNotebooks.get(i).getGuid();
4965 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
4966 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
4967 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
4968 j=dbIgnoredLinkedNotebooks.size();
4973 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
4975 if (!ignore.okClicked())
4980 // Clear out old notebooks & add the new ones
4981 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4982 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
4983 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
4986 List<String> newNotebooks = new ArrayList<String>();
4987 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
4988 String text = ignore.getIgnoredBookList().takeItem(i).text();
4989 for (int j=0; j<notebooks.size(); j++) {
4990 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
4991 Notebook n = notebooks.get(j);
4992 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
4994 newNotebooks.add(n.getGuid());
4999 // Clear out old tags & add new ones
5000 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5001 for (int i=0; i<oldIgnoreTags.size(); i++) {
5002 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5005 List<String> newTags = new ArrayList<String>();
5006 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5007 String text = ignore.getIgnoredTagList().takeItem(i).text();
5008 for (int j=0; j<tags.size(); j++) {
5009 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5010 Tag t = tags.get(j);
5011 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5012 newTags.add(t.getGuid());
5018 // Clear out old tags & add new ones
5019 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5020 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5021 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5024 List<String> newLinked = new ArrayList<String>();
5025 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5026 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5027 for (int j=0; j<linkedNotebooks.size(); j++) {
5028 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5029 LinkedNotebook t = linkedNotebooks.get(j);
5030 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5031 newLinked.add(t.getGuid());
5032 j=linkedNotebooks.size();
5037 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5043 //**********************************************************
5044 //**********************************************************
5045 //* XML Modifying methods
5046 //**********************************************************
5047 //**********************************************************
5048 // An error has happended fetching a resource. let the user know
5049 private void resourceErrorMessage() {
5052 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5053 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5054 "In a perfect world this wouldn't happen, but it has.\n" +
5055 "It is embarasing when a program like me, designed to save all your\n"+
5056 "precious data, has a problem finding data.\n\n" +
5057 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5058 "In the mean time, I'm not going to let you make changes to this note.\n" +
5059 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5060 "this note on the Evernote servers. Sorry."+
5061 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5063 browserWindow.setReadOnly(true);
5069 //**********************************************************
5070 //**********************************************************
5072 //**********************************************************
5073 //**********************************************************
5074 // We should now do a sync with Evernote
5075 private void syncTimer() {
5076 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5077 syncRunner.syncNeeded = true;
5078 syncRunner.disableUploads = Global.disableUploads;
5080 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5082 private void syncStart() {
5083 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5085 if (!syncRunning && Global.isConnected) {
5086 syncRunner.setConnected(true);
5087 syncRunner.setKeepRunning(Global.keepRunning);
5088 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5090 if (syncThreadsReady > 0) {
5091 indexRunner.interrupt = true;
5092 thumbnailRunner.interrupt = true;
5093 saveNoteIndexWidth();
5094 saveNoteColumnPositions();
5095 if (syncRunner.addWork("SYNC")) {
5097 syncRunner.syncNeeded = true;
5102 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5104 @SuppressWarnings("unused")
5105 private void syncThreadComplete(Boolean refreshNeeded) {
5106 setMessage(tr("Finalizing Synchronization"));
5108 syncRunning = false;
5109 syncRunner.syncNeeded = false;
5110 synchronizeAnimationTimer.stop();
5111 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5113 if (currentNote == null) {
5114 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5116 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5117 noteIndexUpdated(false);
5118 noteTableView.selectionModel().blockSignals(true);
5119 scrollToGuid(currentNoteGuid);
5120 noteTableView.selectionModel().blockSignals(false);
5121 refreshEvernoteNote(false);
5122 scrollToGuid(currentNoteGuid);
5124 if (!syncRunner.error)
5125 setMessage(tr("Synchronization Complete"));
5127 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5128 logger.log(logger.MEDIUM, "Sync complete.");
5130 public void saveUploadAmount(long t) {
5131 Global.saveUploadAmount(t);
5133 public void saveUserInformation(User user) {
5134 Global.saveUserInformation(user);
5136 public void saveEvernoteUpdateCount(int i) {
5137 Global.saveEvernoteUpdateCount(i);
5139 public void refreshLists() {
5140 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5142 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5143 tagIndexUpdated(true);
5144 notebookIndexUpdated();
5145 savedSearchIndexUpdated();
5146 listManager.loadNotesIndex();
5148 noteTableView.selectionModel().blockSignals(true);
5149 noteIndexUpdated(true);
5150 noteTableView.selectionModel().blockSignals(false);
5151 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5155 @SuppressWarnings("unused")
5156 private void authTimer() {
5157 Calendar cal = Calendar.getInstance();
5159 // If we are not connected let's get out of here
5160 if (!Global.isConnected)
5163 // If this is the first time through, then we need to set this
5164 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5165 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5167 // long now = new Date().getTime();
5168 // if (now > Global.authRefreshTime && Global.isConnected) {
5169 syncRunner.authRefreshNeeded = true;
5173 @SuppressWarnings("unused")
5174 private void authRefreshComplete(boolean goodSync) {
5175 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5176 Global.isConnected = syncRunner.isConnected;
5178 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5179 authTimer.start(1000*60*15);
5180 logger.log(logger.LOW, "Authentication token has been renewed");
5181 // setMessage("Authentication token has been renewed.");
5183 authTimer.start(1000*60*5);
5184 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5185 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5187 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5191 @SuppressWarnings("unused")
5192 private synchronized void indexTimer() {
5193 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5196 if (!indexDisabled && indexRunner.idle) {
5197 thumbnailRunner.interrupt = true;
5198 indexRunner.addWork("SCAN");
5200 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5203 @SuppressWarnings("unused")
5204 private void indexStarted() {
5205 setMessage(tr("Indexing notes"));
5207 @SuppressWarnings("unused")
5208 private void indexComplete() {
5209 setMessage(tr("Index complete"));
5211 @SuppressWarnings("unused")
5212 private synchronized void toggleNoteIndexing() {
5213 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5214 indexDisabled = !indexDisabled;
5216 setMessage(tr("Indexing is now enabled."));
5218 setMessage(tr("Indexing is now disabled."));
5219 menuBar.disableIndexing.setChecked(indexDisabled);
5220 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5223 @SuppressWarnings("unused")
5224 private void threadMonitorCheck() {
5229 alive = listManager.threadCheck(Global.tagCounterThreadId);
5232 if (tagDeadCount > MAX)
5233 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5234 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5238 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5240 notebookThreadDeadCount++;
5241 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5242 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5244 notebookThreadDeadCount=0;
5246 alive = listManager.threadCheck(Global.trashCounterThreadId);
5249 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5250 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5254 alive = listManager.threadCheck(Global.saveThreadId);
5256 saveThreadDeadCount++;
5257 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5258 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5260 saveThreadDeadCount=0;
5262 if (!syncThread.isAlive()) {
5263 syncThreadDeadCount++;
5264 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5265 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5267 syncThreadDeadCount=0;
5269 if (!indexThread.isAlive()) {
5270 indexThreadDeadCount++;
5271 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5272 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5274 indexThreadDeadCount=0;
5279 private void thumbnailTimer() {
5280 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5281 thumbnailRunner.addWork("SCAN");
5285 //**************************************************
5286 //* Backup & Restore
5287 //**************************************************
5288 @SuppressWarnings("unused")
5289 private void databaseBackup() {
5290 QFileDialog fd = new QFileDialog(this);
5291 fd.setFileMode(FileMode.AnyFile);
5292 fd.setConfirmOverwrite(true);
5293 fd.setWindowTitle(tr("Backup Database"));
5294 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5295 fd.setAcceptMode(AcceptMode.AcceptSave);
5296 if (saveLastPath == null || saveLastPath.equals(""))
5297 fd.setDirectory(System.getProperty("user.home"));
5299 fd.setDirectory(saveLastPath);
5300 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5306 saveLastPath = fd.selectedFiles().get(0);
5307 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5308 setMessage(tr("Backing up database"));
5310 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5312 ExportData noteWriter = new ExportData(conn, true);
5313 String fileName = fd.selectedFiles().get(0);
5315 if (!fileName.endsWith(".nnex"))
5316 fileName = fileName +".nnex";
5317 noteWriter.exportData(fileName);
5318 setMessage(tr("Database backup completed."));
5323 @SuppressWarnings("unused")
5324 private void databaseRestore() {
5325 if (QMessageBox.question(this, tr("Confirmation"),
5326 tr("This is used to restore a database from backups.\n" +
5327 "It is HIGHLY recommened that this only be used to populate\n" +
5328 "an empty database. Restoring into a database that\n already has data" +
5329 " can cause problems.\n\nAre you sure you want to continue?"),
5330 QMessageBox.StandardButton.Yes,
5331 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5336 QFileDialog fd = new QFileDialog(this);
5337 fd.setFileMode(FileMode.ExistingFile);
5338 fd.setConfirmOverwrite(true);
5339 fd.setWindowTitle(tr("Restore Database"));
5340 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5341 fd.setAcceptMode(AcceptMode.AcceptOpen);
5342 if (saveLastPath == null || saveLastPath.equals(""))
5343 fd.setDirectory(System.getProperty("user.home"));
5345 fd.setDirectory(saveLastPath);
5346 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5352 saveLastPath = fd.selectedFiles().get(0);
5353 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5355 setMessage(tr("Restoring database"));
5356 ImportData noteReader = new ImportData(conn, true);
5357 noteReader.importData(fd.selectedFiles().get(0));
5359 if (noteReader.lastError != 0) {
5360 setMessage(noteReader.getErrorMessage());
5361 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5366 listManager.loadNoteTitleColors();
5368 refreshEvernoteNote(true);
5369 setMessage(tr("Database has been restored."));
5372 @SuppressWarnings("unused")
5373 private void exportNotes() {
5374 QFileDialog fd = new QFileDialog(this);
5375 fd.setFileMode(FileMode.AnyFile);
5376 fd.setConfirmOverwrite(true);
5377 fd.setWindowTitle(tr("Backup Database"));
5378 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5379 fd.setAcceptMode(AcceptMode.AcceptSave);
5380 fd.setDirectory(System.getProperty("user.home"));
5381 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5387 setMessage(tr("Exporting Notes"));
5390 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5391 selectedNoteGUIDs.add(currentNoteGuid);
5393 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5394 String fileName = fd.selectedFiles().get(0);
5396 if (!fileName.endsWith(".nnex"))
5397 fileName = fileName +".nnex";
5398 noteWriter.exportData(fileName);
5399 setMessage(tr("Export completed."));
5405 @SuppressWarnings("unused")
5406 private void importNotes() {
5407 QFileDialog fd = new QFileDialog(this);
5408 fd.setFileMode(FileMode.ExistingFile);
5409 fd.setConfirmOverwrite(true);
5410 fd.setWindowTitle(tr("Import Notes"));
5411 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5412 fd.setAcceptMode(AcceptMode.AcceptOpen);
5413 if (saveLastPath == null || saveLastPath.equals(""))
5414 fd.setDirectory(System.getProperty("user.home"));
5416 fd.setDirectory(saveLastPath);
5417 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5423 setMessage("Importing Notes");
5426 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5427 selectedNoteGUIDs.add(currentNoteGuid);
5429 ImportData noteReader = new ImportData(conn, false);
5430 String fileName = fd.selectedFiles().get(0);
5431 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5433 if (!fileName.endsWith(".nnex"))
5434 fileName = fileName +".nnex";
5435 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5436 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5438 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5440 noteReader.importData(fileName);
5442 if (noteReader.lastError != 0) {
5443 setMessage(noteReader.getErrorMessage());
5444 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5449 listManager.loadNoteTitleColors();
5451 refreshEvernoteNote(false);
5452 setMessage(tr("Notes have been imported."));
5455 setMessage("Import completed.");
5462 //**************************************************
5463 //* Duplicate a note
5464 //**************************************************
5465 @SuppressWarnings("unused")
5466 private void duplicateNote() {
5468 duplicateNote(currentNoteGuid);
5473 //**************************************************
5475 //**************************************************
5476 public void setupFolderImports() {
5477 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5479 if (importKeepWatcher == null)
5480 importKeepWatcher = new QFileSystemWatcher();
5481 if (importDeleteWatcher == null) {
5482 importDeleteWatcher = new QFileSystemWatcher();
5483 for (int i=0; i<records.size(); i++) {
5484 if (!records.get(i).keep)
5485 folderImportDelete(records.get(i).folder);
5491 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5492 for (int i=0; i<records.size(); i++) {
5493 if (records.get(i).keep)
5494 importKeepWatcher.addPath(records.get(i).folder);
5496 importDeleteWatcher.addPath(records.get(i).folder);
5499 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5500 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5502 // Look at the files already there so we don't import them again if a new file is created
5503 if (importedFiles == null) {
5504 importedFiles = new ArrayList<String>();
5505 for (int j=0; j<records.size(); j++) {
5506 QDir dir = new QDir(records.get(j).folder);
5507 List<QFileInfo> list = dir.entryInfoList();
5508 for (int k=0; k<list.size(); k++) {
5509 if (list.get(k).isFile())
5510 importedFiles.add(list.get(k).absoluteFilePath());
5515 public void folderImport() {
5516 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5517 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5519 if (!dialog.okClicked())
5522 // We have some sort of update.
5523 if (importKeepWatcher.directories().size() > 0)
5524 importKeepWatcher.removePaths(importKeepWatcher.directories());
5525 if (importDeleteWatcher.directories().size() > 0)
5526 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5528 conn.getWatchFolderTable().expungeAll();
5529 // Start building from the table
5530 for (int i=0; i<dialog.table.rowCount(); i++) {
5531 QTableWidgetItem item = dialog.table.item(i, 0);
5532 String dir = item.text();
5533 item = dialog.table.item(i, 1);
5534 String notebook = item.text();
5535 item = dialog.table.item(i, 2);
5537 if (item.text().equalsIgnoreCase("Keep"))
5542 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5543 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5545 setupFolderImports();
5548 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5550 String whichOS = System.getProperty("os.name");
5551 if (whichOS.contains("Windows"))
5552 dirName = dirName.replace('/','\\');
5554 FileImporter importer = new FileImporter(logger, conn);
5556 QDir dir = new QDir(dirName);
5557 List<QFileInfo> list = dir.entryInfoList();
5558 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5560 for (int i=0; i<list.size(); i++){
5562 boolean redundant = false;
5563 // Check if we've already imported this one or if it existed before
5564 for (int j=0; j<importedFiles.size(); j++) {
5565 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5570 importer.setFileInfo(list.get(i));
5571 importer.setFileName(list.get(i).absoluteFilePath());
5574 if (list.get(i).isFile() && importer.isValidType()) {
5576 if (!importer.importFile()) {
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 importFilesKeep.add(list.get(i).absoluteFilePath());
5583 Note newNote = importer.getNote();
5584 newNote.setNotebookGuid(notebook);
5585 newNote.setTitle(dir.at(i));
5586 listManager.addNote(newNote);
5587 conn.getNoteTable().addNote(newNote, true);
5588 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5589 noteTableView.insertRow(newNote, true, -1);
5590 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5591 listManager.countNotebookResults(listManager.getNoteIndex());
5592 importedFiles.add(list.get(i).absoluteFilePath());
5600 public void folderImportDelete(String dirName) {
5602 String whichOS = System.getProperty("os.name");
5603 if (whichOS.contains("Windows"))
5604 dirName = dirName.replace('/','\\');
5606 FileImporter importer = new FileImporter(logger, conn);
5607 QDir dir = new QDir(dirName);
5608 List<QFileInfo> list = dir.entryInfoList();
5609 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5611 for (int i=0; i<list.size(); i++){
5612 importer.setFileInfo(list.get(i));
5613 importer.setFileName(list.get(i).absoluteFilePath());
5615 if (list.get(i).isFile() && importer.isValidType()) {
5617 if (!importer.importFile()) {
5618 // If we can't get to the file, it is probably locked. We'll try again later.
5619 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5620 importFilesKeep.add(list.get(i).absoluteFilePath());
5624 Note newNote = importer.getNote();
5625 newNote.setNotebookGuid(notebook);
5626 newNote.setTitle(dir.at(i));
5627 listManager.addNote(newNote);
5628 conn.getNoteTable().addNote(newNote, true);
5629 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5630 noteTableView.insertRow(newNote, true, -1);
5631 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5632 listManager.countNotebookResults(listManager.getNoteIndex());
5633 dir.remove(dir.at(i));
5639 //**************************************************
5641 //**************************************************
5642 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5643 logger.log(logger.HIGH, "Entering exernalFileEdited");
5645 // Strip URL prefix and base dir path
5646 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5647 String name = fileName.replace(dPath, "");
5648 int pos = name.lastIndexOf('.');
5651 guid = guid.substring(0,pos);
5653 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5655 guid = name.substring(0, pos);
5658 QFile file = new QFile(fileName);
5659 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5660 // If we can't get to the file, it is probably locked. We'll try again later.
5661 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5662 externalFiles.add(fileName);
5665 QByteArray binData = file.readAll();
5667 if (binData.size() == 0) {
5668 // If we can't get to the file, it is probably locked. We'll try again later.
5669 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5670 externalFiles.add(fileName);
5674 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5676 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5677 if (r == null || r.getData() == null || r.getData().getBody() == null)
5679 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5680 MessageDigest md = MessageDigest.getInstance("MD5");
5681 md.update(binData.toByteArray());
5682 byte[] hash = md.digest();
5683 String newHash = Global.byteArrayToHexString(hash);
5684 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5685 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5687 if (externalWindows.containsKey(r.getNoteGuid())) {
5688 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5689 r.getGuid(), oldHash, newHash);
5691 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5692 Data data = r.getData();
5693 data.setBody(binData.toByteArray());
5694 data.setBodyHash(hash);
5695 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5697 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5699 if (r.getNoteGuid().equals(currentNoteGuid)) {
5700 QWebSettings.setMaximumPagesInCache(0);
5701 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5702 refreshEvernoteNote(true);
5703 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5706 if (externalWindows.containsKey(r.getNoteGuid())) {
5707 QWebSettings.setMaximumPagesInCache(0);
5708 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5709 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5713 logger.log(logger.HIGH, "Exiting externalFielEdited");
5715 // This is a timer event that tries to save any external files that were edited. This
5716 // is only needed if we couldn't save a file earlier.
5717 public void externalFileEditedSaver() {
5718 for (int i=externalFiles.size()-1; i>=0; i--) {
5720 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5721 externalFileEdited(externalFiles.get(i));
5722 externalFiles.remove(i);
5723 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5725 for (int i=0; i<importFilesKeep.size(); i++) {
5727 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5728 folderImportKeep(importFilesKeep.get(i));
5729 importFilesKeep.remove(i);
5730 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5732 for (int i=0; i<importFilesDelete.size(); i++) {
5733 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5734 folderImportDelete(importFilesDelete.get(i));
5735 importFilesDelete.remove(i);
5742 // If an attachment on the current note was edited, we need to update the current notes's hash
5743 // Update a note content's hash. This happens if a resource is edited outside of NN
5744 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5745 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5747 for (;position>-1;) {
5748 endPos = browser.getContent().indexOf(">", position+1);
5749 String oldSegment = browser.getContent().substring(position,endPos);
5750 int hashPos = oldSegment.indexOf("hash=\"");
5751 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5752 String hash = oldSegment.substring(hashPos+6, hashEnd);
5753 if (hash.equalsIgnoreCase(oldHash)) {
5754 String newSegment = oldSegment.replace(oldHash, newHash);
5755 String content = browser.getContent().substring(0,position) +
5757 browser.getContent().substring(endPos);
5758 browser.getBrowser().setContent(new QByteArray(content));;
5761 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5766 //*************************************************
5767 //* Minimize to tray
5768 //*************************************************
5770 public void changeEvent(QEvent e) {
5771 if (e.type() == QEvent.Type.WindowStateChange) {
5772 if (isMinimized() && Global.showTrayIcon()) {
5774 QTimer.singleShot(10, this, "hide()");
5778 windowMaximized = true;
5780 windowMaximized = false;
5784 //*************************************************
5785 //* Check database userid & passwords
5786 //*************************************************
5787 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5788 Connection connection;
5791 Class.forName("org.h2.Driver");
5792 } catch (ClassNotFoundException e1) {
5793 e1.printStackTrace();
5798 String passwordString = null;
5799 if (cypherPassword==null || cypherPassword.trim().equals(""))
5800 passwordString = userPassword;
5802 passwordString = cypherPassword+" "+userPassword;
5803 connection = DriverManager.getConnection(url,userid,passwordString);
5804 } catch (SQLException e) {
5809 } catch (SQLException e) {
5810 e.printStackTrace();