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.QMainWindow;
111 import com.trolltech.qt.gui.QMenu;
112 import com.trolltech.qt.gui.QMessageBox;
113 import com.trolltech.qt.gui.QMessageBox.StandardButton;
114 import com.trolltech.qt.gui.QPainter;
115 import com.trolltech.qt.gui.QPalette.ColorRole;
116 import com.trolltech.qt.gui.QPixmap;
117 import com.trolltech.qt.gui.QPrintDialog;
118 import com.trolltech.qt.gui.QPrinter;
119 import com.trolltech.qt.gui.QSizePolicy;
120 import com.trolltech.qt.gui.QSizePolicy.Policy;
121 import com.trolltech.qt.gui.QSpinBox;
122 import com.trolltech.qt.gui.QSplashScreen;
123 import com.trolltech.qt.gui.QSplitter;
124 import com.trolltech.qt.gui.QStatusBar;
125 import com.trolltech.qt.gui.QSystemTrayIcon;
126 import com.trolltech.qt.gui.QTableWidgetItem;
127 import com.trolltech.qt.gui.QTextEdit;
128 import com.trolltech.qt.gui.QToolBar;
129 import com.trolltech.qt.gui.QTreeWidgetItem;
130 import com.trolltech.qt.network.QNetworkAccessManager;
131 import com.trolltech.qt.network.QNetworkReply;
132 import com.trolltech.qt.network.QNetworkRequest;
133 import com.trolltech.qt.webkit.QWebPage.WebAction;
134 import com.trolltech.qt.webkit.QWebSettings;
136 import cx.fbn.nevernote.config.InitializationException;
137 import cx.fbn.nevernote.config.StartupConfig;
138 import cx.fbn.nevernote.dialog.AccountDialog;
139 import cx.fbn.nevernote.dialog.ConfigDialog;
140 import cx.fbn.nevernote.dialog.DBEncryptDialog;
141 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
142 import cx.fbn.nevernote.dialog.DatabaseStatus;
143 import cx.fbn.nevernote.dialog.FindDialog;
144 import cx.fbn.nevernote.dialog.IgnoreSync;
145 import cx.fbn.nevernote.dialog.LogFileDialog;
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
302 boolean disableTagThreadCheck=false;
303 boolean disableNotebookThreadCheck=false;
304 boolean disableTrashThreadCheck=false;
305 boolean disableSaveThreadCheck=false;
306 boolean disableSyncThreadCheck=false;
307 boolean disableIndexThreadCheck=false;
309 HashMap<String, String> noteCache; // Cash of note content
310 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
311 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
312 List<String> historyGuids; // GUIDs of previously viewed items
313 int historyPosition; // Position within the viewed items
314 boolean fromHistory; // Is this from the history queue?
315 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
316 List<Thumbnailer> thumbGenerators; // generate preview image
317 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
318 boolean encryptOnShutdown; // should I encrypt when I close?
319 boolean decryptOnShutdown; // should I decrypt on shutdown;
320 String encryptCipher; // What cipher should I use?
321 Signal0 minimizeToTray;
322 boolean windowMaximized = false; // Keep track of the window state for restores
323 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
324 List<QPixmap> syncIcons; // Array of icons used in sync animation
325 private boolean closeAction = false; // Used to say when to close or when to minimize
326 private static Logger log = Logger.getLogger(NeverNote.class);
327 private String saveLastPath; // last path we used
328 private final QTimer messageTimer; // Timer to clear the status message.
331 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
334 //***************************************************************
335 //***************************************************************
336 //** Constructor & main entry point
337 //***************************************************************
338 //***************************************************************
339 // Application Constructor
340 @SuppressWarnings("static-access")
341 public NeverNote(DatabaseConnection dbConn) {
343 if (conn.getConnection() == null) {
344 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
345 "is accessing the database or NeverNote is already running.\n\n" +
346 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
348 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
352 // thread().setPriority(Thread.MAX_PRIORITY);
354 logger = new ApplicationLogger("nevernote.log");
355 logger.log(logger.HIGH, "Starting Application");
357 decryptOnShutdown = false;
358 encryptOnShutdown = false;
359 conn.checkDatabaseVersion();
363 // Start building the invalid XML tables
364 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
365 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
367 for (int i=0; i<elements.size(); i++) {
368 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
371 logger.log(logger.EXTREME, "Starting GUI build");
373 QTranslator nevernoteTranslator = new QTranslator();
374 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
375 QApplication.instance().installTranslator(nevernoteTranslator);
377 Global.originalPalette = QApplication.palette();
378 QApplication.setStyle(Global.getStyle());
379 if (Global.useStandardPalette())
380 QApplication.setPalette(QApplication.style().standardPalette());
381 setWindowTitle("NeverNote");
383 mainLeftRightSplitter = new QSplitter();
384 setCentralWidget(mainLeftRightSplitter);
385 leftSplitter1 = new QSplitter();
386 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
388 browserIndexSplitter = new QSplitter();
389 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
391 //* Setup threads & thread timers
392 int indexRunnerCount = Global.getIndexThreads();
393 indexRunnerCount = 1;
394 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
396 logger.log(logger.EXTREME, "Building list manager");
397 listManager = new ListManager(conn, logger);
399 logger.log(logger.EXTREME, "Building index runners & timers");
400 indexRunner = new IndexRunner("indexRunner.log",
401 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
402 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
403 indexThread = new QThread(indexRunner, "Index Thread");
404 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
407 synchronizeAnimationTimer = new QTimer();
408 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
410 indexTimer = new QTimer();
411 indexTime = 1000*Global.getIndexThreadSleepInterval();
412 indexTimer.start(indexTime); // Start indexing timer
413 indexTimer.timeout.connect(this, "indexTimer()");
414 indexDisabled = false;
415 indexRunning = false;
417 logger.log(logger.EXTREME, "Setting sync thread & timers");
419 syncRunner = new SyncRunner("syncRunner.log",
420 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
421 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
422 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
423 syncTimer = new QTimer();
424 syncTimer.timeout.connect(this, "syncTimer()");
425 syncRunner.status.message.connect(this, "setMessage(String)");
426 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
427 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
430 automaticSync = true;
431 syncTimer.start(syncTime*60*1000);
433 automaticSync = false;
436 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
437 syncThread = new QThread(syncRunner, "Synchronization Thread");
441 logger.log(logger.EXTREME, "Starting thumnail thread");
442 pdfReadyQueue = new ArrayList<String>();
443 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
444 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
445 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
446 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
447 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
448 thumbnailThread.start();
449 thumbGenerators = new ArrayList<Thumbnailer>();
450 thumbnailTimer = new QTimer();
451 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
453 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
454 thumbnailTimer.start();
456 logger.log(logger.EXTREME, "Starting authentication timer");
457 authTimer = new QTimer();
458 authTimer.timeout.connect(this, "authTimer()");
459 authTimer.start(1000*60*15);
460 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
462 logger.log(logger.EXTREME, "Setting save note timer");
463 saveTimer = new QTimer();
464 saveTimer.timeout.connect(this, "saveNote()");
465 if (Global.getAutoSaveInterval() > 0) {
466 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
469 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
471 logger.log(logger.EXTREME, "Starting external file monitor timer");
472 externalFileSaveTimer = new QTimer();
473 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
474 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
475 externalFiles = new ArrayList<String>();
476 importFilesDelete = new ArrayList<String>();
477 importFilesKeep = new ArrayList<String>();
478 externalFileSaveTimer.start();
480 notebookTree = new NotebookTreeWidget(conn);
481 attributeTree = new AttributeTreeWidget();
482 tagTree = new TagTreeWidget(conn);
483 savedSearchTree = new SavedSearchTreeWidget();
484 trashTree = new TrashTreeWidget();
485 noteTableView = new TableView(logger, listManager);
487 QGridLayout leftGrid = new QGridLayout();
488 leftSplitter1.setLayout(leftGrid);
489 leftGrid.addWidget(notebookTree, 1, 1);
490 leftGrid.addWidget(tagTree,2,1);
491 leftGrid.addWidget(attributeTree,3,1);
492 leftGrid.addWidget(savedSearchTree,4,1);
493 leftGrid.addWidget(trashTree, 5, 1);
495 // Setup the browser window
496 noteCache = new HashMap<String,String>();
497 readOnlyCache = new HashMap<String, Boolean>();
498 inkNoteCache = new HashMap<String, Boolean>();
499 browserWindow = new BrowserWindow(conn);
501 mainLeftRightSplitter.addWidget(leftSplitter1);
502 mainLeftRightSplitter.addWidget(browserIndexSplitter);
504 if (Global.getListView() == Global.View_List_Wide) {
505 browserIndexSplitter.addWidget(noteTableView);
506 browserIndexSplitter.addWidget(browserWindow);
508 mainLeftRightSplitter.addWidget(noteTableView);
509 mainLeftRightSplitter.addWidget(browserWindow);
512 searchField = new QComboBox();
513 searchField.setEditable(true);
514 searchField.activatedIndex.connect(this, "searchFieldChanged()");
515 searchField.setDuplicatesEnabled(false);
516 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
518 quotaBar = new QuotaProgressBar();
520 // Setup the thumbnail viewer
521 thumbnailViewer = new ThumbnailViewer();
522 thumbnailViewer.upArrow.connect(this, "upAction()");
523 thumbnailViewer.downArrow.connect(this, "downAction()");
524 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
525 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
527 //Setup external browser manager
528 externalWindows = new HashMap<String, ExternalBrowse>();
530 listManager.loadNotesIndex();
531 initializeNotebookTree();
533 initializeSavedSearchTree();
534 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
535 attributeTreeSelected = null;
536 initializeNoteTable();
538 selectedNoteGUIDs = new ArrayList<String>();
539 statusBar = new QStatusBar();
540 setStatusBar(statusBar);
541 menuBar = new MainMenuBar(this);
542 emitLog = new ArrayList<String>();
544 tagTree.setDeleteAction(menuBar.tagDeleteAction);
545 tagTree.setEditAction(menuBar.tagEditAction);
546 tagTree.setAddAction(menuBar.tagAddAction);
547 tagTree.setIconAction(menuBar.tagIconAction);
548 tagTree.setVisible(Global.isWindowVisible("tagTree"));
549 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
550 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
551 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
553 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
554 notebookTree.setEditAction(menuBar.notebookEditAction);
555 notebookTree.setAddAction(menuBar.notebookAddAction);
556 notebookTree.setIconAction(menuBar.notebookIconAction);
557 notebookTree.setStackAction(menuBar.notebookStackAction);
558 notebookTree.setPublishAction(menuBar.notebookPublishAction);
559 notebookTree.setShareAction(menuBar.notebookShareAction);
560 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
561 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
562 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
563 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
564 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
566 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
567 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
568 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
569 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
570 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
571 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
572 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
574 noteTableView.setAddAction(menuBar.noteAdd);
575 noteTableView.setDeleteAction(menuBar.noteDelete);
576 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
577 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
578 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
579 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
580 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
581 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
582 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
583 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
584 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
586 quotaBar.setMouseClickAction(menuBar.accountAction);
589 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
590 trashTree.setEmptyAction(menuBar.emptyTrashAction);
591 trashTree.setVisible(Global.isWindowVisible("trashTree"));
592 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
593 trashTree.updateCounts(listManager.getTrashCount());
594 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
595 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
597 noteTableView.setVisible(Global.isWindowVisible("noteList"));
598 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
600 if (!Global.isWindowVisible("editorButtonBar"))
601 toggleEditorButtonBar();
602 if (!Global.isWindowVisible("leftPanel"))
603 menuBar.hideLeftSide.setChecked(true);
604 if (Global.isWindowVisible("noteInformation"))
605 toggleNoteInformation();
609 find = new FindDialog();
610 find.getOkButton().clicked.connect(this, "doFindText()");
612 // Setup the tray icon menu bar
613 trayShowAction = new QAction("Show/Hide", this);
614 trayExitAction = new QAction("Exit", this);
615 trayAddNoteAction = new QAction("Add Note", this);
617 trayExitAction.triggered.connect(this, "closeNeverNote()");
618 trayAddNoteAction.triggered.connect(this, "addNote()");
619 trayShowAction.triggered.connect(this, "trayToggleVisible()");
621 trayMenu = new QMenu(this);
622 trayMenu.addAction(trayAddNoteAction);
623 trayMenu.addAction(trayShowAction);
624 trayMenu.addAction(trayExitAction);
627 trayIcon = new QSystemTrayIcon(this);
628 trayIcon.setToolTip("NeverNote");
629 trayIcon.setContextMenu(trayMenu);
630 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
633 currentNoteGuid = Global.getLastViewedNoteGuid();
634 historyGuids = new ArrayList<String>();
638 if (!currentNoteGuid.trim().equals("")) {
639 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
642 noteIndexUpdated(true);
644 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
645 if (menuBar.showEditorBar.isChecked())
646 showEditorButtons(browserWindow);
647 tagIndexUpdated(true);
648 savedSearchIndexUpdated();
649 notebookIndexUpdated();
651 setupSyncSignalListeners();
652 setupBrowserSignalListeners();
653 setupIndexListeners();
656 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
657 tagTree.showAllTags(true);
659 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
660 setWindowIcon(appIcon);
661 trayIcon.setIcon(appIcon);
662 if (Global.showTrayIcon())
667 scrollToGuid(currentNoteGuid);
668 if (Global.automaticLogin()) {
670 if (Global.isConnected)
673 setupFolderImports();
676 restoreWindowState(true);
678 if (Global.mimicEvernoteInterface) {
679 notebookTree.selectGuid("");
682 threadMonitorTimer = new QTimer();
683 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
684 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
686 historyGuids.add(currentNoteGuid);
689 menuBar.blockSignals(true);
690 menuBar.narrowListView.blockSignals(true);
691 menuBar.wideListView.blockSignals(true);
692 if (Global.getListView() == Global.View_List_Narrow) {
693 menuBar.narrowListView.setChecked(true);
696 menuBar.wideListView.setChecked(true);
698 menuBar.blockSignals(false);
699 menuBar.narrowListView.blockSignals(false);
700 menuBar.wideListView.blockSignals(false);
702 if (Global.getListView() == Global.View_List_Wide) {
703 browserIndexSplitter.addWidget(noteTableView);
704 browserIndexSplitter.addWidget(browserWindow);
706 mainLeftRightSplitter.addWidget(noteTableView);
707 mainLeftRightSplitter.addWidget(browserWindow);
710 messageTimer = new QTimer();
711 messageTimer.timeout.connect(this, "clearMessage()");
712 messageTimer.setInterval(1000*15);
715 int sortCol = Global.getSortColumn();
716 int sortOrder = Global.getSortOrder();
717 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
718 if (Global.checkVersionUpgrade())
723 public static void main(String[] args) {
724 log.setLevel(Level.FATAL);
725 QApplication.initialize(args);
726 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
727 QSplashScreen splash = new QSplashScreen(pixmap);
730 DatabaseConnection dbConn;
733 initializeGlobalSettings(args);
735 showSplash = Global.isWindowVisible("SplashScreen");
739 dbConn = setupDatabaseConnection();
741 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
742 Global.getFileManager().purgeResDirectory(true);
744 } catch (InitializationException e) {
747 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
751 NeverNote application = new NeverNote(dbConn);
753 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
754 if (Global.startMinimized())
755 application.showMinimized();
757 if (Global.wasWindowMaximized())
758 application.showMaximized();
764 splash.finish(application);
766 System.out.println("Goodbye.");
771 * Open the internal database, or create if not present
773 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
775 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
776 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
778 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
779 boolean dbExists = f.exists();
781 Global.setDatabaseUrl("");
783 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
784 boolean goodCheck = false;
786 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
788 if (!dialog.okPressed())
790 Global.cipherPassword = dialog.getPassword();
791 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
792 Global.getDatabaseUserPassword(), Global.cipherPassword);
795 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
796 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
797 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
801 // Encrypt the database upon shutdown
802 private void encryptOnShutdown() {
803 String dbPath= Global.getFileManager().getDbDirPath("");
804 String dbName = "NeverNote";
806 Statement st = conn.getConnection().createStatement();
807 st.execute("shutdown");
808 if (QMessageBox.question(this, tr("Are you sure"),
809 tr("Are you sure you wish to encrypt the database?"),
810 QMessageBox.StandardButton.Yes,
811 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
812 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
813 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
814 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
816 } catch (SQLException e) {
821 // Decrypt the database upon shutdown
822 private void decryptOnShutdown() {
823 String dbPath= Global.getFileManager().getDbDirPath("");
824 String dbName = "NeverNote";
826 Statement st = conn.getConnection().createStatement();
827 st.execute("shutdown");
828 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
829 encryptCipher = "AES";
831 encryptCipher = "XTEA";
832 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
833 "Are you sure you wish to decrypt the database?"),
834 QMessageBox.StandardButton.Yes,
835 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
837 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
838 Global.setDatabaseUrl("");
839 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
841 } catch (SQLException e) {
846 * Encrypt/Decrypt the local database
848 public void doDatabaseEncrypt() {
849 // The database is not currently encrypted
850 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
851 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
852 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
853 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
854 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
855 "Do you wish to proceed?"),
856 QMessageBox.StandardButton.Yes,
857 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
860 DBEncryptDialog dialog = new DBEncryptDialog();
862 if (dialog.okPressed()) {
863 Global.cipherPassword = dialog.getPassword();
864 encryptOnShutdown = true;
865 encryptCipher = dialog.getEncryptionMethod();
868 DBEncryptDialog dialog = new DBEncryptDialog();
869 dialog.setWindowTitle("Database Decryption");
870 dialog.hideEncryption();
872 if (dialog.okPressed()) {
873 if (!dialog.getPassword().equals(Global.cipherPassword)) {
874 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
877 decryptOnShutdown = true;
884 private static void initializeGlobalSettings(String[] args) throws InitializationException {
885 StartupConfig startupConfig = new StartupConfig();
887 for (String arg : args) {
888 String lower = arg.toLowerCase();
889 if (lower.startsWith("--name="))
890 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
891 if (lower.startsWith("--home="))
892 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
893 if (lower.startsWith("--disable-viewing"))
894 startupConfig.setDisableViewing(true);
896 Global.setup(startupConfig);
901 public void closeEvent(QCloseEvent event) {
902 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
907 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
910 if (currentNote!= null & browserWindow!=null) {
911 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
912 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
915 setMessage(tr("Beginning shutdown."));
917 // Close down external windows
918 Collection<ExternalBrowse> windows = externalWindows.values();
919 Iterator<ExternalBrowse> iterator = windows.iterator();
920 while (iterator.hasNext()) {
921 ExternalBrowse browser = iterator.next();
922 browser.windowClosing.disconnect();
927 externalFileEditedSaver();
928 if (Global.isConnected && Global.synchronizeOnClose()) {
929 setMessage(tr("Performing synchronization before closing."));
930 syncRunner.syncNeeded = true;
931 syncRunner.addWork("SYNC");
932 syncRunner.addWork("STOP");
934 syncRunner.addWork("STOP");
935 syncRunner.keepRunning = false;
937 setMessage("Closing Program.");
938 threadMonitorTimer.stop();
940 thumbnailRunner.addWork("STOP");
941 indexRunner.addWork("STOP");
946 if (tempFiles != null)
949 browserWindow.noteSignal.tagsChanged.disconnect();
950 browserWindow.noteSignal.titleChanged.disconnect();
951 browserWindow.noteSignal.noteChanged.disconnect();
952 browserWindow.noteSignal.notebookChanged.disconnect();
953 browserWindow.noteSignal.createdDateChanged.disconnect();
954 browserWindow.noteSignal.alteredDateChanged.disconnect();
955 syncRunner.searchSignal.listChanged.disconnect();
956 syncRunner.tagSignal.listChanged.disconnect();
957 syncRunner.notebookSignal.listChanged.disconnect();
958 syncRunner.noteIndexSignal.listChanged.disconnect();
961 Global.saveWindowVisible("toolBar", toolBar.isVisible());
962 saveNoteColumnPositions();
963 saveNoteIndexWidth();
965 int width = notebookTree.columnWidth(0);
966 Global.setColumnWidth("notebookTreeName", width);
967 width = tagTree.columnWidth(0);
968 Global.setColumnWidth("tagTreeName", width);
970 Global.saveWindowMaximized(isMaximized());
971 Global.saveCurrentNoteGuid(currentNoteGuid);
973 int sortCol = noteTableView.proxyModel.sortColumn();
974 int sortOrder = noteTableView.proxyModel.sortOrder().value();
975 Global.setSortColumn(sortCol);
976 Global.setSortOrder(sortOrder);
980 Global.keepRunning = false;
982 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
983 if (indexRunner.thread().isAlive())
984 indexRunner.thread().join(50);
985 if (!indexRunner.thread().isAlive())
986 logger.log(logger.MEDIUM, "Index thread has stopped");
988 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
989 indexRunner.thread().interrupt();
991 } catch (InterruptedException e1) {
992 e1.printStackTrace();
995 syncRunner.addWork("STOP");
996 if (!syncRunner.isIdle()) {
998 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
999 System.out.println(tr("Synchronizing. Please be patient."));
1000 while (!syncRunner.isIdle());
1001 logger.log(logger.MEDIUM, "Sync thread has stopped");
1002 //} catch (InterruptedException e1) {
1003 // e1.printStackTrace();
1007 if (encryptOnShutdown) {
1008 encryptOnShutdown();
1010 if (decryptOnShutdown) {
1011 decryptOnShutdown();
1014 Global.getFileManager().purgeResDirectory(false);
1015 } catch (InitializationException e) {
1016 System.out.println(tr("Empty res directory purge failed"));
1017 e.printStackTrace();
1019 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1022 @SuppressWarnings("unused")
1023 private void closeNeverNote() {
1027 public void setMessage(String s) {
1028 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1031 logger.log(logger.HIGH, "Message: " +s);
1032 statusBar.showMessage(s);
1036 messageTimer.stop();
1037 messageTimer.setSingleShot(true);
1038 messageTimer.start();
1041 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1044 private void clearMessage() {
1045 statusBar.clearMessage();
1049 private void waitCursor(boolean wait) {
1051 if (QApplication.overrideCursor() == null)
1052 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1055 while (QApplication.overrideCursor() != null)
1056 QApplication.restoreOverrideCursor();
1060 private void setupIndexListeners() {
1061 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1062 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1063 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1064 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1066 private void setupSyncSignalListeners() {
1067 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1068 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1069 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1070 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1071 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1073 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1074 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1075 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1077 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1078 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1079 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1080 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1081 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1083 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1086 private void setupBrowserSignalListeners() {
1087 setupBrowserWindowListeners(browserWindow, true);
1090 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1091 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1092 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1093 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1094 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1095 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1096 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1097 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1098 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1099 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1100 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1101 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1102 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1103 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1104 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1105 if (master) browser.focusLost.connect(this, "saveNote()");
1106 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1109 //***************************************************************
1110 //***************************************************************
1111 //* Settings and look & feel
1112 //***************************************************************
1113 //***************************************************************
1114 @SuppressWarnings("unused")
1115 private void settings() {
1116 logger.log(logger.HIGH, "Entering NeverNote.settings");
1117 saveNoteColumnPositions();
1118 saveNoteIndexWidth();
1120 ConfigDialog settings = new ConfigDialog(this);
1121 String dateFormat = Global.getDateFormat();
1122 String timeFormat = Global.getTimeFormat();
1124 indexTime = 1000*Global.getIndexThreadSleepInterval();
1125 indexTimer.start(indexTime); // reset indexing timer
1128 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1129 if (Global.showTrayIcon())
1134 if (menuBar.showEditorBar.isChecked())
1135 showEditorButtons(browserWindow);
1137 // Reset the save timer
1138 if (Global.getAutoSaveInterval() > 0)
1139 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1143 // This is a hack to force a reload of the index in case the date or time changed.
1144 // if (!dateFormat.equals(Global.getDateFormat()) ||
1145 // !timeFormat.equals(Global.getTimeFormat())) {
1147 readOnlyCache.clear();
1148 inkNoteCache.clear();
1149 noteIndexUpdated(true);
1152 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1154 // Restore things to the way they were
1155 private void restoreWindowState(boolean mainWindow) {
1156 // We need to name things or this doesn't work.
1157 setObjectName("NeverNote");
1158 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1159 browserIndexSplitter.setObjectName("browserIndexSplitter");
1160 leftSplitter1.setObjectName("leftSplitter1");
1162 // Restore the actual positions.
1164 restoreGeometry(Global.restoreGeometry(objectName()));
1165 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1166 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1167 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1170 // Save window positions for the next start
1171 private void saveWindowState() {
1172 Global.saveGeometry(objectName(), saveGeometry());
1173 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1174 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1175 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1177 // Load the style sheet
1178 private void loadStyleSheet() {
1179 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1180 fileName = Global.getFileManager().getQssDirPath("default.qss");
1181 QFile file = new QFile(fileName);
1183 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1184 if (!file.exists()) {
1185 fileName = Global.getFileManager().getQssDirPath("default.qss");
1186 file = new QFile(fileName);
1188 file.open(OpenModeFlag.ReadOnly);
1189 String styleSheet = file.readAll().toString();
1191 setStyleSheet(styleSheet);
1193 // Save column positions for the next time
1194 private void saveNoteColumnPositions() {
1195 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1196 Global.setColumnPosition("noteTableCreationPosition", position);
1197 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1198 Global.setColumnPosition("noteTableTagPosition", position);
1199 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1200 Global.setColumnPosition("noteTableNotebookPosition", position);
1201 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1202 Global.setColumnPosition("noteTableChangedPosition", position);
1203 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1204 Global.setColumnPosition("noteTableAuthorPosition", position);
1205 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1206 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1207 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1208 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1209 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1210 Global.setColumnPosition("noteTableTitlePosition", position);
1211 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1212 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1213 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1214 Global.setColumnPosition("noteTableGuidPosition", position);
1215 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1216 Global.setColumnPosition("noteTableThumbnailPosition", position);
1219 // Save column widths for the next time
1220 private void saveNoteIndexWidth() {
1222 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1223 Global.setColumnWidth("noteTableCreationPosition", width);
1224 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1225 Global.setColumnWidth("noteTableChangedPosition", width);
1226 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1227 Global.setColumnWidth("noteTableGuidPosition", width);
1228 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1229 Global.setColumnWidth("noteTableNotebookPosition", width);
1230 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1231 Global.setColumnWidth("noteTableTagPosition", width);
1232 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1233 Global.setColumnWidth("noteTableTitlePosition", width);
1234 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1235 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1236 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1237 Global.setColumnWidth("noteTableAuthorPosition", width);
1238 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1239 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1240 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1241 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1242 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1243 Global.setColumnWidth("noteTableThumbnailPosition", width);
1244 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1245 Global.setColumnWidth("noteTableGuidPosition", width);
1249 //***************************************************************
1250 //***************************************************************
1251 //** These functions deal with Notebook menu items
1252 //***************************************************************
1253 //***************************************************************
1254 // Setup the tree containing the user's notebooks.
1255 private void initializeNotebookTree() {
1256 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1257 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1258 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1259 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1260 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1262 // Listener when a notebook is selected
1263 private void notebookTreeSelection() {
1264 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1267 clearAttributeFilter();
1268 clearSavedSearchFilter();
1269 if (Global.mimicEvernoteInterface) {
1271 searchField.clear();
1273 menuBar.noteRestoreAction.setVisible(false);
1274 menuBar.notebookEditAction.setEnabled(true);
1275 menuBar.notebookDeleteAction.setEnabled(true);
1276 menuBar.notebookPublishAction.setEnabled(true);
1277 menuBar.notebookShareAction.setEnabled(true);
1278 menuBar.notebookIconAction.setEnabled(true);
1279 menuBar.notebookStackAction.setEnabled(true);
1280 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1281 selectedNotebookGUIDs.clear();
1283 String stackName = "";
1284 if (selections.size() > 0) {
1285 guid = (selections.get(0).text(2));
1286 stackName = selections.get(0).text(0);
1288 if (!Global.mimicEvernoteInterface) {
1289 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1290 if (selections.size()==0) {
1291 selectedNotebookGUIDs.clear();
1292 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1293 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1295 menuBar.notebookEditAction.setEnabled(false);
1296 menuBar.notebookDeleteAction.setEnabled(false);
1297 menuBar.notebookStackAction.setEnabled(false);
1298 menuBar.notebookIconAction.setEnabled(false);
1301 if (!guid.equals("") && !guid.equals("STACK")) {
1302 selectedNotebookGUIDs.add(guid);
1303 menuBar.notebookIconAction.setEnabled(true);
1305 menuBar.notebookIconAction.setEnabled(true);
1306 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1307 Notebook book = listManager.getNotebookIndex().get(j);
1308 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1309 selectedNotebookGUIDs.add(book.getGuid());
1312 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1313 listManager.loadNotesIndex();
1314 noteIndexUpdated(false);
1315 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1318 private void clearNotebookFilter() {
1319 notebookTree.blockSignals(true);
1320 notebookTree.clearSelection();
1321 menuBar.noteRestoreAction.setVisible(false);
1322 menuBar.notebookEditAction.setEnabled(false);
1323 menuBar.notebookDeleteAction.setEnabled(false);
1324 selectedNotebookGUIDs.clear();
1325 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1326 notebookTree.blockSignals(false);
1328 // Triggered when the notebook DB has been updated
1329 private void notebookIndexUpdated() {
1330 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1332 // Get the possible icons
1333 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1334 notebookTree.setIcons(icons);
1336 if (selectedNotebookGUIDs == null)
1337 selectedNotebookGUIDs = new ArrayList<String>();
1338 List<Notebook> books = conn.getNotebookTable().getAll();
1339 for (int i=books.size()-1; i>=0; i--) {
1340 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1341 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1343 j=listManager.getArchiveNotebookIndex().size();
1349 listManager.countNotebookResults(listManager.getNoteIndex());
1350 notebookTree.blockSignals(true);
1351 notebookTree.load(books, listManager.getLocalNotebooks());
1352 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1353 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1355 selectedNotebookGUIDs.remove(i);
1357 notebookTree.blockSignals(false);
1359 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1361 // Show/Hide note information
1362 private void toggleNotebookWindow() {
1363 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1364 if (notebookTree.isVisible())
1365 notebookTree.hide();
1367 notebookTree.show();
1368 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1369 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1370 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1372 // Add a new notebook
1373 @SuppressWarnings("unused")
1374 private void addNotebook() {
1375 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1376 NotebookEdit edit = new NotebookEdit();
1377 edit.setNotebooks(listManager.getNotebookIndex());
1380 if (!edit.okPressed())
1383 Calendar currentTime = new GregorianCalendar();
1384 Long l = new Long(currentTime.getTimeInMillis());
1385 String randint = new String(Long.toString(l));
1387 Notebook newBook = new Notebook();
1388 newBook.setUpdateSequenceNum(0);
1389 newBook.setGuid(randint);
1390 newBook.setName(edit.getNotebook());
1391 newBook.setServiceCreated(new Date().getTime());
1392 newBook.setServiceUpdated(new Date().getTime());
1393 newBook.setDefaultNotebook(false);
1394 newBook.setPublished(false);
1396 listManager.getNotebookIndex().add(newBook);
1398 listManager.getLocalNotebooks().add(newBook.getGuid());
1399 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1400 notebookIndexUpdated();
1401 listManager.countNotebookResults(listManager.getNoteIndex());
1402 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1403 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1405 // Edit an existing notebook
1406 @SuppressWarnings("unused")
1407 private void stackNotebook() {
1408 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1409 StackNotebook edit = new StackNotebook();
1411 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1412 QTreeWidgetItem currentSelection;
1413 for (int i=0; i<selections.size(); i++) {
1414 currentSelection = selections.get(0);
1415 String guid = currentSelection.text(2);
1416 if (guid.equalsIgnoreCase("")) {
1417 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1420 if (guid.equalsIgnoreCase("STACK")) {
1421 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1426 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1431 if (!edit.okPressed())
1434 String stack = edit.getStackName();
1436 for (int i=0; i<selections.size(); i++) {
1437 currentSelection = selections.get(i);
1438 String guid = currentSelection.text(2);
1439 listManager.updateNotebookStack(guid, stack);
1441 notebookIndexUpdated();
1442 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1444 // Edit an existing notebook
1445 @SuppressWarnings("unused")
1446 private void editNotebook() {
1447 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1448 NotebookEdit edit = new NotebookEdit();
1450 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1451 QTreeWidgetItem currentSelection;
1452 currentSelection = selections.get(0);
1453 edit.setNotebook(currentSelection.text(0));
1455 String guid = currentSelection.text(2);
1456 if (!guid.equalsIgnoreCase("STACK")) {
1457 edit.setTitle(tr("Edit Notebook"));
1458 edit.setNotebooks(listManager.getNotebookIndex());
1459 edit.setLocalCheckboxEnabled(false);
1460 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1461 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1462 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1463 i=listManager.getNotebookIndex().size();
1467 edit.setTitle(tr("Edit Stack"));
1468 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1469 edit.hideLocalCheckbox();
1470 edit.hideDefaultCheckbox();
1475 if (!edit.okPressed())
1479 if (guid.equalsIgnoreCase("STACK")) {
1480 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1481 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1482 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1483 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1484 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1486 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1487 currentSelection.setText(0, edit.getNotebook());
1491 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1492 currentSelection.setText(0, edit.getNotebook());
1494 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1495 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1496 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1497 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1498 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1499 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1500 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1501 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1503 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1504 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1505 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1506 linkedNotebook.setShareName(edit.getNotebook());
1507 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1509 i=listManager.getNotebookIndex().size();
1513 // Build a list of non-closed notebooks
1514 List<Notebook> nbooks = new ArrayList<Notebook>();
1515 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1516 boolean found=false;
1517 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1518 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1522 nbooks.add(listManager.getNotebookIndex().get(i));
1526 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1527 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1528 browserWindow.setNotebookList(filteredBooks);
1529 Iterator<String> set = externalWindows.keySet().iterator();
1530 while(set.hasNext())
1531 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1532 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1534 // Publish a notebook
1535 @SuppressWarnings("unused")
1536 private void publishNotebook() {
1537 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1538 QTreeWidgetItem currentSelection;
1539 currentSelection = selections.get(0);
1540 String guid = currentSelection.text(2);
1542 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1547 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1548 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1549 n = listManager.getNotebookIndex().get(i);
1551 i = listManager.getNotebookIndex().size();
1557 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1560 if (!publish.okClicked())
1563 Publishing p = publish.getPublishing();
1564 boolean isPublished = !publish.isStopPressed();
1565 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1566 n.setPublished(isPublished);
1568 listManager.getNotebookIndex().set(position, n);
1569 notebookIndexUpdated();
1571 // Publish a notebook
1572 @SuppressWarnings("unused")
1573 private void shareNotebook() {
1574 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1575 QTreeWidgetItem currentSelection;
1576 currentSelection = selections.get(0);
1577 String guid = currentSelection.text(2);
1579 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1583 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1584 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1585 n = listManager.getNotebookIndex().get(i);
1586 i = listManager.getNotebookIndex().size();
1590 String authToken = null;
1591 if (syncRunner.isConnected)
1592 authToken = syncRunner.authToken;
1593 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1598 // Delete an existing notebook
1599 @SuppressWarnings("unused")
1600 private void deleteNotebook() {
1601 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1602 boolean stacksFound = false;
1603 boolean notebooksFound = false;
1604 boolean assigned = false;
1605 // Check if any notes have this notebook
1606 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1607 for (int i=0; i<selections.size(); i++) {
1608 QTreeWidgetItem currentSelection;
1609 currentSelection = selections.get(i);
1610 String guid = currentSelection.text(2);
1611 if (!guid.equalsIgnoreCase("STACK")) {
1612 notebooksFound = true;
1613 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1614 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1615 if (noteGuid.equals(guid)) {
1617 j=listManager.getNoteIndex().size();
1618 i=selections.size();
1626 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1627 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1631 if (conn.getNotebookTable().getAll().size() == 1) {
1632 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1636 // If all notebooks are clear, verify the delete
1637 String msg1 = new String(tr("Delete selected notebooks?"));
1638 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1639 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1640 " not deleted unless selected?"));
1642 if (stacksFound && notebooksFound)
1644 if (!stacksFound && notebooksFound)
1646 if (stacksFound && !notebooksFound)
1648 if (QMessageBox.question(this, tr("Confirmation"), msg,
1649 QMessageBox.StandardButton.Yes,
1650 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1654 // If confirmed, delete the notebook
1655 for (int i=selections.size()-1; i>=0; i--) {
1656 QTreeWidgetItem currentSelection;
1657 currentSelection = selections.get(i);
1658 String guid = currentSelection.text(2);
1659 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1660 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1661 listManager.renameStack(currentSelection.text(0), "");
1663 conn.getNotebookTable().expungeNotebook(guid, true);
1664 listManager.deleteNotebook(guid);
1668 notebookIndexUpdated();
1669 // notebookTreeSelection();
1670 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1671 // listManager.countNotebookResults(listManager.getNoteIndex());
1672 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1674 // A note's notebook has been updated
1675 @SuppressWarnings("unused")
1676 private void updateNoteNotebook(String guid, String notebookGuid) {
1678 // Update the list manager
1679 listManager.updateNoteNotebook(guid, notebookGuid);
1680 listManager.countNotebookResults(listManager.getNoteIndex());
1681 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1683 // Find the name of the notebook
1684 String notebookName = null;
1685 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1686 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1687 notebookName = listManager.getNotebookIndex().get(i).getName();
1692 // If we found the name, update the browser window
1693 if (notebookName != null) {
1694 updateListNoteNotebook(guid, notebookName);
1695 if (guid.equals(currentNoteGuid)) {
1696 int pos = browserWindow.notebookBox.findText(notebookName);
1698 browserWindow.notebookBox.setCurrentIndex(pos);
1702 // If we're dealing with the current note, then we need to be sure and update the notebook there
1703 if (guid.equals(currentNoteGuid)) {
1704 if (currentNote != null) {
1705 currentNote.setNotebookGuid(notebookGuid);
1709 // Open/close notebooks
1710 @SuppressWarnings("unused")
1711 private void closeNotebooks() {
1712 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1714 if (!na.okClicked())
1718 listManager.getArchiveNotebookIndex().clear();
1720 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1721 String text = na.getClosedBookList().takeItem(i).text();
1722 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1723 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1724 Notebook n = listManager.getNotebookIndex().get(j);
1725 conn.getNotebookTable().setArchived(n.getGuid(),true);
1726 listManager.getArchiveNotebookIndex().add(n);
1727 j=listManager.getNotebookIndex().size();
1732 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1733 String text = na.getOpenBookList().takeItem(i).text();
1734 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1735 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1736 Notebook n = listManager.getNotebookIndex().get(j);
1737 conn.getNotebookTable().setArchived(n.getGuid(),false);
1738 j=listManager.getNotebookIndex().size();
1742 notebookTreeSelection();
1743 listManager.loadNotesIndex();
1744 notebookIndexUpdated();
1745 noteIndexUpdated(false);
1746 reloadTagTree(true);
1747 // noteIndexUpdated(false);
1749 // Build a list of non-closed notebooks
1750 List<Notebook> nbooks = new ArrayList<Notebook>();
1751 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1752 boolean found=false;
1753 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1754 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1758 nbooks.add(listManager.getNotebookIndex().get(i));
1761 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1762 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1763 browserWindow.setNotebookList(filteredBooks);
1765 // Update any external windows
1766 Iterator<String> set = externalWindows.keySet().iterator();
1767 while(set.hasNext())
1768 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1772 // Change the notebook's icon
1773 @SuppressWarnings("unused")
1774 private void setNotebookIcon() {
1775 boolean stackSelected = false;
1776 boolean allNotebookSelected = false;
1778 QTreeWidgetItem currentSelection;
1779 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1780 if (selections.size() == 0)
1783 currentSelection = selections.get(0);
1784 String guid = currentSelection.text(2);
1785 if (guid.equalsIgnoreCase(""))
1786 allNotebookSelected = true;
1787 if (guid.equalsIgnoreCase("STACK"))
1788 stackSelected = true;
1790 QIcon currentIcon = currentSelection.icon(0);
1794 if (!stackSelected && !allNotebookSelected) {
1795 icon = conn.getNotebookTable().getIcon(guid);
1797 dialog = new SetIcon(currentIcon, saveLastPath);
1798 dialog.setUseDefaultIcon(true);
1800 dialog = new SetIcon(icon, saveLastPath);
1801 dialog.setUseDefaultIcon(false);
1804 if (stackSelected) {
1805 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1807 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1810 dialog = new SetIcon(currentIcon, saveLastPath);
1811 dialog.setUseDefaultIcon(true);
1813 dialog = new SetIcon(icon, saveLastPath);
1814 dialog.setUseDefaultIcon(false);
1818 if (dialog.okPressed()) {
1819 saveLastPath = dialog.getPath();
1821 QIcon newIcon = dialog.getIcon();
1822 if (stackSelected) {
1823 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1824 if (newIcon == null) {
1825 newIcon = new QIcon(iconPath+"books2.png");
1827 currentSelection.setIcon(0,newIcon);
1830 if (allNotebookSelected) {
1831 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1832 if (newIcon == null) {
1833 newIcon = new QIcon(iconPath+"notebook-green.png");
1835 currentSelection.setIcon(0,newIcon);
1838 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1839 if (newIcon == null) {
1840 boolean isPublished = false;;
1841 boolean found = false;
1842 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1843 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1844 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1848 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1850 currentSelection.setIcon(0, newIcon);
1856 //***************************************************************
1857 //***************************************************************
1858 //** These functions deal with Tag menu items
1859 //***************************************************************
1860 //***************************************************************
1861 // Add a new notebook
1862 @SuppressWarnings("unused")
1863 private void addTag() {
1864 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1865 TagEdit edit = new TagEdit();
1866 edit.setTagList(listManager.getTagIndex());
1869 if (!edit.okPressed())
1872 Calendar currentTime = new GregorianCalendar();
1873 Long l = new Long(currentTime.getTimeInMillis());
1874 String randint = new String(Long.toString(l));
1876 Tag newTag = new Tag();
1877 newTag.setUpdateSequenceNum(0);
1878 newTag.setGuid(randint);
1879 newTag.setName(edit.getTag());
1880 conn.getTagTable().addTag(newTag, true);
1881 listManager.getTagIndex().add(newTag);
1882 reloadTagTree(true);
1884 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1886 @SuppressWarnings("unused")
1887 private void reloadTagTree() {
1888 reloadTagTree(false);
1890 private void reloadTagTree(boolean reload) {
1891 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1892 tagIndexUpdated(reload);
1893 boolean filter = false;
1894 listManager.countTagResults(listManager.getNoteIndex());
1895 if (notebookTree.selectedItems().size() > 0
1896 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1898 if (tagTree.selectedItems().size() > 0)
1900 tagTree.showAllTags(!filter);
1901 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1903 // Edit an existing tag
1904 @SuppressWarnings("unused")
1905 private void editTag() {
1906 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1907 TagEdit edit = new TagEdit();
1908 edit.setTitle("Edit Tag");
1909 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1910 QTreeWidgetItem currentSelection;
1911 currentSelection = selections.get(0);
1912 edit.setTag(currentSelection.text(0));
1913 edit.setTagList(listManager.getTagIndex());
1916 if (!edit.okPressed())
1919 String guid = currentSelection.text(2);
1920 currentSelection.setText(0,edit.getTag());
1922 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1923 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1924 listManager.getTagIndex().get(i).setName(edit.getTag());
1925 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1926 updateListTagName(guid);
1927 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1928 browserWindow.setTag(getTagNamesForNote(currentNote));
1929 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1933 browserWindow.setTag(getTagNamesForNote(currentNote));
1934 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1936 // Delete an existing tag
1937 @SuppressWarnings("unused")
1938 private void deleteTag() {
1939 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1941 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1942 QMessageBox.StandardButton.Yes,
1943 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1947 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1948 for (int i=selections.size()-1; i>=0; i--) {
1949 QTreeWidgetItem currentSelection;
1950 currentSelection = selections.get(i);
1951 removeTagItem(currentSelection.text(2));
1953 tagIndexUpdated(true);
1955 listManager.countTagResults(listManager.getNoteIndex());
1956 // tagTree.updateCounts(listManager.getTagCounter());
1957 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1959 // Remove a tag tree item. Go recursively down & remove the children too
1960 private void removeTagItem(String guid) {
1961 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1962 String parent = listManager.getTagIndex().get(j).getParentGuid();
1963 if (parent != null && parent.equals(guid)) {
1964 //Remove this tag's children
1965 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1968 //Now, remove this tag
1969 removeListTagName(guid);
1970 conn.getTagTable().expungeTag(guid, true);
1971 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1972 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1973 listManager.getTagIndex().remove(a);
1978 // Setup the tree containing the user's tags
1979 private void initializeTagTree() {
1980 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1981 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1982 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
1983 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1984 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1985 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1987 // Listener when a tag is selected
1988 private void tagTreeSelection() {
1989 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1992 clearAttributeFilter();
1993 clearSavedSearchFilter();
1995 menuBar.noteRestoreAction.setVisible(false);
1997 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1998 QTreeWidgetItem currentSelection;
1999 selectedTagGUIDs.clear();
2000 for (int i=0; i<selections.size(); i++) {
2001 currentSelection = selections.get(i);
2002 selectedTagGUIDs.add(currentSelection.text(2));
2004 if (selections.size() > 0) {
2005 menuBar.tagEditAction.setEnabled(true);
2006 menuBar.tagDeleteAction.setEnabled(true);
2007 menuBar.tagIconAction.setEnabled(true);
2010 menuBar.tagEditAction.setEnabled(false);
2011 menuBar.tagDeleteAction.setEnabled(false);
2012 menuBar.tagIconAction.setEnabled(true);
2014 listManager.setSelectedTags(selectedTagGUIDs);
2015 listManager.loadNotesIndex();
2016 noteIndexUpdated(false);
2017 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2019 // trigger the tag index to be refreshed
2020 @SuppressWarnings("unused")
2021 private void tagIndexUpdated() {
2022 tagIndexUpdated(true);
2024 private void tagIndexUpdated(boolean reload) {
2025 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2026 if (selectedTagGUIDs == null)
2027 selectedTagGUIDs = new ArrayList<String>();
2029 listManager.reloadTagIndex();
2031 tagTree.blockSignals(true);
2033 tagTree.setIcons(conn.getTagTable().getAllIcons());
2034 tagTree.load(listManager.getTagIndex());
2036 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2037 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2039 selectedTagGUIDs.remove(i);
2041 tagTree.blockSignals(false);
2043 browserWindow.setTag(getTagNamesForNote(currentNote));
2044 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2046 // Show/Hide note information
2047 private void toggleTagWindow() {
2048 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2049 if (tagTree.isVisible())
2053 menuBar.hideTags.setChecked(tagTree.isVisible());
2054 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2055 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2057 // A note's tags have been updated
2058 @SuppressWarnings("unused")
2059 private void updateNoteTags(String guid, List<String> tags) {
2060 // Save any new tags. We'll need them later.
2061 List<String> newTags = new ArrayList<String>();
2062 for (int i=0; i<tags.size(); i++) {
2063 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2064 newTags.add(tags.get(i));
2067 listManager.saveNoteTags(guid, tags);
2068 listManager.countTagResults(listManager.getNoteIndex());
2069 StringBuffer names = new StringBuffer("");
2070 for (int i=0; i<tags.size(); i++) {
2071 names = names.append(tags.get(i));
2072 if (i<tags.size()-1) {
2073 names.append(Global.tagDelimeter + " ");
2076 browserWindow.setTag(names.toString());
2079 // Now, we need to add any new tags to the tag tree
2080 for (int i=0; i<newTags.size(); i++)
2081 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2083 // Get a string containing all tag names for a note
2084 private String getTagNamesForNote(Note n) {
2085 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2086 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2088 StringBuffer buffer = new StringBuffer(100);
2089 Vector<String> v = new Vector<String>();
2090 List<String> guids = n.getTagGuids();
2095 for (int i=0; i<guids.size(); i++) {
2096 v.add(listManager.getTagNameByGuid(guids.get(i)));
2098 Comparator<String> comparator = Collections.reverseOrder();
2099 Collections.sort(v,comparator);
2100 Collections.reverse(v);
2102 for (int i = 0; i<v.size(); i++) {
2104 buffer.append(", ");
2105 buffer.append(v.get(i));
2108 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2109 return buffer.toString();
2111 // Tags were added via dropping notes from the note list
2112 @SuppressWarnings("unused")
2113 private void tagsAdded(String noteGuid, String tagGuid) {
2114 String tagName = null;
2115 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2116 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2117 tagName = listManager.getTagIndex().get(i).getName();
2118 i=listManager.getTagIndex().size();
2121 if (tagName == null)
2124 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2125 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2126 List<String> tagNames = new ArrayList<String>();
2127 tagNames.add(new String(tagName));
2128 Note n = listManager.getMasterNoteIndex().get(i);
2129 for (int j=0; j<n.getTagNames().size(); j++) {
2130 tagNames.add(new String(n.getTagNames().get(j)));
2132 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2133 if (n.getGuid().equals(currentNoteGuid)) {
2134 Collections.sort(tagNames);
2135 String display = "";
2136 for (int j=0; j<tagNames.size(); j++) {
2137 display = display+tagNames.get(j);
2138 if (j+2<tagNames.size())
2139 display = display+Global.tagDelimeter+" ";
2141 browserWindow.setTag(display);
2143 i=listManager.getMasterNoteIndex().size();
2148 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2150 private void clearTagFilter() {
2151 tagTree.blockSignals(true);
2152 tagTree.clearSelection();
2153 menuBar.noteRestoreAction.setVisible(false);
2154 menuBar.tagEditAction.setEnabled(false);
2155 menuBar.tagDeleteAction.setEnabled(false);
2156 menuBar.tagIconAction.setEnabled(false);
2157 selectedTagGUIDs.clear();
2158 listManager.setSelectedTags(selectedTagGUIDs);
2159 tagTree.blockSignals(false);
2161 // Change the icon for a tag
2162 @SuppressWarnings("unused")
2163 private void setTagIcon() {
2164 QTreeWidgetItem currentSelection;
2165 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2166 if (selections.size() == 0)
2169 currentSelection = selections.get(0);
2170 String guid = currentSelection.text(2);
2172 QIcon currentIcon = currentSelection.icon(0);
2173 QIcon icon = conn.getTagTable().getIcon(guid);
2176 dialog = new SetIcon(currentIcon, saveLastPath);
2177 dialog.setUseDefaultIcon(true);
2179 dialog = new SetIcon(icon, saveLastPath);
2180 dialog.setUseDefaultIcon(false);
2183 if (dialog.okPressed()) {
2184 saveLastPath = dialog.getPath();
2185 QIcon newIcon = dialog.getIcon();
2186 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2187 if (newIcon == null)
2188 newIcon = new QIcon(iconPath+"tag.png");
2189 currentSelection.setIcon(0, newIcon);
2195 //***************************************************************
2196 //***************************************************************
2197 //** These functions deal with Saved Search menu items
2198 //***************************************************************
2199 //***************************************************************
2200 // Add a new notebook
2201 @SuppressWarnings("unused")
2202 private void addSavedSearch() {
2203 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2204 SavedSearchEdit edit = new SavedSearchEdit();
2205 edit.setSearchList(listManager.getSavedSearchIndex());
2208 if (!edit.okPressed())
2211 Calendar currentTime = new GregorianCalendar();
2212 Long l = new Long(currentTime.getTimeInMillis());
2213 String randint = new String(Long.toString(l));
2215 SavedSearch search = new SavedSearch();
2216 search.setUpdateSequenceNum(0);
2217 search.setGuid(randint);
2218 search.setName(edit.getName());
2219 search.setQuery(edit.getQuery());
2220 search.setFormat(QueryFormat.USER);
2221 listManager.getSavedSearchIndex().add(search);
2222 conn.getSavedSearchTable().addSavedSearch(search, true);
2223 savedSearchIndexUpdated();
2224 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2226 // Edit an existing tag
2227 @SuppressWarnings("unused")
2228 private void editSavedSearch() {
2229 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2230 SavedSearchEdit edit = new SavedSearchEdit();
2231 edit.setTitle(tr("Edit Search"));
2232 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2233 QTreeWidgetItem currentSelection;
2234 currentSelection = selections.get(0);
2235 String guid = currentSelection.text(1);
2236 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2237 edit.setName(currentSelection.text(0));
2238 edit.setQuery(s.getQuery());
2239 edit.setSearchList(listManager.getSavedSearchIndex());
2242 if (!edit.okPressed())
2245 List<SavedSearch> list = listManager.getSavedSearchIndex();
2246 SavedSearch search = null;
2247 boolean found = false;
2248 for (int i=0; i<list.size(); i++) {
2249 search = list.get(i);
2250 if (search.getGuid().equals(guid)) {
2257 search.setName(edit.getName());
2258 search.setQuery(edit.getQuery());
2259 conn.getSavedSearchTable().updateSavedSearch(search, true);
2260 savedSearchIndexUpdated();
2261 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2263 // Delete an existing tag
2264 @SuppressWarnings("unused")
2265 private void deleteSavedSearch() {
2266 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2268 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2269 QMessageBox.StandardButton.Yes,
2270 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2274 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2275 for (int i=selections.size()-1; i>=0; i--) {
2276 QTreeWidgetItem currentSelection;
2277 currentSelection = selections.get(i);
2278 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2279 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2280 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2281 listManager.getSavedSearchIndex().remove(j);
2282 j=listManager.getSavedSearchIndex().size()+1;
2285 selections.remove(i);
2287 savedSearchIndexUpdated();
2288 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2290 // Setup the tree containing the user's tags
2291 private void initializeSavedSearchTree() {
2292 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2293 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2294 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2296 // Listener when a tag is selected
2297 @SuppressWarnings("unused")
2298 private void savedSearchTreeSelection() {
2299 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2301 clearNotebookFilter();
2304 clearAttributeFilter();
2306 String currentGuid = selectedSavedSearchGUID;
2307 menuBar.savedSearchEditAction.setEnabled(true);
2308 menuBar.savedSearchDeleteAction.setEnabled(true);
2309 menuBar.savedSearchIconAction.setEnabled(true);
2310 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2311 QTreeWidgetItem currentSelection;
2312 selectedSavedSearchGUID = "";
2313 for (int i=0; i<selections.size(); i++) {
2314 currentSelection = selections.get(i);
2315 if (currentSelection.text(1).equals(currentGuid)) {
2316 currentSelection.setSelected(false);
2318 selectedSavedSearchGUID = currentSelection.text(1);
2320 // i = selections.size() +1;
2323 // There is the potential for no notebooks to be selected if this
2324 // happens then we make it look like all notebooks were selecetd.
2325 // If that happens, just select the "all notebooks"
2326 if (selections.size()==0) {
2327 clearSavedSearchFilter();
2329 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2331 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2333 private void clearSavedSearchFilter() {
2334 menuBar.savedSearchEditAction.setEnabled(false);
2335 menuBar.savedSearchDeleteAction.setEnabled(false);
2336 menuBar.savedSearchIconAction.setEnabled(false);
2337 savedSearchTree.blockSignals(true);
2338 savedSearchTree.clearSelection();
2339 savedSearchTree.blockSignals(false);
2340 selectedSavedSearchGUID = "";
2341 searchField.setEditText("");
2342 searchPerformed = false;
2343 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2345 // trigger the tag index to be refreshed
2346 private void savedSearchIndexUpdated() {
2347 if (selectedSavedSearchGUID == null)
2348 selectedSavedSearchGUID = new String();
2349 savedSearchTree.blockSignals(true);
2350 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2351 savedSearchTree.load(listManager.getSavedSearchIndex());
2352 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2353 savedSearchTree.blockSignals(false);
2355 // trigger when the saved search selection changes
2356 @SuppressWarnings("unused")
2357 private void updateSavedSearchSelection() {
2358 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2360 menuBar.savedSearchEditAction.setEnabled(true);
2361 menuBar.savedSearchDeleteAction.setEnabled(true);
2362 menuBar.savedSearchIconAction.setEnabled(true);
2363 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2365 if (selections.size() > 0) {
2366 menuBar.savedSearchEditAction.setEnabled(true);
2367 menuBar.savedSearchDeleteAction.setEnabled(true);
2368 menuBar.savedSearchIconAction.setEnabled(true);
2369 selectedSavedSearchGUID = selections.get(0).text(1);
2370 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2371 searchField.setEditText(s.getQuery());
2373 menuBar.savedSearchEditAction.setEnabled(false);
2374 menuBar.savedSearchDeleteAction.setEnabled(false);
2375 menuBar.savedSearchIconAction.setEnabled(false);
2376 selectedSavedSearchGUID = "";
2377 searchField.setEditText("");
2379 searchFieldChanged();
2381 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2385 // Show/Hide note information
2386 private void toggleSavedSearchWindow() {
2387 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2388 if (savedSearchTree.isVisible())
2389 savedSearchTree.hide();
2391 savedSearchTree.show();
2392 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2394 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2395 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2397 // Change the icon for a saved search
2398 @SuppressWarnings("unused")
2399 private void setSavedSearchIcon() {
2400 QTreeWidgetItem currentSelection;
2401 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2402 if (selections.size() == 0)
2405 currentSelection = selections.get(0);
2406 String guid = currentSelection.text(1);
2408 QIcon currentIcon = currentSelection.icon(0);
2409 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2412 dialog = new SetIcon(currentIcon, saveLastPath);
2413 dialog.setUseDefaultIcon(true);
2415 dialog = new SetIcon(icon, saveLastPath);
2416 dialog.setUseDefaultIcon(false);
2419 if (dialog.okPressed()) {
2420 saveLastPath = dialog.getPath();
2421 QIcon newIcon = dialog.getIcon();
2422 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2423 if (newIcon == null)
2424 newIcon = new QIcon(iconPath+"search.png");
2425 currentSelection.setIcon(0, newIcon);
2433 //***************************************************************
2434 //***************************************************************
2435 //** These functions deal with Help menu & tool menu items
2436 //***************************************************************
2437 //***************************************************************
2438 // Show database status
2439 @SuppressWarnings("unused")
2440 private void databaseStatus() {
2442 indexRunner.interrupt = true;
2443 int dirty = conn.getNoteTable().getDirtyCount();
2444 int unindexed = conn.getNoteTable().getUnindexedCount();
2445 DatabaseStatus status = new DatabaseStatus();
2446 status.setUnsynchronized(dirty);
2447 status.setUnindexed(unindexed);
2448 status.setNoteCount(conn.getNoteTable().getNoteCount());
2449 status.setNotebookCount(listManager.getNotebookIndex().size());
2450 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2451 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2452 status.setTagCount(listManager.getTagIndex().size());
2453 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2454 status.setWordCount(conn.getWordsTable().getWordCount());
2458 // Compact the database
2459 @SuppressWarnings("unused")
2460 private void compactDatabase() {
2461 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2462 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2463 "but please be aware that depending upon the size of your database this can be time consuming " +
2464 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2465 QMessageBox.StandardButton.Yes,
2466 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2469 setMessage("Compacting database.");
2471 listManager.compactDatabase();
2473 setMessage("Database compact is complete.");
2474 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2476 @SuppressWarnings("unused")
2477 private void accountInformation() {
2478 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2479 AccountDialog dialog = new AccountDialog();
2481 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2483 @SuppressWarnings("unused")
2484 private void releaseNotes() {
2485 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2486 QDialog dialog = new QDialog(this);
2487 QHBoxLayout layout = new QHBoxLayout();
2488 QTextEdit textBox = new QTextEdit();
2489 layout.addWidget(textBox);
2490 textBox.setReadOnly(true);
2491 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2492 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2493 QIODevice.OpenModeFlag.Text)))
2495 textBox.setText(file.readAll().toString());
2497 dialog.setWindowTitle(tr("Release Notes"));
2498 dialog.setLayout(layout);
2500 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2502 // Called when user picks Log from the help menu
2503 @SuppressWarnings("unused")
2504 private void logger() {
2505 logger.log(logger.HIGH, "Entering NeverNote.logger");
2506 LogFileDialog dialog = new LogFileDialog(emitLog);
2508 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2510 // Menu option "help/about" was selected
2511 @SuppressWarnings("unused")
2512 private void about() {
2513 logger.log(logger.HIGH, "Entering NeverNote.about");
2514 QMessageBox.about(this,
2515 tr("About NeverNote"),
2516 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2518 +tr("<hr></center>Evernote"
2519 +"An Open Source Evernote Client.<br><br>"
2520 +"Licensed under GPL v2. <br><hr><br>"
2521 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2522 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2523 +"PDFRenderer is licened under the LGPL<br>"
2524 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2525 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2526 +"Jazzy is licened under the LGPL<br>"
2527 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2528 logger.log(logger.HIGH, "Leaving NeverNote.about");
2530 // Hide the entire left hand side
2531 @SuppressWarnings("unused")
2532 private void toggleLeftSide() {
2535 hidden = !menuBar.hideLeftSide.isChecked();
2536 menuBar.hideLeftSide.setChecked(!hidden);
2538 if (notebookTree.isVisible() != hidden)
2539 toggleNotebookWindow();
2540 if (savedSearchTree.isVisible() != hidden)
2541 toggleSavedSearchWindow();
2542 if (tagTree.isVisible() != hidden)
2544 if (attributeTree.isVisible() != hidden)
2545 toggleAttributesWindow();
2546 if (trashTree.isVisible() != hidden)
2547 toggleTrashWindow();
2549 Global.saveWindowVisible("leftPanel", hidden);
2552 public void checkForUpdates() {
2553 // Send off thread to check for a new version
2554 versionChecker = new QNetworkAccessManager(this);
2555 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2556 QNetworkRequest request = new QNetworkRequest();
2557 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2558 versionChecker.get(request);
2560 @SuppressWarnings("unused")
2561 private void upgradeFileRead(QNetworkReply reply) {
2562 if (!reply.isReadable())
2565 String winVersion = Global.version;
2566 String osxVersion = Global.version;
2567 String linuxVersion = Global.version;
2568 String linux64Version = Global.version;
2569 String version = Global.version;
2571 // Determine the versions available
2572 QByteArray data = reply.readLine();
2573 while (data != null && !reply.atEnd()) {
2574 String line = data.toString();
2576 if (line.contains(":"))
2577 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2580 if (line.toLowerCase().contains("windows"))
2581 winVersion = lineVersion;
2582 else if (line.toLowerCase().contains("os-x"))
2583 osxVersion = lineVersion;
2584 else if (line.toLowerCase().contains("linux amd64"))
2585 linux64Version = lineVersion;
2586 else if (line.toLowerCase().contains("linux i386"))
2587 linuxVersion = lineVersion;
2588 else if (line.toLowerCase().contains("default"))
2589 version = lineVersion;
2591 // Read the next line
2592 data = reply.readLine();
2595 // Now we need to determine what system we are on.
2596 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2597 version = winVersion;
2598 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2599 version = osxVersion;
2600 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2601 if (System.getProperty("os.arch").contains("amd64") ||
2602 System.getProperty("os.arch").contains("x86_64"))
2603 version = linux64Version;
2605 version = linuxVersion;
2609 for (String validVersion : Global.validVersions) {
2610 if (version.equals(validVersion))
2614 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2616 if (dialog.remindMe())
2617 Global.setCheckVersionUpgrade(true);
2619 Global.setCheckVersionUpgrade(false);
2623 //***************************************************************
2624 //***************************************************************
2625 //** These functions deal with the Toolbar
2626 //***************************************************************
2627 //***************************************************************
2628 // Text in the search bar has been cleared
2629 private void searchFieldCleared() {
2632 // This is done because we want to force a reload of
2633 // images. Some images we may want to highlight the text.
2634 readOnlyCache.clear();
2635 inkNoteCache.clear();
2637 QWebSettings.setMaximumPagesInCache(0);
2638 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2640 searchField.setEditText("");
2641 saveNoteColumnPositions();
2642 saveNoteIndexWidth();
2643 noteIndexUpdated(true);
2644 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2645 currentNote = listManager.getNoteIndex().get(0);
2646 currentNoteGuid = currentNote.getGuid();
2648 if (currentNote != null)
2649 loadNoteBrowserInformation(browserWindow);
2651 // text in the search bar changed. We only use this to tell if it was cleared,
2652 // otherwise we trigger off searchFieldChanged.
2653 @SuppressWarnings("unused")
2654 private void searchFieldTextChanged(String text) {
2655 QWebSettings.setMaximumPagesInCache(0);
2656 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2658 if (text.trim().equals("")) {
2659 searchFieldCleared();
2660 if (searchPerformed) {
2662 // This is done because we want to force a reload of
2663 // images. Some images we may want to highlight the text.
2665 readOnlyCache.clear();
2666 inkNoteCache.clear();
2668 listManager.setEnSearch("");
2669 listManager.loadNotesIndex();
2670 refreshEvernoteNote(true);
2671 noteIndexUpdated(false);
2673 searchPerformed = false;
2676 // Text in the toolbar has changed
2677 private void searchFieldChanged() {
2678 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2680 readOnlyCache.clear();
2681 inkNoteCache.clear();
2682 saveNoteColumnPositions();
2683 saveNoteIndexWidth();
2684 String text = searchField.currentText();
2685 listManager.setEnSearch(text.trim());
2686 listManager.loadNotesIndex();
2687 //--->>> noteIndexUpdated(true);
2688 noteIndexUpdated(false);
2689 refreshEvernoteNote(true);
2690 searchPerformed = true;
2691 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2694 // Build the window tool bar
2695 private void setupToolBar() {
2696 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2697 toolBar = addToolBar(tr("Tool Bar"));
2698 menuBar.setupToolBarVisible();
2699 if (!Global.isWindowVisible("toolBar"))
2700 toolBar.setVisible(false);
2702 toolBar.setVisible(true);
2704 prevButton = toolBar.addAction("Previous");
2705 QIcon prevIcon = new QIcon(iconPath+"back.png");
2706 prevButton.setIcon(prevIcon);
2707 prevButton.triggered.connect(this, "previousViewedAction()");
2708 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2710 nextButton = toolBar.addAction("Next");
2711 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2712 nextButton.setIcon(nextIcon);
2713 nextButton.triggered.connect(this, "nextViewedAction()");
2714 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2716 upButton = toolBar.addAction("Up");
2717 QIcon upIcon = new QIcon(iconPath+"up.png");
2718 upButton.setIcon(upIcon);
2719 upButton.triggered.connect(this, "upAction()");
2720 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2723 downButton = toolBar.addAction("Down");
2724 QIcon downIcon = new QIcon(iconPath+"down.png");
2725 downButton.setIcon(downIcon);
2726 downButton.triggered.connect(this, "downAction()");
2727 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2729 synchronizeButton = toolBar.addAction("Synchronize");
2730 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2731 synchronizeIconAngle = 0;
2732 synchronizeButton.triggered.connect(this, "evernoteSync()");
2733 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2735 printButton = toolBar.addAction("Print");
2736 QIcon printIcon = new QIcon(iconPath+"print.png");
2737 printButton.setIcon(printIcon);
2738 printButton.triggered.connect(this, "printNote()");
2739 togglePrintButton(Global.isToolbarButtonVisible("print"));
2741 tagButton = toolBar.addAction("Tag");
2742 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2743 tagButton.setIcon(tagIcon);
2744 tagButton.triggered.connect(browserWindow, "modifyTags()");
2745 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2747 attributeButton = toolBar.addAction("Attributes");
2748 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2749 attributeButton.setIcon(attributeIcon);
2750 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2751 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2753 emailButton = toolBar.addAction("Email");
2754 QIcon emailIcon = new QIcon(iconPath+"email.png");
2755 emailButton.setIcon(emailIcon);
2756 emailButton.triggered.connect(this, "emailNote()");
2757 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2759 deleteButton = toolBar.addAction("Delete");
2760 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2761 deleteButton.setIcon(deleteIcon);
2762 deleteButton.triggered.connect(this, "deleteNote()");
2763 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2765 newButton = toolBar.addAction("New");
2766 QIcon newIcon = new QIcon(iconPath+"new.png");
2767 newButton.triggered.connect(this, "addNote()");
2768 newButton.setIcon(newIcon);
2769 toggleNewButton(Global.isToolbarButtonVisible("new"));
2771 allNotesButton = toolBar.addAction("All Notes");
2772 QIcon allIcon = new QIcon(iconPath+"books.png");
2773 allNotesButton.triggered.connect(this, "allNotes()");
2774 allNotesButton.setIcon(allIcon);
2775 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2777 toolBar.addSeparator();
2778 toolBar.addWidget(new QLabel(tr("Quota:")));
2779 toolBar.addWidget(quotaBar);
2780 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2782 toolBar.addSeparator();
2785 zoomSpinner = new QSpinBox();
2786 zoomSpinner.setMinimum(10);
2787 zoomSpinner.setMaximum(1000);
2788 zoomSpinner.setAccelerated(true);
2789 zoomSpinner.setSingleStep(10);
2790 zoomSpinner.setValue(100);
2791 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2792 toolBar.addWidget(new QLabel(tr("Zoom")));
2793 toolBar.addWidget(zoomSpinner);
2795 //toolBar.addWidget(new QLabel(" "));
2796 toolBar.addSeparator();
2797 toolBar.addWidget(new QLabel(tr(" Search:")));
2798 toolBar.addWidget(searchField);
2799 QSizePolicy sizePolicy = new QSizePolicy();
2800 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2801 searchField.setSizePolicy(sizePolicy);
2802 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2804 searchClearButton = toolBar.addAction("Search Clear");
2805 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2806 searchClearButton.setIcon(searchClearIcon);
2807 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2808 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2810 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2812 // Update the sychronize button picture
2814 public QMenu createPopupMenu() {
2815 QMenu contextMenu = super.createPopupMenu();
2817 contextMenu.addSeparator();
2818 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2819 contextMenu.addAction(prevAction);
2820 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2822 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2823 contextMenu.addAction(nextAction);
2824 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2826 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2827 contextMenu.addAction(upAction);
2828 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2830 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2831 contextMenu.addAction(downAction);
2832 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2834 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2835 contextMenu.addAction(synchronizeAction);
2836 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2838 QAction printAction = addContextAction("print", tr("Print"));
2839 contextMenu.addAction(printAction);
2840 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2842 QAction tagAction = addContextAction("tag", tr("Tag"));
2843 contextMenu.addAction(tagAction);
2844 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2846 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2847 contextMenu.addAction(attributeAction);
2848 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2850 QAction emailAction = addContextAction("email", tr("Email"));
2851 contextMenu.addAction(emailAction);
2852 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2854 QAction deleteAction = addContextAction("delete", tr("Delete"));
2855 contextMenu.addAction(deleteAction);
2856 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2858 QAction newAction = addContextAction("new", tr("Add"));
2859 contextMenu.addAction(newAction);
2860 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2862 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2863 contextMenu.addAction(allNotesAction);
2864 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2866 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2867 contextMenu.addAction(searchClearAction);
2868 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2873 private QAction addContextAction(String config, String name) {
2874 QAction newAction = new QAction(this);
2875 newAction.setText(name);
2876 newAction.setCheckable(true);
2877 newAction.setChecked(Global.isToolbarButtonVisible(config));
2880 private void togglePrevArrowButton(Boolean toggle) {
2881 prevButton.setVisible(toggle);
2882 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2884 private void toggleNextArrowButton(Boolean toggle) {
2885 nextButton.setVisible(toggle);
2886 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2888 private void toggleUpArrowButton(Boolean toggle) {
2889 upButton.setVisible(toggle);
2890 Global.saveToolbarButtonsVisible("upArrow", toggle);
2892 private void toggleDownArrowButton(Boolean toggle) {
2893 downButton.setVisible(toggle);
2894 Global.saveToolbarButtonsVisible("downArrow", toggle);
2896 private void toggleSynchronizeButton(Boolean toggle) {
2897 synchronizeButton.setVisible(toggle);
2898 Global.saveToolbarButtonsVisible("synchronize", toggle);
2900 private void togglePrintButton(Boolean toggle) {
2901 printButton.setVisible(toggle);
2902 Global.saveToolbarButtonsVisible("print", toggle);
2904 private void toggleTagButton(Boolean toggle) {
2905 tagButton.setVisible(toggle);
2906 Global.saveToolbarButtonsVisible("tag", toggle);
2908 private void toggleAttributeButton(Boolean toggle) {
2909 attributeButton.setVisible(toggle);
2910 Global.saveToolbarButtonsVisible("attribute", toggle);
2912 private void toggleEmailButton(Boolean toggle) {
2913 emailButton.setVisible(toggle);
2914 Global.saveToolbarButtonsVisible("email", toggle);
2916 private void toggleDeleteButton(Boolean toggle) {
2917 deleteButton.setVisible(toggle);
2918 Global.saveToolbarButtonsVisible("delete", toggle);
2920 private void toggleNewButton(Boolean toggle) {
2921 newButton.setVisible(toggle);
2922 Global.saveToolbarButtonsVisible("new", toggle);
2924 private void toggleAllNotesButton(Boolean toggle) {
2925 allNotesButton.setVisible(toggle);
2926 Global.saveToolbarButtonsVisible("allNotes", toggle);
2928 private void toggleSearchClearButton(Boolean toggle) {
2929 searchClearButton.setVisible(toggle);
2930 Global.saveToolbarButtonsVisible("searchClear", toggle);
2937 @SuppressWarnings("unused")
2938 private void updateSyncButton() {
2940 if (syncIcons == null) {
2941 syncIcons = new ArrayList<QPixmap>();
2943 synchronizeIconAngle = 0;
2944 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2946 for (int i=0; i<=360; i++) {
2947 QPixmap rotatedPix = new QPixmap(pix.size());
2948 QPainter p = new QPainter(rotatedPix);
2949 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2950 QSize size = pix.size();
2951 p.translate(size.width()/2, size.height()/2);
2954 p.setBackgroundMode(BGMode.OpaqueMode);
2955 p.translate(-size.width()/2, -size.height()/2);
2956 p.drawPixmap(0,0, pix);
2958 syncIcons.add(rotatedPix);
2962 synchronizeIconAngle++;
2963 if (synchronizeIconAngle > 359)
2964 synchronizeIconAngle=0;
2965 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2968 // Synchronize with Evernote
2969 @SuppressWarnings("unused")
2970 private void evernoteSync() {
2971 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2972 if (!Global.isConnected)
2974 if (Global.isConnected)
2975 synchronizeAnimationTimer.start(5);
2976 // synchronizeAnimationTimer.start(200);
2978 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2980 private void updateQuotaBar() {
2981 long limit = Global.getUploadLimit();
2982 long amount = Global.getUploadAmount();
2983 if (amount>0 && limit>0) {
2984 int percent =(int)(amount*100/limit);
2985 quotaBar.setValue(percent);
2987 quotaBar.setValue(0);
2990 @SuppressWarnings("unused")
2991 private void zoomChanged() {
2992 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2995 //****************************************************************
2996 //****************************************************************
2997 //* System Tray functions
2998 //****************************************************************
2999 //****************************************************************
3000 private void trayToggleVisible() {
3005 if (windowMaximized)
3012 @SuppressWarnings("unused")
3013 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3014 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3015 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3016 trayToggleVisible();
3021 //***************************************************************
3022 //***************************************************************
3023 //** These functions deal with the trash tree
3024 //***************************************************************
3025 //***************************************************************
3026 // Setup the tree containing the trash.
3027 @SuppressWarnings("unused")
3028 private void trashTreeSelection() {
3029 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3031 clearNotebookFilter();
3033 clearAttributeFilter();
3034 clearSavedSearchFilter();
3036 String tempGuid = currentNoteGuid;
3038 // currentNoteGuid = "";
3039 currentNote = new Note();
3040 selectedNoteGUIDs.clear();
3041 listManager.getSelectedNotebooks().clear();
3042 listManager.getSelectedTags().clear();
3043 listManager.setSelectedSavedSearch("");
3044 browserWindow.clear();
3046 // toggle the add buttons
3047 newButton.setEnabled(!newButton.isEnabled());
3048 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3049 menuBar.noteAdd.setVisible(true);
3051 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3052 if (selections.size() == 0) {
3053 currentNoteGuid = trashNoteGuid;
3054 trashNoteGuid = tempGuid;
3055 Global.showDeleted = false;
3056 menuBar.noteRestoreAction.setEnabled(false);
3057 menuBar.noteRestoreAction.setVisible(false);
3060 currentNoteGuid = trashNoteGuid;
3061 trashNoteGuid = tempGuid;
3062 menuBar.noteRestoreAction.setEnabled(true);
3063 menuBar.noteRestoreAction.setVisible(true);
3064 Global.showDeleted = true;
3066 listManager.loadNotesIndex();
3067 noteIndexUpdated(false);
3068 //// browserWindow.setEnabled(newButton.isEnabled());
3069 browserWindow.setReadOnly(!newButton.isEnabled());
3070 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3072 // Empty the trash file
3073 @SuppressWarnings("unused")
3074 private void emptyTrash() {
3075 // browserWindow.clear();
3076 listManager.emptyTrash();
3077 if (trashTree.selectedItems().size() > 0) {
3078 listManager.getSelectedNotebooks().clear();
3079 listManager.getSelectedTags().clear();
3080 listManager.setSelectedSavedSearch("");
3081 newButton.setEnabled(!newButton.isEnabled());
3082 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3083 menuBar.noteAdd.setVisible(true);
3084 browserWindow.clear();
3087 clearNotebookFilter();
3088 clearSavedSearchFilter();
3089 clearAttributeFilter();
3091 Global.showDeleted = false;
3092 menuBar.noteRestoreAction.setEnabled(false);
3093 menuBar.noteRestoreAction.setVisible(false);
3095 listManager.loadNotesIndex();
3096 //--->>> noteIndexUpdated(true);
3097 noteIndexUpdated(false);
3100 // Show/Hide trash window
3101 private void toggleTrashWindow() {
3102 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3103 if (trashTree.isVisible())
3107 menuBar.hideTrash.setChecked(trashTree.isVisible());
3109 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3110 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3112 private void clearTrashFilter() {
3113 Global.showDeleted = false;
3114 newButton.setEnabled(true);
3115 menuBar.noteAdd.setEnabled(true);
3116 menuBar.noteAdd.setVisible(true);
3117 trashTree.blockSignals(true);
3118 trashTree.clearSelection();
3119 trashTree.blockSignals(false);
3124 //***************************************************************
3125 //***************************************************************
3126 //** These functions deal with connection settings
3127 //***************************************************************
3128 //***************************************************************
3129 // SyncRunner had a problem and things are disconnected
3130 @SuppressWarnings("unused")
3131 private void remoteErrorDisconnect() {
3132 menuBar.connectAction.setText(tr("Connect"));
3133 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3134 menuBar.synchronizeAction.setEnabled(false);
3135 Global.isConnected = false;
3136 synchronizeAnimationTimer.stop();
3139 // Do a manual connect/disconnect
3140 private void remoteConnect() {
3141 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3143 if (Global.isConnected) {
3144 Global.isConnected = false;
3145 syncRunner.enDisconnect();
3146 setupConnectMenuOptions();
3151 AESEncrypter aes = new AESEncrypter();
3153 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3154 } catch (FileNotFoundException e) {
3155 // File not found, so we'll just get empty strings anyway.
3158 if (Global.getProxyValue("url").equals("")) {
3159 System.setProperty("http.proxyHost","") ;
3160 System.setProperty("http.proxyPort", "") ;
3161 System.setProperty("https.proxyHost","") ;
3162 System.setProperty("https.proxyPort", "") ;
3165 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3166 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3167 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3168 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3170 if (Global.getProxyValue("userid").equals("")) {
3171 Authenticator.setDefault(new Authenticator() {
3173 protected PasswordAuthentication getPasswordAuthentication() {
3175 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3181 syncRunner.userStoreUrl = Global.userStoreUrl;
3182 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3183 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3185 String userid = aes.getUserid();
3186 String password = aes.getPassword();
3187 if (!userid.equals("") && !password.equals("")) {
3188 Global.username = userid;
3189 Global.password = password;
3190 syncRunner.username = Global.username;
3191 syncRunner.password = Global.password;
3192 syncRunner.enConnect();
3195 Global.isConnected = syncRunner.isConnected;
3197 if (!Global.isConnected) {
3198 // Show the login dialog box
3199 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3200 LoginDialog login = new LoginDialog();
3203 if (!login.okPressed()) {
3207 Global.username = login.getUserid();
3208 Global.password = login.getPassword();
3210 syncRunner.username = Global.username;
3211 syncRunner.password = Global.password;
3212 syncRunner.enConnect();
3213 Global.isConnected = syncRunner.isConnected;
3216 if (!Global.isConnected)
3219 setupConnectMenuOptions();
3220 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3222 private void setupConnectMenuOptions() {
3223 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3224 if (!Global.isConnected) {
3225 menuBar.connectAction.setText(tr("Connect"));
3226 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3227 menuBar.synchronizeAction.setEnabled(false);
3229 menuBar.connectAction.setText(tr("Disconnect"));
3230 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3231 menuBar.synchronizeAction.setEnabled(true);
3233 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3238 //***************************************************************
3239 //***************************************************************
3240 //** These functions deal with the GUI Attribute tree
3241 //***************************************************************
3242 //***************************************************************
3243 @SuppressWarnings("unused")
3244 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3246 // clearTagFilter();
3247 // clearNotebookFilter();
3249 // clearSavedSearchFilter();
3251 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3252 if (item.childCount() > 0) {
3253 item.setSelected(false);
3255 Global.createdBeforeFilter.reset();
3256 Global.createdSinceFilter.reset();
3257 Global.changedBeforeFilter.reset();
3258 Global.changedSinceFilter.reset();
3259 Global.containsFilter.reset();
3260 attributeTreeSelected = item;
3261 DateAttributeFilterTable f = null;
3262 f = findDateAttributeFilterTable(item.parent());
3264 f.select(item.parent().indexOfChild(item));
3266 Global.containsFilter.select(item.parent().indexOfChild(item));
3269 listManager.loadNotesIndex();
3270 noteIndexUpdated(false);
3273 attributeTreeSelected = null;
3274 item.setSelected(false);
3275 Global.createdBeforeFilter.reset();
3276 Global.createdSinceFilter.reset();
3277 Global.changedBeforeFilter.reset();
3278 Global.changedSinceFilter.reset();
3279 Global.containsFilter.reset();
3280 listManager.loadNotesIndex();
3281 noteIndexUpdated(false);
3283 // This determines what attribute filter we need, depending upon the selection
3284 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3285 if (w.parent() != null && w.childCount() > 0) {
3286 QTreeWidgetItem parent = w.parent();
3287 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3288 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3289 return Global.createdSinceFilter;
3290 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3291 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3292 return Global.createdBeforeFilter;
3293 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3294 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3295 return Global.changedSinceFilter;
3296 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3297 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3298 return Global.changedBeforeFilter;
3303 // Show/Hide attribute search window
3304 private void toggleAttributesWindow() {
3305 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3306 if (attributeTree.isVisible())
3307 attributeTree.hide();
3309 attributeTree.show();
3310 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3312 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3313 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3315 private void clearAttributeFilter() {
3316 Global.createdBeforeFilter.reset();
3317 Global.createdSinceFilter.reset();
3318 Global.changedBeforeFilter.reset();
3319 Global.changedSinceFilter.reset();
3320 Global.containsFilter.reset();
3321 attributeTreeSelected = null;
3322 attributeTree.blockSignals(true);
3323 attributeTree.clearSelection();
3324 attributeTree.blockSignals(false);
3328 //***************************************************************
3329 //***************************************************************
3330 //** These functions deal with the GUI Note index table
3331 //***************************************************************
3332 //***************************************************************
3333 // Initialize the note list table
3334 private void initializeNoteTable() {
3335 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3336 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3337 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3338 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3340 // Show/Hide trash window
3341 @SuppressWarnings("unused")
3342 private void toggleNoteListWindow() {
3343 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3344 if (noteTableView.isVisible())
3345 noteTableView.hide();
3347 noteTableView.show();
3348 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3350 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3351 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3353 // Handle the event that a user selects a note from the table
3354 @SuppressWarnings("unused")
3355 private void noteTableSelection() {
3356 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3358 if (historyGuids.size() == 0) {
3359 historyGuids.add(currentNoteGuid);
3360 historyPosition = 1;
3362 noteTableView.showColumn(Global.noteTableGuidPosition);
3364 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3365 if (!Global.isColumnVisible("guid"))
3366 noteTableView.hideColumn(Global.noteTableGuidPosition);
3368 if (selections.size() > 0) {
3370 menuBar.noteDuplicateAction.setEnabled(true);
3371 menuBar.noteOnlineHistoryAction.setEnabled(true);
3372 menuBar.noteMergeAction.setEnabled(true);
3373 selectedNoteGUIDs.clear();
3374 if (selections.size() != 1 || Global.showDeleted) {
3375 menuBar.noteDuplicateAction.setEnabled(false);
3377 if (selections.size() != 1 || !Global.isConnected) {
3378 menuBar.noteOnlineHistoryAction.setEnabled(false);
3380 if (selections.size() == 1) {
3381 menuBar.noteMergeAction.setEnabled(false);
3383 for (int i=0; i<selections.size(); i++) {
3384 int row = selections.get(i).row();
3386 upButton.setEnabled(false);
3388 upButton.setEnabled(true);
3389 if (row < listManager.getNoteTableModel().rowCount()-1)
3390 downButton.setEnabled(true);
3392 downButton.setEnabled(false);
3393 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3394 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3395 currentNoteGuid = (String)ix.values().toArray()[0];
3396 selectedNoteGUIDs.add(currentNoteGuid);
3400 nextButton.setEnabled(true);
3401 prevButton.setEnabled(true);
3403 int endPosition = historyGuids.size()-1;
3404 for (int j=historyPosition; j<=endPosition; j++) {
3405 historyGuids.remove(historyGuids.size()-1);
3407 historyGuids.add(currentNoteGuid);
3408 historyPosition = historyGuids.size();
3410 if (historyPosition <= 1)
3411 prevButton.setEnabled(false);
3412 if (historyPosition == historyGuids.size())
3413 nextButton.setEnabled(false);
3415 fromHistory = false;
3416 scrollToGuid(currentNoteGuid);
3417 refreshEvernoteNote(true);
3418 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3420 // Trigger a refresh when the note db has been updated
3421 private void noteIndexUpdated(boolean reload) {
3422 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3424 refreshEvernoteNoteList();
3425 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3426 noteTableView.load(reload);
3427 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3429 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3430 pos = noteTableView.proxyModel.rowCount();
3433 if (noteTableView.proxyModel.rowCount() == 0)
3436 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3438 currentNoteGuid = (String)i.data();
3439 noteTableView.selectRow(pos-1);
3444 scrollToGuid(currentNoteGuid);
3445 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3447 // Called when the list of notes is updated
3448 private void refreshEvernoteNoteList() {
3449 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3450 browserWindow.setDisabled(false);
3451 if (selectedNoteGUIDs == null)
3452 selectedNoteGUIDs = new ArrayList<String>();
3453 selectedNoteGUIDs.clear(); // clear out old entries
3455 String saveCurrentNoteGuid = new String();
3456 String tempNoteGuid = new String();
3458 historyGuids.clear();
3459 historyPosition = 0;
3460 prevButton.setEnabled(false);
3461 nextButton.setEnabled(false);
3463 if (currentNoteGuid == null)
3464 currentNoteGuid = new String();
3466 //determine current note guid
3467 for (Note note : listManager.getNoteIndex()) {
3468 tempNoteGuid = note.getGuid();
3469 if (currentNoteGuid.equals(tempNoteGuid)) {
3470 saveCurrentNoteGuid = tempNoteGuid;
3474 if (listManager.getNoteIndex().size() == 0) {
3475 currentNoteGuid = "";
3477 browserWindow.clear();
3478 browserWindow.setDisabled(true);
3481 if (!saveCurrentNoteGuid.equals("")) {
3482 refreshEvernoteNote(false);
3484 currentNoteGuid = "";
3486 reloadTagTree(false);
3488 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3490 // Called when the previous arrow button is clicked
3491 @SuppressWarnings("unused")
3492 private void previousViewedAction() {
3493 if (!prevButton.isEnabled())
3495 if (historyPosition == 0)
3498 if (historyPosition <= 0)
3500 String historyGuid = historyGuids.get(historyPosition-1);
3502 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3503 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3504 if (modelIndex != null) {
3505 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3506 String tableGuid = (String)ix.values().toArray()[0];
3507 if (tableGuid.equals(historyGuid)) {
3508 noteTableView.selectRow(i);
3514 @SuppressWarnings("unused")
3515 private void nextViewedAction() {
3516 if (!nextButton.isEnabled())
3518 String historyGuid = historyGuids.get(historyPosition);
3521 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3522 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3523 if (modelIndex != null) {
3524 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3525 String tableGuid = (String)ix.values().toArray()[0];
3526 if (tableGuid.equals(historyGuid)) {
3527 noteTableView.selectRow(i);
3533 // Called when the up arrow is clicked
3534 @SuppressWarnings("unused")
3535 private void upAction() {
3536 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3537 int row = selections.get(0).row();
3539 noteTableView.selectRow(row-1);
3542 // Called when the down arrow is clicked
3543 @SuppressWarnings("unused")
3544 private void downAction() {
3545 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3546 int row = selections.get(0).row();
3547 int max = listManager.getNoteTableModel().rowCount();
3549 noteTableView.selectRow(row+1);
3552 // Update a tag string for a specific note in the list
3553 @SuppressWarnings("unused")
3554 private void updateListTags(String guid, List<String> tags) {
3555 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3556 StringBuffer tagBuffer = new StringBuffer();
3557 for (int i=0; i<tags.size(); i++) {
3558 tagBuffer.append(tags.get(i));
3559 if (i<tags.size()-1)
3560 tagBuffer.append(", ");
3563 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3564 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3565 if (modelIndex != null) {
3566 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3567 String tableGuid = (String)ix.values().toArray()[0];
3568 if (tableGuid.equals(guid)) {
3569 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3570 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3571 noteTableView.proxyModel.invalidate();
3576 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3578 // Update a title for a specific note in the list
3579 @SuppressWarnings("unused")
3580 private void updateListAuthor(String guid, String author) {
3581 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3583 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3584 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3585 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3586 if (modelIndex != null) {
3587 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3588 String tableGuid = (String)ix.values().toArray()[0];
3589 if (tableGuid.equals(guid)) {
3590 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3591 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3592 noteTableView.proxyModel.invalidate();
3598 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3600 private void updateListNoteNotebook(String guid, String notebook) {
3601 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3602 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3603 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3605 // Update a title for a specific note in the list
3606 @SuppressWarnings("unused")
3607 private void updateListSourceUrl(String guid, String url) {
3608 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3610 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3611 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3612 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3613 if (modelIndex != null) {
3614 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3615 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3616 String tableGuid = (String)ix.values().toArray()[0];
3617 if (tableGuid.equals(guid)) {
3618 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3619 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3620 noteTableView.proxyModel.invalidate();
3625 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3627 @SuppressWarnings("unused")
3628 private void updateListGuid(String oldGuid, String newGuid) {
3629 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3631 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3632 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3633 if (modelIndex != null) {
3634 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3635 String tableGuid = (String)ix.values().toArray()[0];
3636 if (tableGuid.equals(oldGuid)) {
3637 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3638 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3643 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3645 private void updateListTagName(String guid) {
3646 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3648 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3649 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3650 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3652 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3653 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3654 if (modelIndex != null) {
3655 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3656 String noteGuid = (String)ix.values().toArray()[0];
3657 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3658 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3659 i=listManager.getNoteTableModel().rowCount();
3665 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3667 private void removeListTagName(String guid) {
3668 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3670 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3671 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3672 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3673 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3674 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3677 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3678 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3679 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3680 if (modelIndex != null) {
3681 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3682 String noteGuid = (String)ix.values().toArray()[0];
3683 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3684 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3685 i=listManager.getNoteTableModel().rowCount();
3691 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3693 private void updateListNotebookName(String oldName, String newName) {
3694 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3696 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3697 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3698 if (modelIndex != null) {
3699 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3700 String tableName = (String)ix.values().toArray()[0];
3701 if (tableName.equalsIgnoreCase(oldName)) {
3702 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3706 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3708 @SuppressWarnings("unused")
3709 private void updateListDateCreated(String guid, QDateTime date) {
3710 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3712 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3713 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3714 if (modelIndex != null) {
3715 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3716 String tableGuid = (String)ix.values().toArray()[0];
3717 if (tableGuid.equals(guid)) {
3718 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3719 noteTableView.proxyModel.invalidate();
3724 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3726 @SuppressWarnings("unused")
3727 private void updateListDateSubject(String guid, QDateTime date) {
3728 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3730 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3731 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3732 if (modelIndex != null) {
3733 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3734 String tableGuid = (String)ix.values().toArray()[0];
3735 if (tableGuid.equals(guid)) {
3736 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3737 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3738 noteTableView.proxyModel.invalidate();
3743 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3745 private void updateListDateChanged(String guid, QDateTime date) {
3746 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3748 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3749 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3750 if (modelIndex != null) {
3751 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3752 String tableGuid = (String)ix.values().toArray()[0];
3753 if (tableGuid.equals(guid)) {
3754 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3755 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3760 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3762 private void updateListDateChanged() {
3763 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3764 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3765 updateListDateChanged(currentNoteGuid, date);
3766 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3769 private void scrollToCurrentGuid() {
3770 //scrollToGuid(currentNoteGuid);
3771 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3772 if (selections.size() == 0)
3774 QModelIndex index = selections.get(0);
3775 int row = selections.get(0).row();
3776 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3779 // Scroll to a particular index item
3780 private void scrollToGuid(String guid) {
3781 if (currentNote == null || guid == null)
3783 if (currentNote.isActive() && Global.showDeleted) {
3784 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3785 if (!listManager.getNoteIndex().get(i).isActive()) {
3786 currentNote = listManager.getNoteIndex().get(i);
3787 currentNoteGuid = currentNote.getGuid();
3788 i = listManager.getNoteIndex().size();
3793 if (!currentNote.isActive() && !Global.showDeleted) {
3794 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3795 if (listManager.getNoteIndex().get(i).isActive()) {
3796 currentNote = listManager.getNoteIndex().get(i);
3797 currentNoteGuid = currentNote.getGuid();
3798 i = listManager.getNoteIndex().size();
3804 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3805 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3806 if (currentNoteGuid.equals(index.data())) {
3807 // noteTableView.setCurrentIndex(index);
3808 noteTableView.selectRow(i);
3809 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3810 i=listManager.getNoteTableModel().rowCount();
3813 noteTableView.repaint();
3815 // Show/Hide columns
3816 private void showColumns() {
3817 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3818 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3819 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3820 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3821 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3822 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3823 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3824 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3825 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3826 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3827 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3829 // Title color has changed
3830 @SuppressWarnings("unused")
3831 private void titleColorChanged(Integer color) {
3832 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3834 QColor backgroundColor = new QColor();
3835 QColor foregroundColor = new QColor(QColor.black);
3836 backgroundColor.setRgb(color);
3838 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3839 foregroundColor.setRgb(QColor.white.rgb());
3841 if (selectedNoteGUIDs.size() == 0)
3842 selectedNoteGUIDs.add(currentNoteGuid);
3844 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3845 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3846 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3847 if (modelIndex != null) {
3848 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3849 String tableGuid = (String)ix.values().toArray()[0];
3850 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3851 for (int k=0; k<Global.noteTableColumnCount; k++) {
3852 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3853 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3854 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3856 i=listManager.getNoteTableModel().rowCount();
3861 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3863 // Wide list was chosen
3864 public void narrowListView() {
3865 saveNoteColumnPositions();
3866 saveNoteIndexWidth();
3868 int sortCol = noteTableView.proxyModel.sortColumn();
3869 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3870 Global.setSortColumn(sortCol);
3871 Global.setSortOrder(sortOrder);
3873 Global.setListView(Global.View_List_Narrow);
3875 menuBar.wideListView.blockSignals(true);
3876 menuBar.narrowListView.blockSignals(true);
3878 menuBar.wideListView.setChecked(false);
3879 menuBar.narrowListView.setChecked(true);
3881 menuBar.wideListView.blockSignals(false);
3882 menuBar.narrowListView.blockSignals(false);
3884 mainLeftRightSplitter.addWidget(noteTableView);
3885 mainLeftRightSplitter.addWidget(browserWindow);
3886 restoreWindowState(false);
3887 noteTableView.repositionColumns();
3888 noteTableView.resizeColumnWidths();
3889 noteTableView.resizeRowHeights();
3891 sortCol = Global.getSortColumn();
3892 sortOrder = Global.getSortOrder();
3893 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3896 noteTableView.load(false);
3897 scrollToCurrentGuid();
3899 public void wideListView() {
3900 int sortCol = noteTableView.proxyModel.sortColumn();
3901 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3902 Global.setSortColumn(sortCol);
3903 Global.setSortOrder(sortOrder);
3906 saveNoteColumnPositions();
3907 saveNoteIndexWidth();
3908 Global.setListView(Global.View_List_Wide);
3910 menuBar.wideListView.blockSignals(true);
3911 menuBar.narrowListView.blockSignals(true);
3913 menuBar.wideListView.setChecked(true);
3914 menuBar.narrowListView.setChecked(false);
3916 menuBar.wideListView.blockSignals(false);
3917 menuBar.narrowListView.blockSignals(false);
3918 browserIndexSplitter.setVisible(true);
3919 browserIndexSplitter.addWidget(noteTableView);
3920 browserIndexSplitter.addWidget(browserWindow);
3921 restoreWindowState(false);
3922 noteTableView.repositionColumns();
3923 noteTableView.resizeColumnWidths();
3924 noteTableView.resizeRowHeights();
3926 sortCol = Global.getSortColumn();
3927 sortOrder = Global.getSortOrder();
3928 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3931 noteTableView.load(false);
3932 scrollToCurrentGuid();
3936 //***************************************************************
3937 //***************************************************************
3938 //** External editor window functions
3939 //***************************************************************
3940 //***************************************************************
3941 private void listDoubleClick() {
3943 if (externalWindows.containsKey(currentNoteGuid)) {
3944 externalWindows.get(currentNoteGuid).raise();
3947 // We have a new external editor to create
3948 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3949 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3950 newBrowser.setWindowIcon(appIcon);
3951 externalWindows.put(currentNoteGuid, newBrowser);
3952 showEditorButtons(newBrowser.getBrowserWindow());
3953 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3954 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3955 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3956 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3957 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3958 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3960 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3961 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3962 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3966 @SuppressWarnings("unused")
3967 private void externalWindowTitleEdited(String guid, String text) {
3968 if (guid.equals(currentNoteGuid)) {
3969 browserWindow.setTitle(text);
3972 @SuppressWarnings({ "rawtypes", "unused" })
3973 private void externalWindowTagsEdited(String guid, List values) {
3974 StringBuffer line = new StringBuffer(100);
3975 for (int i=0; i<values.size(); i++) {
3977 line.append(Global.tagDelimeter+" ");
3978 line.append(values.get(i));
3980 if (guid.equals(currentNoteGuid)) {
3981 browserWindow.setTag(line.toString());
3984 @SuppressWarnings("unused")
3985 private void externalWindowClosing(String guid) {
3986 externalWindows.remove(guid);
3991 //***************************************************************
3992 //***************************************************************
3993 //** These functions deal with Note specific things
3994 //***************************************************************
3995 //***************************************************************
3996 @SuppressWarnings("unused")
3997 private void setNoteDirty() {
3998 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4000 // Find if the note is being edited externally. If it is, update it.
4001 if (externalWindows.containsKey(currentNoteGuid)) {
4002 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4003 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4004 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4005 window.getBrowserWindow().getBrowser().setContent(unicode);
4008 // If the note is dirty, then it is unsynchronized by default.
4012 // Set the note as dirty and check if its status is synchronized in the display table
4014 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4015 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4019 // If this wasn't already marked as unsynchronized, then we need to update the table
4020 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4021 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4022 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4023 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4024 if (modelIndex != null) {
4025 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4026 String tableGuid = (String)ix.values().toArray()[0];
4027 if (tableGuid.equals(currentNoteGuid)) {
4028 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4034 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4036 @SuppressWarnings("unused")
4037 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4038 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4039 QByteArray unicode = codec.fromUnicode(content);
4040 noteCache.remove(guid);
4041 noteCache.put(guid, unicode.toString());
4042 if (guid.equals(currentNoteGuid)) {
4044 browserWindow.getBrowser().setContent(unicode);
4047 thumbnailRunner.addWork("GENERATE "+ guid);
4048 saveNote(guid, browser);
4052 private void saveNote() {
4054 saveNote(currentNoteGuid, browserWindow);
4055 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4059 private void saveNote(String guid, BrowserWindow window) {
4060 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4061 logger.log(logger.EXTREME, "Note is dirty.");
4064 logger.log(logger.EXTREME, "Saving to cache");
4065 QTextCodec codec = QTextCodec.codecForLocale();
4066 // QTextDecoder decoder = codec.makeDecoder();
4067 codec = QTextCodec.codecForName("UTF-8");
4068 QByteArray unicode = codec.fromUnicode(window.getContent());
4069 noteCache.put(guid, unicode.toString());
4071 logger.log(logger.EXTREME, "updating list manager");
4072 listManager.updateNoteContent(guid, window.getContent());
4073 logger.log(logger.EXTREME, "Updating title");
4074 listManager.updateNoteTitle(guid, window.getTitle());
4075 updateListDateChanged();
4077 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4078 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4079 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4080 currentNote = listManager.getNoteIndex().get(i);
4081 i = listManager.getNoteIndex().size();
4086 // Get a note from Evernote (and put it in the browser)
4087 private void refreshEvernoteNote(boolean reload) {
4088 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4090 if (Global.disableViewing) {
4091 browserWindow.setEnabled(false);
4096 if (Global.showDeleted)
4098 Global.cryptCounter =0;
4099 if (currentNoteGuid.equals("")) {
4100 browserWindow.setReadOnly(true);
4108 browserWindow.loadingData(true);
4110 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4111 if (currentNote == null)
4114 loadNoteBrowserInformation(browserWindow);
4117 private void loadNoteBrowserInformation(BrowserWindow browser) {
4118 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4119 formatter.setNote(currentNote, Global.pdfPreview());
4120 formatter.setHighlight(listManager.getEnSearch());
4122 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4123 js = new QByteArray();
4124 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4125 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4126 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>");
4127 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4128 js.append("<style> img { max-width:100%; }</style>");
4129 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4130 js.append("</head>");
4131 formatter.setNote(currentNote, Global.pdfPreview());
4132 js.append(formatter.rebuildNoteHTML());
4133 js.append("</HTML>");
4134 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4135 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4136 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4137 browser.getBrowser().setContent(js);
4138 noteCache.put(currentNoteGuid, js.toString());
4140 if (formatter.resourceError)
4141 resourceErrorMessage();
4142 readOnly = formatter.readOnly;
4143 inkNote = formatter.inkNote;
4145 readOnlyCache.put(currentNoteGuid, true);
4147 inkNoteCache.put(currentNoteGuid, true);
4149 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4150 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4151 js = new QByteArray(cachedContent);
4152 browser.getBrowser().setContent(js);
4153 if (readOnlyCache.containsKey(currentNoteGuid))
4155 if (inkNoteCache.containsKey(currentNoteGuid))
4158 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4159 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4162 if (readOnly || inkNote)
4163 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4165 browser.getBrowser().page().setContentEditable(true);
4166 browser.setReadOnly(readOnly);
4167 deleteButton.setEnabled(!readOnly);
4168 tagButton.setEnabled(!readOnly);
4169 menuBar.noteDelete.setEnabled(!readOnly);
4170 menuBar.noteTags.setEnabled(!readOnly);
4171 browser.setNote(currentNote);
4173 if (conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4174 deleteButton.setEnabled(false);
4175 menuBar.notebookDeleteAction.setEnabled(false);
4177 deleteButton.setEnabled(true);
4178 menuBar.notebookDeleteAction.setEnabled(true);
4181 // Build a list of non-closed notebooks
4182 List<Notebook> nbooks = new ArrayList<Notebook>();
4183 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4184 boolean found=false;
4185 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4186 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4190 nbooks.add(listManager.getNotebookIndex().get(i));
4193 browser.setTitle(currentNote.getTitle());
4194 browser.setTag(getTagNamesForNote(currentNote));
4195 browser.setAuthor(currentNote.getAttributes().getAuthor());
4197 browser.setAltered(currentNote.getUpdated());
4198 browser.setCreation(currentNote.getCreated());
4199 if (currentNote.getAttributes().getSubjectDate() > 0)
4200 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4202 browser.setSubjectDate(currentNote.getCreated());
4203 browser.setUrl(currentNote.getAttributes().getSourceURL());
4205 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4206 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4207 browser.setAllTags(tagList);
4209 browser.setCurrentTags(currentNote.getTagNames());
4211 scrollToGuid(currentNoteGuid);
4213 browser.loadingData(false);
4214 if (thumbnailViewer.isActiveWindow())
4217 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4218 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4221 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4223 // Save a generated thumbnail
4224 private void toggleNoteInformation() {
4225 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4226 browserWindow.toggleInformation();
4227 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4228 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4229 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4231 // Listener triggered when a print button is pressed
4232 @SuppressWarnings("unused")
4233 private void printNote() {
4234 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4236 QPrintDialog dialog = new QPrintDialog();
4237 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4238 QPrinter printer = dialog.printer();
4239 browserWindow.getBrowser().print(printer);
4241 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4244 // Listener triggered when the email button is pressed
4245 @SuppressWarnings("unused")
4246 private void emailNote() {
4247 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4249 if (Desktop.isDesktopSupported()) {
4250 Desktop desktop = Desktop.getDesktop();
4252 String text2 = browserWindow.getContentsToEmail();
4253 QUrl url = new QUrl("mailto:");
4254 url.addQueryItem("subject", currentNote.getTitle());
4255 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4256 url.addQueryItem("body", text2);
4257 QDesktopServices.openUrl(url);
4261 if (desktop.isSupported(Desktop.Action.MAIL)) {
4262 URI uriMailTo = null;
4264 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4265 String text = browserWindow.getContentsToEmail();
4266 //text = "<b>" +text +"</b>";
4267 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4268 +"&BODY=" +text, null);
4269 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4270 +"&ATTACHMENT=d:/test.pdf", null);
4271 desktop.mail(uriMailTo);
4272 } catch (URISyntaxException e) {
4273 e.printStackTrace();
4274 } catch (IOException e) {
4275 e.printStackTrace();
4282 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4284 // Reindex all notes
4285 @SuppressWarnings("unused")
4286 private void fullReindex() {
4287 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4288 indexRunner.addWork("REINDEXALL");
4289 setMessage(tr("Database will be reindexed."));
4290 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4292 // Listener when a user wants to reindex a specific note
4293 @SuppressWarnings("unused")
4294 private void reindexNote() {
4295 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4296 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4297 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4299 if (selectedNotebookGUIDs.size() > 1)
4300 setMessage(tr("Notes will be reindexed."));
4302 setMessage(tr("Note will be reindexed."));
4303 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4306 @SuppressWarnings("unused")
4307 private void deleteNote() {
4308 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4309 if (currentNote == null)
4311 if (currentNoteGuid.equals(""))
4314 // If we are deleting non-trash notes
4315 if (currentNote.isActive()) {
4316 if (Global.verifyDelete()) {
4317 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4318 QMessageBox.StandardButton.Yes,
4319 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4323 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4324 selectedNoteGUIDs.add(currentNoteGuid);
4325 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4326 listManager.deleteNote(selectedNoteGUIDs.get(i));
4329 // If we are deleting from the trash.
4330 if (Global.verifyDelete()) {
4331 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4332 QMessageBox.StandardButton.Yes,
4333 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4337 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4338 selectedNoteGUIDs.add(currentNoteGuid);
4339 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4340 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4341 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4342 if (modelIndex != null) {
4343 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4344 String tableGuid = (String)ix.values().toArray()[0];
4345 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4346 listManager.getNoteTableModel().removeRow(j);
4351 listManager.expungeNote(selectedNoteGUIDs.get(i));
4354 currentNoteGuid = "";
4355 listManager.loadNotesIndex();
4356 noteIndexUpdated(false);
4357 refreshEvernoteNote(true);
4358 scrollToGuid(currentNoteGuid);
4359 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4362 @SuppressWarnings("unused")
4363 private void addNote() {
4364 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4365 // browserWindow.setEnabled(true);
4366 browserWindow.setReadOnly(false);
4368 Calendar currentTime = new GregorianCalendar();
4369 StringBuffer noteString = new StringBuffer(100);
4370 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4371 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4374 if (Global.overrideDefaultFont()) {
4375 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4376 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4377 noteString.append("<br clear=\"none\" />\n");
4378 noteString.append("</span>\n</font>\n");
4380 noteString.append("<br clear=\"none\" />\n");
4381 noteString.append("</en-note>");
4383 Long l = new Long(currentTime.getTimeInMillis());
4384 String randint = new String(Long.toString(l));
4386 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4388 // for the first non-archived notebook. Finally, if nothing else we
4389 // pick the first notebook in the list.
4390 String notebook = null;
4391 listManager.getNotebookIndex().get(0).getGuid();
4392 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4393 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4394 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4395 notebook = currentSelectedNotebook.text(2);
4397 boolean found = false;
4398 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4399 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4400 boolean match = false;
4401 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4402 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4404 j = listManager.getArchiveNotebookIndex().size();
4408 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4409 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4411 // Now we have a list of good notebooks, so we can look for the default
4413 for (int i=0; i<goodNotebooks.size(); i++) {
4414 if (goodNotebooks.get(i).isDefaultNotebook()) {
4415 notebook = goodNotebooks.get(i).getGuid();
4417 i = goodNotebooks.size();
4421 if (goodNotebooks.size() > 0 && !found)
4422 notebook = goodNotebooks.get(0).getGuid();
4425 notebook = listManager.getNotebookIndex().get(0).getGuid();
4428 Note newNote = new Note();
4429 newNote.setUpdateSequenceNum(0);
4430 newNote.setGuid(randint);
4431 newNote.setNotebookGuid(notebook);
4432 newNote.setTitle("");
4433 newNote.setContent(noteString.toString());
4434 newNote.setDeleted(0);
4435 newNote.setCreated(System.currentTimeMillis());
4436 newNote.setUpdated(System.currentTimeMillis());
4437 newNote.setActive(true);
4438 NoteAttributes na = new NoteAttributes();
4439 na.setLatitude(0.0);
4440 na.setLongitude(0.0);
4441 na.setAltitude(0.0);
4442 newNote.setAttributes(new NoteAttributes());
4443 newNote.setTagGuids(new ArrayList<String>());
4444 newNote.setTagNames(new ArrayList<String>());
4446 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4447 if (Global.newNoteWithSelectedTags()) {
4448 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4449 QTreeWidgetItem currentSelection;
4450 for (int i=0; i<selections.size(); i++) {
4451 currentSelection = selections.get(i);
4452 newNote.getTagGuids().add(currentSelection.text(2));
4453 newNote.getTagNames().add(currentSelection.text(0));
4457 conn.getNoteTable().addNote(newNote, true);
4458 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4459 listManager.addNote(newNote);
4460 // noteTableView.insertRow(newNote, true, -1);
4462 currentNote = newNote;
4463 currentNoteGuid = currentNote.getGuid();
4464 noteTableView.clearSelection();
4465 refreshEvernoteNote(true);
4466 listManager.countNotebookResults(listManager.getNoteIndex());
4467 browserWindow.titleLabel.setFocus();
4468 browserWindow.titleLabel.selectAll();
4469 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4471 // If the window is hidden, then we want to popup this in an external window &
4474 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4476 // Restore a note from the trash;
4477 @SuppressWarnings("unused")
4478 private void restoreNote() {
4480 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4481 selectedNoteGUIDs.add(currentNoteGuid);
4482 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4483 listManager.restoreNote(selectedNoteGUIDs.get(i));
4485 currentNoteGuid = "";
4486 listManager.loadNotesIndex();
4487 noteIndexUpdated(false);
4490 // Search a note for specific txt
4491 @SuppressWarnings("unused")
4492 private void findText() {
4494 find.setFocusOnTextField();
4496 @SuppressWarnings("unused")
4497 private void doFindText() {
4498 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4501 @SuppressWarnings("unused")
4502 private void updateNoteTitle(String guid, String title) {
4503 listManager.setNoteSynchronized(guid, false);
4505 // Signal received that note content has changed. Normally we just need the guid to remove
4506 // it from the cache.
4507 @SuppressWarnings("unused")
4508 private void invalidateNoteCache(String guid, String content) {
4509 String v = noteCache.remove(guid);
4510 // if (guid.equals(currentNoteGuid) && !noteDirty)
4511 refreshEvernoteNote(true);
4513 // Signal received that a note guid has changed
4514 @SuppressWarnings("unused")
4515 private void noteGuidChanged(String oldGuid, String newGuid) {
4516 if (noteCache.containsKey(oldGuid)) {
4517 if (!oldGuid.equals(currentNoteGuid)) {
4518 String cache = noteCache.get(oldGuid);
4519 noteCache.put(newGuid, cache);
4520 noteCache.remove(oldGuid);
4522 noteCache.remove(oldGuid);
4523 noteCache.put(newGuid, browserWindow.getContent());
4527 listManager.updateNoteGuid(oldGuid, newGuid, false);
4528 if (currentNoteGuid.equals(oldGuid)) {
4529 if (currentNote != null)
4530 currentNote.setGuid(newGuid);
4531 currentNoteGuid = newGuid;
4534 if (externalWindows.containsKey(oldGuid)) {
4535 ExternalBrowse b = externalWindows.get(oldGuid);
4536 externalWindows.remove(oldGuid);
4537 b.getBrowserWindow().getNote().setGuid(newGuid);
4538 externalWindows.put(newGuid, b);
4541 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4542 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4543 noteTableView.proxyModel.addGuid(newGuid);
4544 i=listManager.getNoteIndex().size();
4548 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4549 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4550 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4551 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4555 // Toggle the note editor button bar
4556 private void toggleEditorButtonBar() {
4557 if (browserWindow.buttonsVisible) {
4558 browserWindow.hideButtons();
4559 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4560 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4562 browserWindow.buttonsVisible = true;
4563 showEditorButtons(browserWindow);
4565 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4567 // Show editor buttons
4568 private void showEditorButtons(BrowserWindow browser) {
4569 browser.buttonLayout.setVisible(true);
4570 browser.undoAction.setVisible(false);
4572 browser.undoButton.setVisible(false);
4574 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4575 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4576 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4577 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4578 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4579 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4580 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4581 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4582 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4583 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4584 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4585 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4586 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4587 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4588 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4589 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4590 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4591 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4592 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4593 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4594 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4595 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4596 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4598 private void duplicateNote(String guid) {
4600 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4601 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4602 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4603 oldNote.setResources(resList);
4604 duplicateNote(oldNote);
4606 private void duplicateNote(Note oldNote) {
4608 // Now that we have a good notebook guid, we need to move the conflicting note
4609 // to the local notebook
4610 Calendar currentTime = new GregorianCalendar();
4611 Long l = new Long(currentTime.getTimeInMillis());
4612 String newGuid = new String(Long.toString(l));
4614 // Note newNote = oldNote.deepCopy();
4615 Note newNote = (Note)Global.deepCopy(oldNote);
4616 newNote.setUpdateSequenceNum(0);
4617 newNote.setGuid(newGuid);
4618 newNote.setDeleted(0);
4619 newNote.setActive(true);
4622 List<String> tagNames = new ArrayList<String>();
4623 List<String> tagGuids = new ArrayList<String>();;
4624 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4625 tagNames.add(oldNote.getTagNames().get(i));
4626 tagGuids.add(oldNote.getTagGuids().get(i));
4629 // Sort note Tags to make them look nice
4630 for (int i=0; i<tagNames.size()-1; i++) {
4631 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4632 String n1 = tagNames.get(i);
4633 String n2 = tagNames.get(i+1);
4634 tagNames.set(i, n2);
4635 tagNames.set(i+1, n1);
4638 newNote.setTagGuids(tagGuids);
4639 newNote.setTagNames(tagNames);
4641 // Add tag guids to note
4644 // Duplicate resources
4645 List<Resource> resList = oldNote.getResources();
4646 if (resList == null)
4647 resList = new ArrayList<Resource>();
4649 for (int i=0; i<resList.size(); i++) {
4651 while (l == prevGuid) {
4652 currentTime = new GregorianCalendar();
4653 l = new Long(currentTime.getTimeInMillis());
4656 String newResGuid = new String(Long.toString(l));
4657 resList.get(i).setNoteGuid(newGuid);
4658 resList.get(i).setGuid(newResGuid);
4659 resList.get(i).setUpdateSequenceNum(0);
4660 resList.get(i).setActive(true);
4661 conn.getNoteTable().noteResourceTable.saveNoteResource(
4662 (Resource)Global.deepCopy(resList.get(i)), true);
4664 newNote.setResources(resList);
4666 // Add note to the database
4667 listManager.addNote(newNote);
4668 conn.getNoteTable().addNote(newNote, true);
4669 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4670 noteTableView.insertRow(newNote, true, -1);
4671 currentNoteGuid = newNote.getGuid();
4672 currentNote = newNote;
4673 refreshEvernoteNote(true);
4674 listManager.countNotebookResults(listManager.getNoteIndex());
4678 @SuppressWarnings("unused")
4679 private void allNotes() {
4680 clearAttributeFilter();
4681 clearNotebookFilter();
4682 clearSavedSearchFilter();
4685 searchField.clear();
4686 if (Global.mimicEvernoteInterface) {
4687 notebookTree.selectGuid("");
4689 notebookTreeSelection();
4692 @SuppressWarnings("unused")
4693 private void mergeNotes() {
4694 logger.log(logger.HIGH, "Merging notes");
4697 String masterGuid = null;
4698 List<String> sources = new ArrayList<String>();
4700 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4701 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4702 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4703 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4705 masterGuid = (String)ix.values().toArray()[0];
4707 sources.add((String)ix.values().toArray()[0]);
4710 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4711 logger.log(logger.EXTREME, "Children count: "+sources.size());
4712 mergeNoteContents(masterGuid, sources);
4713 currentNoteGuid = masterGuid;
4714 noteIndexUpdated(false);
4715 refreshEvernoteNote(true);
4718 private void mergeNoteContents(String targetGuid, List<String> sources) {
4719 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4720 String newContent = target.getContent();
4721 newContent = newContent.replace("</en-note>", "<br></br>");
4723 for (int i=0; i<sources.size(); i++) {
4724 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4725 if (source.isSetTitle()) {
4726 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4728 String sourceContent = source.getContent();
4729 logger.log(logger.EXTREME, "Merging contents into note");
4730 logger.log(logger.EXTREME, sourceContent);
4731 logger.log(logger.EXTREME, "End of content");
4732 int startOfNote = sourceContent.indexOf("<en-note>");
4733 sourceContent = sourceContent.substring(startOfNote+9);
4734 int endOfNote = sourceContent.indexOf("</en-note>");
4735 sourceContent = sourceContent.substring(0,endOfNote);
4736 newContent = newContent + sourceContent;
4737 logger.log(logger.EXTREME, "New note content");
4738 logger.log(logger.EXTREME, newContent);
4739 logger.log(logger.EXTREME, "End of content");
4740 for (int j=0; j<source.getResourcesSize(); j++) {
4741 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4742 Resource r = source.getResources().get(j);
4743 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4745 Calendar currentTime = new GregorianCalendar();
4746 Long l = new Long(currentTime.getTimeInMillis());
4750 while (l == prevGuid) {
4751 currentTime = new GregorianCalendar();
4752 l = new Long(currentTime.getTimeInMillis());
4754 String newResGuid = new String(Long.toString(l));
4755 newRes.setNoteGuid(targetGuid);
4756 newRes.setGuid(newResGuid);
4757 newRes.setUpdateSequenceNum(0);
4758 newRes.setActive(true);
4759 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4762 logger.log(logger.EXTREME, "Updating note");
4763 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4764 for (int i=0; i<sources.size(); i++) {
4765 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4766 listManager.deleteNote(sources.get(i));
4768 logger.log(logger.EXTREME, "Exiting merge note");
4770 // A resource within a note has had a guid change
4771 @SuppressWarnings("unused")
4772 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4773 if (!oldGuid.equals(newGuid))
4774 Global.resourceMap.put(oldGuid, newGuid);
4776 // View a thumbnail of the note
4777 public void thumbnailView() {
4779 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4780 QFile thumbnail = new QFile(thumbnailName);
4781 if (!thumbnail.exists()) {
4783 QImage img = new QImage();
4784 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4785 thumbnailViewer.setThumbnail(img);
4787 thumbnailViewer.setThumbnail(thumbnailName);
4788 if (!thumbnailViewer.isVisible())
4789 thumbnailViewer.showFullScreen();
4791 // An error happened while saving a note. Inform the user
4792 @SuppressWarnings("unused")
4793 private void saveRunnerError(String guid, String msg) {
4795 String title = "*Unknown*";
4796 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4797 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4798 title = listManager.getMasterNoteIndex().get(i).getTitle();
4799 i=listManager.getMasterNoteIndex().size();
4802 msg = "An error has happened while saving the note \"" +title+
4803 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4804 "As a result, changes to the note may not be saved properly in the database."+
4805 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4806 "\nbe lost. Please review the note to recover any critical data before restarting.";
4808 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4811 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4812 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4813 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4814 // Find an idle preview object
4815 for (int i=0; i<thumbGenerators.size(); i++) {
4816 if (thumbGenerators.get(i).mutex.tryLock()) {
4817 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4818 thumbGenerators.get(i).loadContent(guid, html, zoom);
4822 if (thumbGenerators.size() >= 1) {
4823 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4827 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4828 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4829 thumbGenerators.add(preview);
4831 if (preview.mutex.tryLock()) {
4832 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4833 preview.loadContent(guid, html, zoom);
4835 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4840 //**********************************************************
4841 //**********************************************************
4842 //* Online user actions
4843 //**********************************************************
4844 //**********************************************************
4845 private void setupOnlineMenu() {
4846 if (!Global.isConnected) {
4847 menuBar.noteOnlineHistoryAction.setEnabled(false);
4848 menuBar.selectiveSyncAction.setEnabled(false);
4851 menuBar.noteOnlineHistoryAction.setEnabled(true);
4852 menuBar.selectiveSyncAction.setEnabled(true);
4855 @SuppressWarnings("unused")
4856 private void viewNoteHistory() {
4857 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4859 if (currentNote.getUpdateSequenceNum() == 0) {
4860 setMessage(tr("Note has never been synchronized."));
4861 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4865 setMessage(tr("Getting Note History"));
4867 Note currentOnlineNote = null;
4870 if (Global.isPremium())
4871 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4873 versions = new ArrayList<NoteVersionId>();
4874 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4875 } catch (EDAMUserException e) {
4876 setMessage("EDAMUserException: " +e.getMessage());
4878 } catch (EDAMSystemException e) {
4879 setMessage("EDAMSystemException: " +e.getMessage());
4881 } catch (EDAMNotFoundException e) {
4882 setMessage(tr("Note not found on server."));
4883 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4885 } catch (TException e) {
4886 setMessage("EDAMTransactionException: " +e.getMessage());
4890 // If we've gotten this far, we have a good note.
4891 if (historyWindow == null) {
4892 historyWindow = new OnlineNoteHistory(logger, conn);
4893 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4894 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4895 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4897 historyWindow.historyCombo.clear();
4899 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4900 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4902 historyWindow.setCurrent(isDirty);
4904 loadHistoryWindowContent(currentOnlineNote);
4905 historyWindow.load(versions);
4906 setMessage(tr("History retrieved"));
4908 historyWindow.exec();
4910 private Note reloadHistoryWindow(String selection) {
4912 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4913 String dateTimeFormat = new String(fmt);
4914 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4918 for (int i=0; i<versions.size(); i++) {
4919 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4920 if (versionDate.toString().equals(selection))
4924 if (index > -1 || selection.indexOf("Current") > -1) {
4925 Note historyNote = null;
4928 usn = versions.get(index).getUpdateSequenceNum();
4929 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4931 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4932 } catch (EDAMUserException e) {
4933 setMessage("EDAMUserException: " +e.getMessage());
4936 } catch (EDAMSystemException e) {
4937 setMessage("EDAMSystemException: " +e.getMessage());
4940 } catch (EDAMNotFoundException e) {
4941 setMessage("EDAMNotFoundException: " +e.getMessage());
4944 } catch (TException e) {
4945 setMessage("EDAMTransactionException: " +e.getMessage());
4951 if (historyNote != null)
4952 historyWindow.setContent(historyNote);
4958 private void loadHistoryWindowContent(Note note) {
4959 note.setUpdateSequenceNum(0);
4960 historyWindow.setContent(note);
4962 @SuppressWarnings("unused")
4963 private void restoreHistoryNoteAsNew() {
4964 setMessage(tr("Restoring as new note."));
4965 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4966 setMessage(tr("Note has been restored as a new note."));
4968 @SuppressWarnings("unused")
4969 private void restoreHistoryNote() {
4970 setMessage(tr("Restoring note."));
4971 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
4972 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
4975 for (int i=0; i<n.getResourcesSize(); i++) {
4976 n.getResources().get(i).setActive(true);
4977 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
4979 listManager.addNote(n);
4980 conn.getNoteTable().addNote(n, true);
4981 refreshEvernoteNote(true);
4982 setMessage(tr("Note has been restored."));
4984 @SuppressWarnings("unused")
4985 private void setupSelectiveSync() {
4987 // Get a list of valid notebooks
4988 List<Notebook> notebooks = null;
4989 List<Tag> tags = null;
4990 List<LinkedNotebook> linkedNotebooks = null;
4992 notebooks = syncRunner.noteStore.listNotebooks(syncRunner.authToken);
4993 tags = syncRunner.noteStore.listTags(syncRunner.authToken);
4994 linkedNotebooks = syncRunner.noteStore.listLinkedNotebooks(syncRunner.authToken);
4995 } catch (EDAMUserException e) {
4996 setMessage("EDAMUserException: " +e.getMessage());
4998 } catch (EDAMSystemException e) {
4999 setMessage("EDAMSystemException: " +e.getMessage());
5001 } catch (TException e) {
5002 setMessage("EDAMTransactionException: " +e.getMessage());
5004 } catch (EDAMNotFoundException e) {
5005 setMessage("EDAMNotFoundException: " +e.getMessage());
5009 // Split up notebooks into synchronized & non-synchronized
5010 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5011 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5013 for (int i=notebooks.size()-1; i>=0; i--) {
5014 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5015 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5016 ignoredBooks.add(notebooks.get(i));
5017 j=dbIgnoredNotebooks.size();
5022 // split up tags into synchronized & non-synchronized
5023 List<Tag> ignoredTags = new ArrayList<Tag>();
5024 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5026 for (int i=tags.size()-1; i>=0; i--) {
5027 for (int j=0; j<dbIgnoredTags.size(); j++) {
5028 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5029 ignoredTags.add(tags.get(i));
5030 j=dbIgnoredTags.size();
5035 // split up linked notebooks into synchronized & non-synchronized
5036 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5037 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5038 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5039 String notebookGuid = linkedNotebooks.get(i).getGuid();
5040 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5041 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5042 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5043 j=dbIgnoredLinkedNotebooks.size();
5048 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5050 if (!ignore.okClicked())
5055 // Clear out old notebooks & add the new ones
5056 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5057 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5058 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5061 List<String> newNotebooks = new ArrayList<String>();
5062 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5063 String text = ignore.getIgnoredBookList().takeItem(i).text();
5064 for (int j=0; j<notebooks.size(); j++) {
5065 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5066 Notebook n = notebooks.get(j);
5067 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5069 newNotebooks.add(n.getGuid());
5074 // Clear out old tags & add new ones
5075 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5076 for (int i=0; i<oldIgnoreTags.size(); i++) {
5077 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5080 List<String> newTags = new ArrayList<String>();
5081 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5082 String text = ignore.getIgnoredTagList().takeItem(i).text();
5083 for (int j=0; j<tags.size(); j++) {
5084 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5085 Tag t = tags.get(j);
5086 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5087 newTags.add(t.getGuid());
5093 // Clear out old tags & add new ones
5094 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5095 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5096 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5099 List<String> newLinked = new ArrayList<String>();
5100 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5101 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5102 for (int j=0; j<linkedNotebooks.size(); j++) {
5103 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5104 LinkedNotebook t = linkedNotebooks.get(j);
5105 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5106 newLinked.add(t.getGuid());
5107 j=linkedNotebooks.size();
5112 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5118 //**********************************************************
5119 //**********************************************************
5120 //* XML Modifying methods
5121 //**********************************************************
5122 //**********************************************************
5123 // An error has happended fetching a resource. let the user know
5124 private void resourceErrorMessage() {
5127 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5128 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5129 "In a perfect world this wouldn't happen, but it has.\n" +
5130 "It is embarasing when a program like me, designed to save all your\n"+
5131 "precious data, has a problem finding data.\n\n" +
5132 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5133 "In the mean time, I'm not going to let you make changes to this note.\n" +
5134 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5135 "this note on the Evernote servers. Sorry."+
5136 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5138 browserWindow.setReadOnly(true);
5144 //**********************************************************
5145 //**********************************************************
5147 //**********************************************************
5148 //**********************************************************
5149 // We should now do a sync with Evernote
5150 private void syncTimer() {
5151 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5152 syncRunner.syncNeeded = true;
5153 syncRunner.disableUploads = Global.disableUploads;
5155 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5157 private void syncStart() {
5158 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5160 if (!syncRunning && Global.isConnected) {
5161 syncRunner.setConnected(true);
5162 syncRunner.setKeepRunning(Global.keepRunning);
5163 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5165 if (syncThreadsReady > 0) {
5166 thumbnailRunner.interrupt = true;
5167 saveNoteIndexWidth();
5168 saveNoteColumnPositions();
5169 if (syncRunner.addWork("SYNC")) {
5171 syncRunner.syncNeeded = true;
5176 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5178 @SuppressWarnings("unused")
5179 private void syncThreadComplete(Boolean refreshNeeded) {
5180 setMessage(tr("Finalizing Synchronization"));
5182 syncRunning = false;
5183 syncRunner.syncNeeded = false;
5184 synchronizeAnimationTimer.stop();
5185 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5187 if (currentNote == null) {
5188 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5190 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5191 noteIndexUpdated(false);
5192 noteTableView.selectionModel().blockSignals(true);
5193 scrollToGuid(currentNoteGuid);
5194 noteTableView.selectionModel().blockSignals(false);
5195 refreshEvernoteNote(false);
5196 scrollToGuid(currentNoteGuid);
5198 if (!syncRunner.error)
5199 setMessage(tr("Synchronization Complete"));
5201 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5202 logger.log(logger.MEDIUM, "Sync complete.");
5204 public void saveUploadAmount(long t) {
5205 Global.saveUploadAmount(t);
5207 public void saveUserInformation(User user) {
5208 Global.saveUserInformation(user);
5210 public void saveEvernoteUpdateCount(int i) {
5211 Global.saveEvernoteUpdateCount(i);
5213 public void refreshLists() {
5214 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5216 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5217 tagIndexUpdated(true);
5218 notebookIndexUpdated();
5219 savedSearchIndexUpdated();
5220 listManager.loadNotesIndex();
5222 noteTableView.selectionModel().blockSignals(true);
5223 noteIndexUpdated(true);
5224 noteTableView.selectionModel().blockSignals(false);
5225 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5229 @SuppressWarnings("unused")
5230 private void authTimer() {
5231 Calendar cal = Calendar.getInstance();
5233 // If we are not connected let's get out of here
5234 if (!Global.isConnected)
5237 // If this is the first time through, then we need to set this
5238 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5239 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5241 // long now = new Date().getTime();
5242 // if (now > Global.authRefreshTime && Global.isConnected) {
5243 syncRunner.authRefreshNeeded = true;
5247 @SuppressWarnings("unused")
5248 private void authRefreshComplete(boolean goodSync) {
5249 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5250 Global.isConnected = syncRunner.isConnected;
5252 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5253 authTimer.start(1000*60*15);
5254 logger.log(logger.LOW, "Authentication token has been renewed");
5255 // setMessage("Authentication token has been renewed.");
5257 authTimer.start(1000*60*5);
5258 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5259 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5261 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5265 @SuppressWarnings("unused")
5266 private synchronized void indexTimer() {
5267 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5270 if (!indexDisabled && indexRunner.idle) {
5271 thumbnailRunner.interrupt = true;
5272 indexRunner.addWork("SCAN");
5274 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5277 @SuppressWarnings("unused")
5278 private void indexStarted() {
5279 setMessage(tr("Indexing notes"));
5281 @SuppressWarnings("unused")
5282 private void indexComplete() {
5283 setMessage(tr("Index complete"));
5285 @SuppressWarnings("unused")
5286 private synchronized void toggleNoteIndexing() {
5287 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5288 indexDisabled = !indexDisabled;
5290 setMessage(tr("Indexing is now enabled."));
5292 setMessage(tr("Indexing is now disabled."));
5293 menuBar.disableIndexing.setChecked(indexDisabled);
5294 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5297 @SuppressWarnings("unused")
5298 private void threadMonitorCheck() {
5303 alive = listManager.threadCheck(Global.tagCounterThreadId);
5306 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5307 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5308 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5309 disableTagThreadCheck = true;
5314 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5316 notebookThreadDeadCount++;
5317 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5318 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5319 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5320 disableNotebookThreadCheck=true;
5323 notebookThreadDeadCount=0;
5325 alive = listManager.threadCheck(Global.trashCounterThreadId);
5328 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5329 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5330 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5331 disableTrashThreadCheck = true;
5336 alive = listManager.threadCheck(Global.saveThreadId);
5338 saveThreadDeadCount++;
5339 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5340 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5341 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5342 disableSaveThreadCheck = true;
5345 saveThreadDeadCount=0;
5347 if (!syncThread.isAlive()) {
5348 syncThreadDeadCount++;
5349 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5350 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5351 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5352 disableSyncThreadCheck = true;
5355 syncThreadDeadCount=0;
5357 if (!indexThread.isAlive()) {
5358 indexThreadDeadCount++;
5359 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5360 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5361 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5362 disableIndexThreadCheck = true;
5365 indexThreadDeadCount=0;
5370 private void thumbnailTimer() {
5371 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5372 thumbnailRunner.addWork("SCAN");
5376 //**************************************************
5377 //* Backup & Restore
5378 //**************************************************
5379 @SuppressWarnings("unused")
5380 private void databaseBackup() {
5381 QFileDialog fd = new QFileDialog(this);
5382 fd.setFileMode(FileMode.AnyFile);
5383 fd.setConfirmOverwrite(true);
5384 fd.setWindowTitle(tr("Backup Database"));
5385 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5386 fd.setAcceptMode(AcceptMode.AcceptSave);
5387 if (saveLastPath == null || saveLastPath.equals(""))
5388 fd.setDirectory(System.getProperty("user.home"));
5390 fd.setDirectory(saveLastPath);
5391 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5397 saveLastPath = fd.selectedFiles().get(0);
5398 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5399 setMessage(tr("Backing up database"));
5401 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5403 ExportData noteWriter = new ExportData(conn, true);
5404 String fileName = fd.selectedFiles().get(0);
5406 if (!fileName.endsWith(".nnex"))
5407 fileName = fileName +".nnex";
5408 noteWriter.exportData(fileName);
5409 setMessage(tr("Database backup completed."));
5414 @SuppressWarnings("unused")
5415 private void databaseRestore() {
5416 if (QMessageBox.question(this, tr("Confirmation"),
5417 tr("This is used to restore a database from backups.\n" +
5418 "It is HIGHLY recommened that this only be used to populate\n" +
5419 "an empty database. Restoring into a database that\n already has data" +
5420 " can cause problems.\n\nAre you sure you want to continue?"),
5421 QMessageBox.StandardButton.Yes,
5422 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5427 QFileDialog fd = new QFileDialog(this);
5428 fd.setFileMode(FileMode.ExistingFile);
5429 fd.setConfirmOverwrite(true);
5430 fd.setWindowTitle(tr("Restore Database"));
5431 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5432 fd.setAcceptMode(AcceptMode.AcceptOpen);
5433 if (saveLastPath == null || saveLastPath.equals(""))
5434 fd.setDirectory(System.getProperty("user.home"));
5436 fd.setDirectory(saveLastPath);
5437 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5443 saveLastPath = fd.selectedFiles().get(0);
5444 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5446 setMessage(tr("Restoring database"));
5447 ImportData noteReader = new ImportData(conn, true);
5448 noteReader.importData(fd.selectedFiles().get(0));
5450 if (noteReader.lastError != 0) {
5451 setMessage(noteReader.getErrorMessage());
5452 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5457 listManager.loadNoteTitleColors();
5459 refreshEvernoteNote(true);
5460 setMessage(tr("Database has been restored."));
5463 @SuppressWarnings("unused")
5464 private void exportNotes() {
5465 QFileDialog fd = new QFileDialog(this);
5466 fd.setFileMode(FileMode.AnyFile);
5467 fd.setConfirmOverwrite(true);
5468 fd.setWindowTitle(tr("Backup Database"));
5469 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5470 fd.setAcceptMode(AcceptMode.AcceptSave);
5471 fd.setDirectory(System.getProperty("user.home"));
5472 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5478 setMessage(tr("Exporting Notes"));
5481 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5482 selectedNoteGUIDs.add(currentNoteGuid);
5484 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5485 String fileName = fd.selectedFiles().get(0);
5487 if (!fileName.endsWith(".nnex"))
5488 fileName = fileName +".nnex";
5489 noteWriter.exportData(fileName);
5490 setMessage(tr("Export completed."));
5496 @SuppressWarnings("unused")
5497 private void importNotes() {
5498 QFileDialog fd = new QFileDialog(this);
5499 fd.setFileMode(FileMode.ExistingFile);
5500 fd.setConfirmOverwrite(true);
5501 fd.setWindowTitle(tr("Import Notes"));
5502 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5503 fd.setAcceptMode(AcceptMode.AcceptOpen);
5504 if (saveLastPath == null || saveLastPath.equals(""))
5505 fd.setDirectory(System.getProperty("user.home"));
5507 fd.setDirectory(saveLastPath);
5508 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5514 setMessage("Importing Notes");
5517 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5518 selectedNoteGUIDs.add(currentNoteGuid);
5520 ImportData noteReader = new ImportData(conn, false);
5521 String fileName = fd.selectedFiles().get(0);
5522 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5524 if (!fileName.endsWith(".nnex"))
5525 fileName = fileName +".nnex";
5526 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5527 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5529 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5531 noteReader.importData(fileName);
5533 if (noteReader.lastError != 0) {
5534 setMessage(noteReader.getErrorMessage());
5535 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5540 listManager.loadNoteTitleColors();
5542 refreshEvernoteNote(false);
5543 setMessage(tr("Notes have been imported."));
5546 setMessage("Import completed.");
5553 //**************************************************
5554 //* Duplicate a note
5555 //**************************************************
5556 @SuppressWarnings("unused")
5557 private void duplicateNote() {
5559 duplicateNote(currentNoteGuid);
5564 //**************************************************
5566 //**************************************************
5567 public void setupFolderImports() {
5568 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5570 if (importKeepWatcher == null)
5571 importKeepWatcher = new QFileSystemWatcher();
5572 if (importDeleteWatcher == null) {
5573 importDeleteWatcher = new QFileSystemWatcher();
5574 for (int i=0; i<records.size(); i++) {
5575 if (!records.get(i).keep)
5576 folderImportDelete(records.get(i).folder);
5582 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5583 for (int i=0; i<records.size(); i++) {
5584 if (records.get(i).keep)
5585 importKeepWatcher.addPath(records.get(i).folder);
5587 importDeleteWatcher.addPath(records.get(i).folder);
5590 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5591 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5593 // Look at the files already there so we don't import them again if a new file is created
5594 if (importedFiles == null) {
5595 importedFiles = new ArrayList<String>();
5596 for (int j=0; j<records.size(); j++) {
5597 QDir dir = new QDir(records.get(j).folder);
5598 List<QFileInfo> list = dir.entryInfoList();
5599 for (int k=0; k<list.size(); k++) {
5600 if (list.get(k).isFile())
5601 importedFiles.add(list.get(k).absoluteFilePath());
5606 public void folderImport() {
5607 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5608 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5610 if (!dialog.okClicked())
5613 // We have some sort of update.
5614 if (importKeepWatcher.directories().size() > 0)
5615 importKeepWatcher.removePaths(importKeepWatcher.directories());
5616 if (importDeleteWatcher.directories().size() > 0)
5617 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5619 conn.getWatchFolderTable().expungeAll();
5620 // Start building from the table
5621 for (int i=0; i<dialog.table.rowCount(); i++) {
5622 QTableWidgetItem item = dialog.table.item(i, 0);
5623 String dir = item.text();
5624 item = dialog.table.item(i, 1);
5625 String notebook = item.text();
5626 item = dialog.table.item(i, 2);
5628 if (item.text().equalsIgnoreCase("Keep"))
5633 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5634 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5636 setupFolderImports();
5639 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5641 String whichOS = System.getProperty("os.name");
5642 if (whichOS.contains("Windows"))
5643 dirName = dirName.replace('/','\\');
5645 FileImporter importer = new FileImporter(logger, conn);
5647 QDir dir = new QDir(dirName);
5648 List<QFileInfo> list = dir.entryInfoList();
5649 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5651 for (int i=0; i<list.size(); i++){
5653 boolean redundant = false;
5654 // Check if we've already imported this one or if it existed before
5655 for (int j=0; j<importedFiles.size(); j++) {
5656 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5661 importer.setFileInfo(list.get(i));
5662 importer.setFileName(list.get(i).absoluteFilePath());
5665 if (list.get(i).isFile() && importer.isValidType()) {
5667 if (!importer.importFile()) {
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 importFilesKeep.add(list.get(i).absoluteFilePath());
5674 Note newNote = importer.getNote();
5675 newNote.setNotebookGuid(notebook);
5676 newNote.setTitle(dir.at(i));
5677 listManager.addNote(newNote);
5678 conn.getNoteTable().addNote(newNote, true);
5679 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5680 noteTableView.insertRow(newNote, true, -1);
5681 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5682 listManager.countNotebookResults(listManager.getNoteIndex());
5683 importedFiles.add(list.get(i).absoluteFilePath());
5691 public void folderImportDelete(String dirName) {
5693 String whichOS = System.getProperty("os.name");
5694 if (whichOS.contains("Windows"))
5695 dirName = dirName.replace('/','\\');
5697 FileImporter importer = new FileImporter(logger, conn);
5698 QDir dir = new QDir(dirName);
5699 List<QFileInfo> list = dir.entryInfoList();
5700 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5702 for (int i=0; i<list.size(); i++){
5703 importer.setFileInfo(list.get(i));
5704 importer.setFileName(list.get(i).absoluteFilePath());
5706 if (list.get(i).isFile() && importer.isValidType()) {
5708 if (!importer.importFile()) {
5709 // If we can't get to the file, it is probably locked. We'll try again later.
5710 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5711 importFilesKeep.add(list.get(i).absoluteFilePath());
5715 Note newNote = importer.getNote();
5716 newNote.setNotebookGuid(notebook);
5717 newNote.setTitle(dir.at(i));
5718 listManager.addNote(newNote);
5719 conn.getNoteTable().addNote(newNote, true);
5720 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5721 noteTableView.insertRow(newNote, true, -1);
5722 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5723 listManager.countNotebookResults(listManager.getNoteIndex());
5724 dir.remove(dir.at(i));
5730 //**************************************************
5732 //**************************************************
5733 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5734 logger.log(logger.HIGH, "Entering exernalFileEdited");
5736 // Strip URL prefix and base dir path
5737 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5738 String name = fileName.replace(dPath, "");
5739 int pos = name.lastIndexOf('.');
5742 guid = guid.substring(0,pos);
5744 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5746 guid = name.substring(0, pos);
5749 QFile file = new QFile(fileName);
5750 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5751 // If we can't get to the file, it is probably locked. We'll try again later.
5752 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5753 externalFiles.add(fileName);
5756 QByteArray binData = file.readAll();
5758 if (binData.size() == 0) {
5759 // If we can't get to the file, it is probably locked. We'll try again later.
5760 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5761 externalFiles.add(fileName);
5765 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5767 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5768 if (r == null || r.getData() == null || r.getData().getBody() == null)
5770 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5771 MessageDigest md = MessageDigest.getInstance("MD5");
5772 md.update(binData.toByteArray());
5773 byte[] hash = md.digest();
5774 String newHash = Global.byteArrayToHexString(hash);
5775 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5776 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5778 if (externalWindows.containsKey(r.getNoteGuid())) {
5779 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5780 r.getGuid(), oldHash, newHash);
5782 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5783 Data data = r.getData();
5784 data.setBody(binData.toByteArray());
5785 data.setBodyHash(hash);
5786 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5788 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5790 if (r.getNoteGuid().equals(currentNoteGuid)) {
5791 QWebSettings.setMaximumPagesInCache(0);
5792 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5793 refreshEvernoteNote(true);
5794 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5797 if (externalWindows.containsKey(r.getNoteGuid())) {
5798 QWebSettings.setMaximumPagesInCache(0);
5799 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5800 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5804 logger.log(logger.HIGH, "Exiting externalFielEdited");
5806 // This is a timer event that tries to save any external files that were edited. This
5807 // is only needed if we couldn't save a file earlier.
5808 public void externalFileEditedSaver() {
5809 for (int i=externalFiles.size()-1; i>=0; i--) {
5811 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5812 externalFileEdited(externalFiles.get(i));
5813 externalFiles.remove(i);
5814 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5816 for (int i=0; i<importFilesKeep.size(); i++) {
5818 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5819 folderImportKeep(importFilesKeep.get(i));
5820 importFilesKeep.remove(i);
5821 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5823 for (int i=0; i<importFilesDelete.size(); i++) {
5824 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5825 folderImportDelete(importFilesDelete.get(i));
5826 importFilesDelete.remove(i);
5833 // If an attachment on the current note was edited, we need to update the current notes's hash
5834 // Update a note content's hash. This happens if a resource is edited outside of NN
5835 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5836 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5838 for (;position>-1;) {
5839 endPos = browser.getContent().indexOf(">", position+1);
5840 String oldSegment = browser.getContent().substring(position,endPos);
5841 int hashPos = oldSegment.indexOf("hash=\"");
5842 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5843 String hash = oldSegment.substring(hashPos+6, hashEnd);
5844 if (hash.equalsIgnoreCase(oldHash)) {
5845 String newSegment = oldSegment.replace(oldHash, newHash);
5846 String content = browser.getContent().substring(0,position) +
5848 browser.getContent().substring(endPos);
5849 browser.getBrowser().setContent(new QByteArray(content));;
5852 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5857 //*************************************************
5858 //* Minimize to tray
5859 //*************************************************
5861 public void changeEvent(QEvent e) {
5862 if (e.type() == QEvent.Type.WindowStateChange) {
5863 if (isMinimized() && Global.showTrayIcon()) {
5865 QTimer.singleShot(10, this, "hide()");
5869 windowMaximized = true;
5871 windowMaximized = false;
5875 //*************************************************
5876 //* Check database userid & passwords
5877 //*************************************************
5878 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5879 Connection connection;
5882 Class.forName("org.h2.Driver");
5883 } catch (ClassNotFoundException e1) {
5884 e1.printStackTrace();
5889 String passwordString = null;
5890 if (cypherPassword==null || cypherPassword.trim().equals(""))
5891 passwordString = userPassword;
5893 passwordString = cypherPassword+" "+userPassword;
5894 connection = DriverManager.getConnection(url,userid,passwordString);
5895 } catch (SQLException e) {
5900 } catch (SQLException e) {
5901 e.printStackTrace();