2 * This file is part of NeverNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QModelIndex;
79 import com.trolltech.qt.core.QSize;
80 import com.trolltech.qt.core.QTemporaryFile;
81 import com.trolltech.qt.core.QTextCodec;
82 import com.trolltech.qt.core.QThreadPool;
83 import com.trolltech.qt.core.QTimer;
84 import com.trolltech.qt.core.QTranslator;
85 import com.trolltech.qt.core.QUrl;
86 import com.trolltech.qt.core.Qt;
87 import com.trolltech.qt.core.Qt.BGMode;
88 import com.trolltech.qt.core.Qt.ItemDataRole;
89 import com.trolltech.qt.core.Qt.SortOrder;
90 import com.trolltech.qt.core.Qt.WidgetAttribute;
91 import com.trolltech.qt.gui.QAbstractItemView;
92 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
93 import com.trolltech.qt.gui.QAction;
94 import com.trolltech.qt.gui.QApplication;
95 import com.trolltech.qt.gui.QCloseEvent;
96 import com.trolltech.qt.gui.QColor;
97 import com.trolltech.qt.gui.QComboBox;
98 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
99 import com.trolltech.qt.gui.QCursor;
100 import com.trolltech.qt.gui.QDesktopServices;
101 import com.trolltech.qt.gui.QDialog;
102 import com.trolltech.qt.gui.QFileDialog;
103 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
104 import com.trolltech.qt.gui.QFileDialog.FileMode;
105 import com.trolltech.qt.gui.QGridLayout;
106 import com.trolltech.qt.gui.QHBoxLayout;
107 import com.trolltech.qt.gui.QIcon;
108 import com.trolltech.qt.gui.QImage;
109 import com.trolltech.qt.gui.QLabel;
110 import com.trolltech.qt.gui.QListWidget;
111 import com.trolltech.qt.gui.QMainWindow;
112 import com.trolltech.qt.gui.QMenu;
113 import com.trolltech.qt.gui.QMessageBox;
114 import com.trolltech.qt.gui.QMessageBox.StandardButton;
115 import com.trolltech.qt.gui.QPainter;
116 import com.trolltech.qt.gui.QPalette.ColorRole;
117 import com.trolltech.qt.gui.QPixmap;
118 import com.trolltech.qt.gui.QPrintDialog;
119 import com.trolltech.qt.gui.QPrinter;
120 import com.trolltech.qt.gui.QSizePolicy;
121 import com.trolltech.qt.gui.QSizePolicy.Policy;
122 import com.trolltech.qt.gui.QSpinBox;
123 import com.trolltech.qt.gui.QSplashScreen;
124 import com.trolltech.qt.gui.QSplitter;
125 import com.trolltech.qt.gui.QStatusBar;
126 import com.trolltech.qt.gui.QSystemTrayIcon;
127 import com.trolltech.qt.gui.QTableWidgetItem;
128 import com.trolltech.qt.gui.QTextEdit;
129 import com.trolltech.qt.gui.QToolBar;
130 import com.trolltech.qt.gui.QTreeWidgetItem;
131 import com.trolltech.qt.network.QNetworkAccessManager;
132 import com.trolltech.qt.network.QNetworkReply;
133 import com.trolltech.qt.network.QNetworkRequest;
134 import com.trolltech.qt.webkit.QWebPage.WebAction;
135 import com.trolltech.qt.webkit.QWebSettings;
137 import cx.fbn.nevernote.config.InitializationException;
138 import cx.fbn.nevernote.config.StartupConfig;
139 import cx.fbn.nevernote.dialog.AccountDialog;
140 import cx.fbn.nevernote.dialog.ConfigDialog;
141 import cx.fbn.nevernote.dialog.DBEncryptDialog;
142 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
143 import cx.fbn.nevernote.dialog.DatabaseStatus;
144 import cx.fbn.nevernote.dialog.FindDialog;
145 import cx.fbn.nevernote.dialog.IgnoreSync;
146 import cx.fbn.nevernote.dialog.LoginDialog;
147 import cx.fbn.nevernote.dialog.NotebookArchive;
148 import cx.fbn.nevernote.dialog.NotebookEdit;
149 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
150 import cx.fbn.nevernote.dialog.PublishNotebook;
151 import cx.fbn.nevernote.dialog.SavedSearchEdit;
152 import cx.fbn.nevernote.dialog.SetIcon;
153 import cx.fbn.nevernote.dialog.ShareNotebook;
154 import cx.fbn.nevernote.dialog.StackNotebook;
155 import cx.fbn.nevernote.dialog.TagEdit;
156 import cx.fbn.nevernote.dialog.ThumbnailViewer;
157 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
158 import cx.fbn.nevernote.dialog.WatchFolder;
159 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
160 import cx.fbn.nevernote.filters.FilterEditorTags;
161 import cx.fbn.nevernote.gui.AttributeTreeWidget;
162 import cx.fbn.nevernote.gui.BrowserWindow;
163 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
164 import cx.fbn.nevernote.gui.ExternalBrowse;
165 import cx.fbn.nevernote.gui.MainMenuBar;
166 import cx.fbn.nevernote.gui.NotebookTreeWidget;
167 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
168 import cx.fbn.nevernote.gui.TableView;
169 import cx.fbn.nevernote.gui.TagTreeWidget;
170 import cx.fbn.nevernote.gui.Thumbnailer;
171 import cx.fbn.nevernote.gui.TrashTreeWidget;
172 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
173 import cx.fbn.nevernote.sql.DatabaseConnection;
174 import cx.fbn.nevernote.sql.WatchFolderRecord;
175 import cx.fbn.nevernote.threads.IndexRunner;
176 import cx.fbn.nevernote.threads.SyncRunner;
177 import cx.fbn.nevernote.threads.ThumbnailRunner;
178 import cx.fbn.nevernote.utilities.AESEncrypter;
179 import cx.fbn.nevernote.utilities.ApplicationLogger;
180 import cx.fbn.nevernote.utilities.FileImporter;
181 import cx.fbn.nevernote.utilities.FileUtils;
182 import cx.fbn.nevernote.utilities.ListManager;
183 import cx.fbn.nevernote.utilities.SyncTimes;
184 import cx.fbn.nevernote.xml.ExportData;
185 import cx.fbn.nevernote.xml.ImportData;
186 import cx.fbn.nevernote.xml.NoteFormatter;
189 public class NeverNote extends QMainWindow{
191 QStatusBar statusBar; // Application status bar
193 DatabaseConnection conn;
195 MainMenuBar menuBar; // Main menu bar
196 FindDialog find; // Text search in note dialog
197 List<String> emitLog; // Messages displayed in the status bar;
198 QSystemTrayIcon trayIcon; // little tray icon
199 QMenu trayMenu; // System tray menu
200 QAction trayExitAction; // Exit the application
201 QAction trayShowAction; // toggle the show/hide action
202 QAction trayAddNoteAction; // Add a note from the system tray
203 QNetworkAccessManager versionChecker; // Used when checking for new versions
205 NotebookTreeWidget notebookTree; // List of notebooks
206 AttributeTreeWidget attributeTree; // List of note attributes
207 TagTreeWidget tagTree; // list of user created tags
208 SavedSearchTreeWidget savedSearchTree; // list of saved searches
209 TrashTreeWidget trashTree; // Trashcan
210 TableView noteTableView; // List of notes (the widget).
212 public BrowserWindow browserWindow; // Window containing browser & labels
213 public QToolBar toolBar; // The tool bar under the menu
214 QComboBox searchField; // search filter bar on the toolbar;
215 boolean searchPerformed = false; // Search was done?
216 QuotaProgressBar quotaBar; // The current quota usage
218 ApplicationLogger logger;
219 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
220 List<String> selectedTagGUIDs; // List of selected tag GUIDs
221 List<String> selectedNoteGUIDs; // List of selected notes
222 String selectedSavedSearchGUID; // Currently selected saved searches
223 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
225 NoteFilter filter; // Note filter
226 String currentNoteGuid; // GUID of the current note
227 Note currentNote; // The currently viewed note
228 boolean noteDirty; // Has the note been changed?
229 boolean inkNote; // if this is an ink note, it is read only
230 boolean readOnly; // Is this note read-only?
233 ListManager listManager; // DB runnable task
235 List<QTemporaryFile> tempFiles; // Array of temporary files;
237 QTimer indexTimer; // timer to start the index thread
238 IndexRunner indexRunner; // thread to index notes
241 QTimer syncTimer; // Sync on an interval
242 QTimer syncDelayTimer; // Sync delay to free up database
243 SyncRunner syncRunner; // thread to do a sync.
244 QThread syncThread; // Thread which talks to evernote
245 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
246 QThread thumbnailThread; // Thread that generates pretty pictures
247 QTimer saveTimer; // Timer to save note contents
249 QTimer authTimer; // Refresh authentication
250 QTimer externalFileSaveTimer; // Save files altered externally
251 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
252 List<String> externalFiles; // External files to save later
253 List<String> importFilesKeep; // Auto-import files to save later
254 List<String> importFilesDelete; // Auto-import files to save later
256 int indexTime; // how often to try and index
257 boolean indexRunning; // Is indexing running?
258 boolean indexDisabled; // Is indexing disabled?
260 int syncThreadsReady; // number of sync threads that are free
261 int syncTime; // Sync interval
262 boolean syncRunning; // Is sync running?
263 boolean automaticSync; // do sync automatically?
264 QTreeWidgetItem attributeTreeSelected;
266 QAction prevButton; // Go to the previous item viewed
267 QAction nextButton; // Go to the next item in the history
268 QAction downButton; // Go to the next item in the list
269 QAction upButton; // Go to the prev. item in the list;
270 QAction synchronizeButton; // Synchronize with Evernote
271 QAction allNotesButton; // Reset & view all notes
272 QTimer synchronizeAnimationTimer; // Timer to change animation button
273 int synchronizeIconAngle; // Used to rotate sync icon
274 QAction printButton; // Print Button
275 QAction tagButton; // Tag edit button
276 QAction attributeButton; // Attribute information button
277 QAction emailButton; // Email button
278 QAction deleteButton; // Delete button
279 QAction newButton; // new Note Button;
280 QSpinBox zoomSpinner; // Zoom zoom
281 QAction searchClearButton; // Clear the search field
283 QSplitter mainLeftRightSplitter; // main splitter for left/right side
284 QSplitter leftSplitter1; // first left hand splitter
285 QSplitter browserIndexSplitter; // splitter between note index & note text
287 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
288 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
289 List<String> importedFiles; // History of imported files (so we don't import twice)
291 OnlineNoteHistory historyWindow; // online history window
292 List<NoteVersionId> versions; // history versions
294 QTimer threadMonitorTimer; // Timer to watch threads.
295 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
296 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
297 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
298 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
299 int tagDeadCount=0; // number of consecutive dead times for the tag thread
300 int trashDeadCount=0; // number of consecutive dead times for the trash thread
301 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
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
330 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
333 //***************************************************************
334 //***************************************************************
335 //** Constructor & main entry point
336 //***************************************************************
337 //***************************************************************
338 // Application Constructor
339 @SuppressWarnings("static-access")
340 public NeverNote(DatabaseConnection dbConn) {
342 if (conn.getConnection() == null) {
343 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
344 "is accessing the database or NeverNote is already running.\n\n" +
345 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
347 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
351 thread().setPriority(Thread.MAX_PRIORITY);
353 logger = new ApplicationLogger("nevernote.log");
354 logger.log(logger.HIGH, "Starting Application");
356 decryptOnShutdown = false;
357 encryptOnShutdown = false;
358 conn.checkDatabaseVersion();
362 // Start building the invalid XML tables
363 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
364 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
366 for (int i=0; i<elements.size(); i++) {
367 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
370 logger.log(logger.EXTREME, "Starting GUI build");
372 QTranslator nevernoteTranslator = new QTranslator();
373 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
374 QApplication.instance().installTranslator(nevernoteTranslator);
376 Global.originalPalette = QApplication.palette();
377 QApplication.setStyle(Global.getStyle());
378 if (Global.useStandardPalette())
379 QApplication.setPalette(QApplication.style().standardPalette());
380 setWindowTitle("NeverNote");
382 mainLeftRightSplitter = new QSplitter();
383 setCentralWidget(mainLeftRightSplitter);
384 leftSplitter1 = new QSplitter();
385 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
387 browserIndexSplitter = new QSplitter();
388 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
390 //* Setup threads & thread timers
391 int indexRunnerCount = Global.getIndexThreads();
392 indexRunnerCount = 1;
393 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
395 logger.log(logger.EXTREME, "Building list manager");
396 listManager = new ListManager(conn, logger);
398 logger.log(logger.EXTREME, "Building index runners & timers");
399 indexRunner = new IndexRunner("indexRunner.log",
400 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
401 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
402 indexThread = new QThread(indexRunner, "Index Thread");
403 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
406 synchronizeAnimationTimer = new QTimer();
407 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
409 indexTimer = new QTimer();
410 indexTime = 1000*Global.getIndexThreadSleepInterval();
411 indexTimer.start(indexTime); // Start indexing timer
412 indexTimer.timeout.connect(this, "indexTimer()");
413 indexDisabled = false;
414 indexRunning = false;
416 logger.log(logger.EXTREME, "Setting sync thread & timers");
418 syncRunner = new SyncRunner("syncRunner.log",
419 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
420 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
421 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
422 syncTimer = new QTimer();
423 syncTimer.timeout.connect(this, "syncTimer()");
424 syncRunner.status.message.connect(this, "setMessage(String)");
425 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
426 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
429 automaticSync = true;
430 syncTimer.start(syncTime*60*1000);
432 automaticSync = false;
435 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
436 syncThread = new QThread(syncRunner, "Synchronization Thread");
440 logger.log(logger.EXTREME, "Starting thumnail thread");
441 pdfReadyQueue = new ArrayList<String>();
442 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
443 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
444 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
445 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
446 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
447 thumbnailThread.start();
448 thumbGenerators = new ArrayList<Thumbnailer>();
449 thumbnailTimer = new QTimer();
450 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
452 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
453 thumbnailTimer.start();
455 logger.log(logger.EXTREME, "Starting authentication timer");
456 authTimer = new QTimer();
457 authTimer.timeout.connect(this, "authTimer()");
458 authTimer.start(1000*60*15);
459 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
461 logger.log(logger.EXTREME, "Setting save note timer");
462 saveTimer = new QTimer();
463 saveTimer.timeout.connect(this, "saveNote()");
464 if (Global.getAutoSaveInterval() > 0) {
465 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
468 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
470 logger.log(logger.EXTREME, "Starting external file monitor timer");
471 externalFileSaveTimer = new QTimer();
472 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
473 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
474 externalFiles = new ArrayList<String>();
475 importFilesDelete = new ArrayList<String>();
476 importFilesKeep = new ArrayList<String>();
477 externalFileSaveTimer.start();
479 notebookTree = new NotebookTreeWidget(conn);
480 attributeTree = new AttributeTreeWidget();
481 tagTree = new TagTreeWidget(conn);
482 savedSearchTree = new SavedSearchTreeWidget();
483 trashTree = new TrashTreeWidget();
484 noteTableView = new TableView(logger, listManager);
486 QGridLayout leftGrid = new QGridLayout();
487 leftSplitter1.setLayout(leftGrid);
488 leftGrid.addWidget(notebookTree, 1, 1);
489 leftGrid.addWidget(tagTree,2,1);
490 leftGrid.addWidget(attributeTree,3,1);
491 leftGrid.addWidget(savedSearchTree,4,1);
492 leftGrid.addWidget(trashTree, 5, 1);
494 // Setup the browser window
495 noteCache = new HashMap<String,String>();
496 readOnlyCache = new HashMap<String, Boolean>();
497 inkNoteCache = new HashMap<String, Boolean>();
498 browserWindow = new BrowserWindow(conn);
500 mainLeftRightSplitter.addWidget(leftSplitter1);
501 mainLeftRightSplitter.addWidget(browserIndexSplitter);
503 if (Global.getListView() == Global.View_List_Wide) {
504 browserIndexSplitter.addWidget(noteTableView);
505 browserIndexSplitter.addWidget(browserWindow);
507 mainLeftRightSplitter.addWidget(noteTableView);
508 mainLeftRightSplitter.addWidget(browserWindow);
511 searchField = new QComboBox();
512 searchField.setEditable(true);
513 searchField.activatedIndex.connect(this, "searchFieldChanged()");
514 searchField.setDuplicatesEnabled(false);
515 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
517 quotaBar = new QuotaProgressBar();
519 // Setup the thumbnail viewer
520 thumbnailViewer = new ThumbnailViewer();
521 thumbnailViewer.upArrow.connect(this, "upAction()");
522 thumbnailViewer.downArrow.connect(this, "downAction()");
523 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
524 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
526 //Setup external browser manager
527 externalWindows = new HashMap<String, ExternalBrowse>();
529 listManager.loadNotesIndex();
530 initializeNotebookTree();
532 initializeSavedSearchTree();
533 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
534 attributeTreeSelected = null;
535 initializeNoteTable();
537 selectedNoteGUIDs = new ArrayList<String>();
538 statusBar = new QStatusBar();
539 setStatusBar(statusBar);
540 menuBar = new MainMenuBar(this);
541 emitLog = new ArrayList<String>();
543 tagTree.setDeleteAction(menuBar.tagDeleteAction);
544 tagTree.setEditAction(menuBar.tagEditAction);
545 tagTree.setAddAction(menuBar.tagAddAction);
546 tagTree.setIconAction(menuBar.tagIconAction);
547 tagTree.setVisible(Global.isWindowVisible("tagTree"));
548 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
549 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
550 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
552 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
553 notebookTree.setEditAction(menuBar.notebookEditAction);
554 notebookTree.setAddAction(menuBar.notebookAddAction);
555 notebookTree.setIconAction(menuBar.notebookIconAction);
556 notebookTree.setStackAction(menuBar.notebookStackAction);
557 notebookTree.setPublishAction(menuBar.notebookPublishAction);
558 notebookTree.setShareAction(menuBar.notebookShareAction);
559 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
560 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
561 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
562 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
563 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
565 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
566 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
567 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
568 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
569 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
570 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
571 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
573 noteTableView.setAddAction(menuBar.noteAdd);
574 noteTableView.setDeleteAction(menuBar.noteDelete);
575 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
576 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
577 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
578 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
579 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
580 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
581 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
582 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
583 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
585 quotaBar.setMouseClickAction(menuBar.accountAction);
588 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
589 trashTree.setEmptyAction(menuBar.emptyTrashAction);
590 trashTree.setVisible(Global.isWindowVisible("trashTree"));
591 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
592 trashTree.updateCounts(listManager.getTrashCount());
593 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
594 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
596 noteTableView.setVisible(Global.isWindowVisible("noteList"));
597 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
599 if (!Global.isWindowVisible("editorButtonBar"))
600 toggleEditorButtonBar();
601 if (!Global.isWindowVisible("leftPanel"))
602 menuBar.hideLeftSide.setChecked(true);
603 if (Global.isWindowVisible("noteInformation"))
604 toggleNoteInformation();
608 find = new FindDialog();
609 find.getOkButton().clicked.connect(this, "doFindText()");
611 // Setup the tray icon menu bar
612 trayShowAction = new QAction("Show/Hide", this);
613 trayExitAction = new QAction("Exit", this);
614 trayAddNoteAction = new QAction("Add Note", this);
616 trayExitAction.triggered.connect(this, "closeNeverNote()");
617 trayAddNoteAction.triggered.connect(this, "addNote()");
618 trayShowAction.triggered.connect(this, "trayToggleVisible()");
620 trayMenu = new QMenu(this);
621 trayMenu.addAction(trayAddNoteAction);
622 trayMenu.addAction(trayShowAction);
623 trayMenu.addAction(trayExitAction);
626 trayIcon = new QSystemTrayIcon(this);
627 trayIcon.setToolTip("NeverNote");
628 trayIcon.setContextMenu(trayMenu);
629 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
632 currentNoteGuid = Global.getLastViewedNoteGuid();
633 historyGuids = new ArrayList<String>();
637 if (!currentNoteGuid.trim().equals("")) {
638 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
641 noteIndexUpdated(true);
643 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
644 if (menuBar.showEditorBar.isChecked())
645 showEditorButtons(browserWindow);
646 tagIndexUpdated(true);
647 savedSearchIndexUpdated();
648 notebookIndexUpdated();
650 setupSyncSignalListeners();
651 setupBrowserSignalListeners();
652 setupIndexListeners();
655 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
656 tagTree.showAllTags(true);
658 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
659 setWindowIcon(appIcon);
660 trayIcon.setIcon(appIcon);
661 if (Global.showTrayIcon())
666 scrollToGuid(currentNoteGuid);
667 if (Global.automaticLogin()) {
669 if (Global.isConnected)
672 setupFolderImports();
675 restoreWindowState(true);
677 if (Global.mimicEvernoteInterface) {
678 notebookTree.selectGuid("");
681 threadMonitorTimer = new QTimer();
682 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
683 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
685 historyGuids.add(currentNoteGuid);
688 menuBar.blockSignals(true);
689 menuBar.narrowListView.blockSignals(true);
690 menuBar.wideListView.blockSignals(true);
691 if (Global.getListView() == Global.View_List_Narrow) {
692 menuBar.narrowListView.setChecked(true);
695 menuBar.wideListView.setChecked(true);
697 menuBar.blockSignals(false);
698 menuBar.narrowListView.blockSignals(false);
699 menuBar.wideListView.blockSignals(false);
701 if (Global.getListView() == Global.View_List_Wide) {
702 browserIndexSplitter.addWidget(noteTableView);
703 browserIndexSplitter.addWidget(browserWindow);
705 mainLeftRightSplitter.addWidget(noteTableView);
706 mainLeftRightSplitter.addWidget(browserWindow);
709 int sortCol = Global.getSortColumn();
710 int sortOrder = Global.getSortOrder();
711 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
712 if (Global.checkVersionUpgrade())
717 public static void main(String[] args) {
718 log.setLevel(Level.FATAL);
719 QApplication.initialize(args);
720 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
721 QSplashScreen splash = new QSplashScreen(pixmap);
724 DatabaseConnection dbConn;
727 initializeGlobalSettings(args);
729 showSplash = Global.isWindowVisible("SplashScreen");
733 dbConn = setupDatabaseConnection();
735 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
736 Global.getFileManager().purgeResDirectory(true);
738 } catch (InitializationException e) {
741 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
745 NeverNote application = new NeverNote(dbConn);
747 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
748 if (Global.startMinimized())
749 application.showMinimized();
751 if (Global.wasWindowMaximized())
752 application.showMaximized();
758 splash.finish(application);
760 System.out.println("Goodbye.");
765 * Open the internal database, or create if not present
767 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
769 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
770 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
772 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
773 boolean dbExists = f.exists();
775 Global.setDatabaseUrl("");
777 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
778 boolean goodCheck = false;
780 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
782 if (!dialog.okPressed())
784 Global.cipherPassword = dialog.getPassword();
785 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
786 Global.getDatabaseUserPassword(), Global.cipherPassword);
789 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
790 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
791 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
795 // Encrypt the database upon shutdown
796 private void encryptOnShutdown() {
797 String dbPath= Global.getFileManager().getDbDirPath("");
798 String dbName = "NeverNote";
800 Statement st = conn.getConnection().createStatement();
801 st.execute("shutdown");
802 if (QMessageBox.question(this, tr("Are you sure"),
803 tr("Are you sure you wish to encrypt the database?"),
804 QMessageBox.StandardButton.Yes,
805 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
806 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
807 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
808 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
810 } catch (SQLException e) {
815 // Decrypt the database upon shutdown
816 private void decryptOnShutdown() {
817 String dbPath= Global.getFileManager().getDbDirPath("");
818 String dbName = "NeverNote";
820 Statement st = conn.getConnection().createStatement();
821 st.execute("shutdown");
822 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
823 encryptCipher = "AES";
825 encryptCipher = "XTEA";
826 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
827 "Are you sure you wish to decrypt the database?"),
828 QMessageBox.StandardButton.Yes,
829 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
831 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
832 Global.setDatabaseUrl("");
833 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
835 } catch (SQLException e) {
840 * Encrypt/Decrypt the local database
842 public void doDatabaseEncrypt() {
843 // The database is not currently encrypted
844 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
845 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
846 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
847 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
848 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
849 "Do you wish to proceed?"),
850 QMessageBox.StandardButton.Yes,
851 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
854 DBEncryptDialog dialog = new DBEncryptDialog();
856 if (dialog.okPressed()) {
857 Global.cipherPassword = dialog.getPassword();
858 encryptOnShutdown = true;
859 encryptCipher = dialog.getEncryptionMethod();
862 DBEncryptDialog dialog = new DBEncryptDialog();
863 dialog.setWindowTitle("Database Decryption");
864 dialog.hideEncryption();
866 if (dialog.okPressed()) {
867 if (!dialog.getPassword().equals(Global.cipherPassword)) {
868 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
871 decryptOnShutdown = true;
878 private static void initializeGlobalSettings(String[] args) throws InitializationException {
879 StartupConfig startupConfig = new StartupConfig();
881 for (String arg : args) {
882 String lower = arg.toLowerCase();
883 if (lower.startsWith("--name="))
884 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
885 if (lower.startsWith("--home="))
886 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
887 if (lower.startsWith("--disable-viewing"))
888 startupConfig.setDisableViewing(true);
890 Global.setup(startupConfig);
895 public void closeEvent(QCloseEvent event) {
896 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
901 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
904 if (currentNote!= null & browserWindow!=null) {
905 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
906 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
909 setMessage(tr("Beginning shutdown."));
911 // Close down external windows
912 Collection<ExternalBrowse> windows = externalWindows.values();
913 Iterator<ExternalBrowse> iterator = windows.iterator();
914 while (iterator.hasNext()) {
915 ExternalBrowse browser = iterator.next();
916 browser.windowClosing.disconnect();
921 externalFileEditedSaver();
922 if (Global.isConnected && Global.synchronizeOnClose()) {
923 setMessage(tr("Performing synchronization before closing."));
924 syncRunner.addWork("SYNC");
926 setMessage("Closing Program.");
927 threadMonitorTimer.stop();
929 syncRunner.addWork("STOP");
930 syncRunner.keepRunning = false;
931 thumbnailRunner.addWork("STOP");
932 syncRunner.keepRunning = false;
933 indexRunner.addWork("STOP");
934 syncRunner.keepRunning = false;
939 if (tempFiles != null)
942 browserWindow.noteSignal.tagsChanged.disconnect();
943 browserWindow.noteSignal.titleChanged.disconnect();
944 browserWindow.noteSignal.noteChanged.disconnect();
945 browserWindow.noteSignal.notebookChanged.disconnect();
946 browserWindow.noteSignal.createdDateChanged.disconnect();
947 browserWindow.noteSignal.alteredDateChanged.disconnect();
948 syncRunner.searchSignal.listChanged.disconnect();
949 syncRunner.tagSignal.listChanged.disconnect();
950 syncRunner.notebookSignal.listChanged.disconnect();
951 syncRunner.noteIndexSignal.listChanged.disconnect();
954 Global.saveWindowVisible("toolBar", toolBar.isVisible());
955 saveNoteColumnPositions();
956 saveNoteIndexWidth();
958 int width = notebookTree.columnWidth(0);
959 Global.setColumnWidth("notebookTreeName", width);
960 width = tagTree.columnWidth(0);
961 Global.setColumnWidth("tagTreeName", width);
963 Global.saveWindowMaximized(isMaximized());
964 Global.saveCurrentNoteGuid(currentNoteGuid);
966 int sortCol = noteTableView.proxyModel.sortColumn();
967 int sortOrder = noteTableView.proxyModel.sortOrder().value();
968 Global.setSortColumn(sortCol);
969 Global.setSortOrder(sortOrder);
973 Global.keepRunning = false;
975 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
976 if (indexRunner.thread().isAlive())
977 indexRunner.thread().join(50);
978 if (!indexRunner.thread().isAlive())
979 logger.log(logger.MEDIUM, "Index thread has stopped");
981 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
982 indexRunner.thread().interrupt();
984 } catch (InterruptedException e1) {
985 e1.printStackTrace();
987 if (!syncRunner.isIdle()) {
989 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
991 logger.log(logger.MEDIUM, "Sync thread has stopped");
992 } catch (InterruptedException e1) {
993 e1.printStackTrace();
997 if (encryptOnShutdown) {
1000 if (decryptOnShutdown) {
1001 decryptOnShutdown();
1004 Global.getFileManager().purgeResDirectory(false);
1005 } catch (InitializationException e) {
1006 System.out.println(tr("Empty res directory purge failed"));
1007 e.printStackTrace();
1009 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1012 @SuppressWarnings("unused")
1013 private void closeNeverNote() {
1017 public void setMessage(String s) {
1018 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1019 logger.log(logger.HIGH, "Message: " +s);
1020 statusBar.showMessage(s);
1022 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1025 private void waitCursor(boolean wait) {
1027 if (QApplication.overrideCursor() == null)
1028 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1031 while (QApplication.overrideCursor() != null)
1032 QApplication.restoreOverrideCursor();
1036 private void setupIndexListeners() {
1037 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1038 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1039 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1040 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1042 private void setupSyncSignalListeners() {
1043 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1044 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1045 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1046 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1047 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1049 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1050 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1051 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1053 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1054 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1055 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1056 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1057 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1059 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1062 private void setupBrowserSignalListeners() {
1063 setupBrowserWindowListeners(browserWindow, true);
1066 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1067 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1068 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1069 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1070 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1071 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1072 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1073 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1074 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1075 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1076 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1077 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1078 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1079 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1080 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1081 if (master) browser.focusLost.connect(this, "saveNote()");
1082 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1085 //***************************************************************
1086 //***************************************************************
1087 //* Settings and look & feel
1088 //***************************************************************
1089 //***************************************************************
1090 @SuppressWarnings("unused")
1091 private void settings() {
1092 logger.log(logger.HIGH, "Entering NeverNote.settings");
1093 saveNoteColumnPositions();
1094 saveNoteIndexWidth();
1096 ConfigDialog settings = new ConfigDialog(this);
1097 String dateFormat = Global.getDateFormat();
1098 String timeFormat = Global.getTimeFormat();
1100 indexTime = 1000*Global.getIndexThreadSleepInterval();
1101 indexTimer.start(indexTime); // reset indexing timer
1104 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1105 if (Global.showTrayIcon())
1110 if (menuBar.showEditorBar.isChecked())
1111 showEditorButtons(browserWindow);
1113 // Reset the save timer
1114 if (Global.getAutoSaveInterval() > 0)
1115 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1119 // This is a hack to force a reload of the index in case the date or time changed.
1120 // if (!dateFormat.equals(Global.getDateFormat()) ||
1121 // !timeFormat.equals(Global.getTimeFormat())) {
1123 readOnlyCache.clear();
1124 inkNoteCache.clear();
1125 noteIndexUpdated(true);
1128 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1130 // Restore things to the way they were
1131 private void restoreWindowState(boolean mainWindow) {
1132 // We need to name things or this doesn't work.
1133 setObjectName("NeverNote");
1134 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1135 browserIndexSplitter.setObjectName("browserIndexSplitter");
1136 leftSplitter1.setObjectName("leftSplitter1");
1138 // Restore the actual positions.
1140 restoreGeometry(Global.restoreGeometry(objectName()));
1141 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1142 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1143 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1146 // Save window positions for the next start
1147 private void saveWindowState() {
1148 Global.saveGeometry(objectName(), saveGeometry());
1149 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1150 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1151 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1153 // Load the style sheet
1154 private void loadStyleSheet() {
1155 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1156 fileName = Global.getFileManager().getQssDirPath("default.qss");
1157 QFile file = new QFile(fileName);
1159 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1160 if (!file.exists()) {
1161 fileName = Global.getFileManager().getQssDirPath("default.qss");
1162 file = new QFile(fileName);
1164 file.open(OpenModeFlag.ReadOnly);
1165 String styleSheet = file.readAll().toString();
1167 setStyleSheet(styleSheet);
1169 // Save column positions for the next time
1170 private void saveNoteColumnPositions() {
1171 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1172 Global.setColumnPosition("noteTableCreationPosition", position);
1173 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1174 Global.setColumnPosition("noteTableTagPosition", position);
1175 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1176 Global.setColumnPosition("noteTableNotebookPosition", position);
1177 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1178 Global.setColumnPosition("noteTableChangedPosition", position);
1179 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1180 Global.setColumnPosition("noteTableAuthorPosition", position);
1181 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1182 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1183 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1184 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1185 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1186 Global.setColumnPosition("noteTableTitlePosition", position);
1187 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1188 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1189 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1190 Global.setColumnPosition("noteTableGuidPosition", position);
1191 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1192 Global.setColumnPosition("noteTableThumbnailPosition", position);
1195 // Save column widths for the next time
1196 private void saveNoteIndexWidth() {
1198 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1199 Global.setColumnWidth("noteTableCreationPosition", width);
1200 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1201 Global.setColumnWidth("noteTableChangedPosition", width);
1202 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1203 Global.setColumnWidth("noteTableGuidPosition", width);
1204 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1205 Global.setColumnWidth("noteTableNotebookPosition", width);
1206 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1207 Global.setColumnWidth("noteTableTagPosition", width);
1208 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1209 Global.setColumnWidth("noteTableTitlePosition", width);
1210 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1211 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1212 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1213 Global.setColumnWidth("noteTableAuthorPosition", width);
1214 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1215 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1216 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1217 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1218 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1219 Global.setColumnWidth("noteTableThumbnailPosition", width);
1220 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1221 Global.setColumnWidth("noteTableGuidPosition", width);
1225 //***************************************************************
1226 //***************************************************************
1227 //** These functions deal with Notebook menu items
1228 //***************************************************************
1229 //***************************************************************
1230 // Setup the tree containing the user's notebooks.
1231 private void initializeNotebookTree() {
1232 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1233 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1234 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1235 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1236 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1238 // Listener when a notebook is selected
1239 private void notebookTreeSelection() {
1240 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1243 clearAttributeFilter();
1244 clearSavedSearchFilter();
1245 if (Global.mimicEvernoteInterface) {
1247 searchField.clear();
1249 menuBar.noteRestoreAction.setVisible(false);
1250 menuBar.notebookEditAction.setEnabled(true);
1251 menuBar.notebookDeleteAction.setEnabled(true);
1252 menuBar.notebookPublishAction.setEnabled(true);
1253 menuBar.notebookShareAction.setEnabled(true);
1254 menuBar.notebookIconAction.setEnabled(true);
1255 menuBar.notebookStackAction.setEnabled(true);
1256 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1257 selectedNotebookGUIDs.clear();
1259 String stackName = "";
1260 if (selections.size() > 0) {
1261 guid = (selections.get(0).text(2));
1262 stackName = selections.get(0).text(0);
1264 if (!Global.mimicEvernoteInterface) {
1265 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1266 if (selections.size()==0) {
1267 selectedNotebookGUIDs.clear();
1268 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1269 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1271 menuBar.notebookEditAction.setEnabled(false);
1272 menuBar.notebookDeleteAction.setEnabled(false);
1273 menuBar.notebookStackAction.setEnabled(false);
1274 menuBar.notebookIconAction.setEnabled(false);
1277 if (!guid.equals("") && !guid.equals("STACK")) {
1278 selectedNotebookGUIDs.add(guid);
1279 menuBar.notebookIconAction.setEnabled(true);
1281 menuBar.notebookIconAction.setEnabled(true);
1282 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1283 Notebook book = listManager.getNotebookIndex().get(j);
1284 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1285 selectedNotebookGUIDs.add(book.getGuid());
1288 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1289 listManager.loadNotesIndex();
1290 noteIndexUpdated(false);
1291 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1294 private void clearNotebookFilter() {
1295 notebookTree.blockSignals(true);
1296 notebookTree.clearSelection();
1297 menuBar.noteRestoreAction.setVisible(false);
1298 menuBar.notebookEditAction.setEnabled(false);
1299 menuBar.notebookDeleteAction.setEnabled(false);
1300 selectedNotebookGUIDs.clear();
1301 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1302 notebookTree.blockSignals(false);
1304 // Triggered when the notebook DB has been updated
1305 private void notebookIndexUpdated() {
1306 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1308 // Get the possible icons
1309 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1310 notebookTree.setIcons(icons);
1312 if (selectedNotebookGUIDs == null)
1313 selectedNotebookGUIDs = new ArrayList<String>();
1314 List<Notebook> books = conn.getNotebookTable().getAll();
1315 for (int i=books.size()-1; i>=0; i--) {
1316 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1317 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1319 j=listManager.getArchiveNotebookIndex().size();
1325 listManager.countNotebookResults(listManager.getNoteIndex());
1326 notebookTree.blockSignals(true);
1327 notebookTree.load(books, listManager.getLocalNotebooks());
1328 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1329 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1331 selectedNotebookGUIDs.remove(i);
1333 notebookTree.blockSignals(false);
1335 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1337 // Show/Hide note information
1338 private void toggleNotebookWindow() {
1339 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1340 if (notebookTree.isVisible())
1341 notebookTree.hide();
1343 notebookTree.show();
1344 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1345 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1346 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1348 // Add a new notebook
1349 @SuppressWarnings("unused")
1350 private void addNotebook() {
1351 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1352 NotebookEdit edit = new NotebookEdit();
1353 edit.setNotebooks(listManager.getNotebookIndex());
1356 if (!edit.okPressed())
1359 Calendar currentTime = new GregorianCalendar();
1360 Long l = new Long(currentTime.getTimeInMillis());
1361 String randint = new String(Long.toString(l));
1363 Notebook newBook = new Notebook();
1364 newBook.setUpdateSequenceNum(0);
1365 newBook.setGuid(randint);
1366 newBook.setName(edit.getNotebook());
1367 newBook.setServiceCreated(new Date().getTime());
1368 newBook.setServiceUpdated(new Date().getTime());
1369 newBook.setDefaultNotebook(false);
1370 newBook.setPublished(false);
1372 listManager.getNotebookIndex().add(newBook);
1374 listManager.getLocalNotebooks().add(newBook.getGuid());
1375 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1376 notebookIndexUpdated();
1377 listManager.countNotebookResults(listManager.getNoteIndex());
1378 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1379 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1381 // Edit an existing notebook
1382 @SuppressWarnings("unused")
1383 private void stackNotebook() {
1384 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1385 StackNotebook edit = new StackNotebook();
1387 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1388 QTreeWidgetItem currentSelection;
1389 for (int i=0; i<selections.size(); i++) {
1390 currentSelection = selections.get(0);
1391 String guid = currentSelection.text(2);
1392 if (guid.equalsIgnoreCase("")) {
1393 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1396 if (guid.equalsIgnoreCase("STACK")) {
1397 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1402 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1407 if (!edit.okPressed())
1410 String stack = edit.getStackName();
1412 for (int i=0; i<selections.size(); i++) {
1413 currentSelection = selections.get(i);
1414 String guid = currentSelection.text(2);
1415 listManager.updateNotebookStack(guid, stack);
1417 notebookIndexUpdated();
1418 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1420 // Edit an existing notebook
1421 @SuppressWarnings("unused")
1422 private void editNotebook() {
1423 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1424 NotebookEdit edit = new NotebookEdit();
1426 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1427 QTreeWidgetItem currentSelection;
1428 currentSelection = selections.get(0);
1429 edit.setNotebook(currentSelection.text(0));
1431 String guid = currentSelection.text(2);
1432 if (!guid.equalsIgnoreCase("STACK")) {
1433 edit.setTitle(tr("Edit Notebook"));
1434 edit.setNotebooks(listManager.getNotebookIndex());
1435 edit.setLocalCheckboxEnabled(false);
1436 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1437 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1438 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1439 i=listManager.getNotebookIndex().size();
1443 edit.setTitle(tr("Edit Stack"));
1444 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1445 edit.hideLocalCheckbox();
1446 edit.hideDefaultCheckbox();
1451 if (!edit.okPressed())
1455 if (guid.equalsIgnoreCase("STACK")) {
1456 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1457 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1458 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1459 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1460 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1462 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1463 currentSelection.setText(0, edit.getNotebook());
1467 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1468 currentSelection.setText(0, edit.getNotebook());
1470 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1471 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1472 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1473 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1474 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1475 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1476 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1477 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1479 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1480 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1481 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1482 linkedNotebook.setShareName(edit.getNotebook());
1483 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1485 i=listManager.getNotebookIndex().size();
1489 // Build a list of non-closed notebooks
1490 List<Notebook> nbooks = new ArrayList<Notebook>();
1491 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1492 boolean found=false;
1493 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1494 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1498 nbooks.add(listManager.getNotebookIndex().get(i));
1502 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1503 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1504 browserWindow.setNotebookList(filteredBooks);
1505 Iterator<String> set = externalWindows.keySet().iterator();
1506 while(set.hasNext())
1507 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1508 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1510 // Publish a notebook
1511 @SuppressWarnings("unused")
1512 private void publishNotebook() {
1513 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1514 QTreeWidgetItem currentSelection;
1515 currentSelection = selections.get(0);
1516 String guid = currentSelection.text(2);
1518 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1523 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1524 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1525 n = listManager.getNotebookIndex().get(i);
1527 i = listManager.getNotebookIndex().size();
1533 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1536 if (!publish.okClicked())
1539 Publishing p = publish.getPublishing();
1540 boolean isPublished = !publish.isStopPressed();
1541 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1542 n.setPublished(isPublished);
1544 listManager.getNotebookIndex().set(position, n);
1545 notebookIndexUpdated();
1547 // Publish a notebook
1548 @SuppressWarnings("unused")
1549 private void shareNotebook() {
1550 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1551 QTreeWidgetItem currentSelection;
1552 currentSelection = selections.get(0);
1553 String guid = currentSelection.text(2);
1555 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1559 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1560 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1561 n = listManager.getNotebookIndex().get(i);
1562 i = listManager.getNotebookIndex().size();
1566 String authToken = null;
1567 if (syncRunner.isConnected)
1568 authToken = syncRunner.authToken;
1569 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1574 // Delete an existing notebook
1575 @SuppressWarnings("unused")
1576 private void deleteNotebook() {
1577 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1578 boolean stacksFound = false;
1579 boolean notebooksFound = false;
1580 boolean assigned = false;
1581 // Check if any notes have this notebook
1582 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1583 for (int i=0; i<selections.size(); i++) {
1584 QTreeWidgetItem currentSelection;
1585 currentSelection = selections.get(i);
1586 String guid = currentSelection.text(2);
1587 if (!guid.equalsIgnoreCase("STACK")) {
1588 notebooksFound = true;
1589 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1590 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1591 if (noteGuid.equals(guid)) {
1593 j=listManager.getNoteIndex().size();
1594 i=selections.size();
1602 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1603 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1607 if (conn.getNotebookTable().getAll().size() == 1) {
1608 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1612 // If all notebooks are clear, verify the delete
1613 String msg1 = new String(tr("Delete selected notebooks?"));
1614 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1615 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1616 " not deleted unless selected?"));
1618 if (stacksFound && notebooksFound)
1620 if (!stacksFound && notebooksFound)
1622 if (stacksFound && !notebooksFound)
1624 if (QMessageBox.question(this, tr("Confirmation"), msg,
1625 QMessageBox.StandardButton.Yes,
1626 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1630 // If confirmed, delete the notebook
1631 for (int i=selections.size()-1; i>=0; i--) {
1632 QTreeWidgetItem currentSelection;
1633 currentSelection = selections.get(i);
1634 String guid = currentSelection.text(2);
1635 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1636 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1637 listManager.renameStack(currentSelection.text(0), "");
1639 conn.getNotebookTable().expungeNotebook(guid, true);
1640 listManager.deleteNotebook(guid);
1644 notebookIndexUpdated();
1645 // notebookTreeSelection();
1646 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1647 // listManager.countNotebookResults(listManager.getNoteIndex());
1648 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1650 // A note's notebook has been updated
1651 @SuppressWarnings("unused")
1652 private void updateNoteNotebook(String guid, String notebookGuid) {
1654 // Update the list manager
1655 listManager.updateNoteNotebook(guid, notebookGuid);
1656 listManager.countNotebookResults(listManager.getNoteIndex());
1657 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1659 // Find the name of the notebook
1660 String notebookName = null;
1661 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1662 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1663 notebookName = listManager.getNotebookIndex().get(i).getName();
1668 // If we found the name, update the browser window
1669 if (notebookName != null) {
1670 updateListNoteNotebook(guid, notebookName);
1671 if (guid.equals(currentNoteGuid)) {
1672 int pos = browserWindow.notebookBox.findText(notebookName);
1674 browserWindow.notebookBox.setCurrentIndex(pos);
1678 // If we're dealing with the current note, then we need to be sure and update the notebook there
1679 if (guid.equals(currentNoteGuid)) {
1680 if (currentNote != null) {
1681 currentNote.setNotebookGuid(notebookGuid);
1685 // Open/close notebooks
1686 @SuppressWarnings("unused")
1687 private void closeNotebooks() {
1688 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1690 if (!na.okClicked())
1694 listManager.getArchiveNotebookIndex().clear();
1696 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1697 String text = na.getClosedBookList().takeItem(i).text();
1698 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1699 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1700 Notebook n = listManager.getNotebookIndex().get(j);
1701 conn.getNotebookTable().setArchived(n.getGuid(),true);
1702 listManager.getArchiveNotebookIndex().add(n);
1703 j=listManager.getNotebookIndex().size();
1708 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1709 String text = na.getOpenBookList().takeItem(i).text();
1710 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1711 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1712 Notebook n = listManager.getNotebookIndex().get(j);
1713 conn.getNotebookTable().setArchived(n.getGuid(),false);
1714 j=listManager.getNotebookIndex().size();
1718 notebookTreeSelection();
1719 listManager.loadNotesIndex();
1720 notebookIndexUpdated();
1721 noteIndexUpdated(false);
1722 reloadTagTree(true);
1723 // noteIndexUpdated(false);
1725 // Build a list of non-closed notebooks
1726 List<Notebook> nbooks = new ArrayList<Notebook>();
1727 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1728 boolean found=false;
1729 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1730 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1734 nbooks.add(listManager.getNotebookIndex().get(i));
1737 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1738 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1739 browserWindow.setNotebookList(filteredBooks);
1741 // Update any external windows
1742 Iterator<String> set = externalWindows.keySet().iterator();
1743 while(set.hasNext())
1744 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1748 // Change the notebook's icon
1749 @SuppressWarnings("unused")
1750 private void setNotebookIcon() {
1751 boolean stackSelected = false;
1752 boolean allNotebookSelected = false;
1754 QTreeWidgetItem currentSelection;
1755 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1756 if (selections.size() == 0)
1759 currentSelection = selections.get(0);
1760 String guid = currentSelection.text(2);
1761 if (guid.equalsIgnoreCase(""))
1762 allNotebookSelected = true;
1763 if (guid.equalsIgnoreCase("STACK"))
1764 stackSelected = true;
1766 QIcon currentIcon = currentSelection.icon(0);
1770 if (!stackSelected && !allNotebookSelected) {
1771 icon = conn.getNotebookTable().getIcon(guid);
1773 dialog = new SetIcon(currentIcon, saveLastPath);
1774 dialog.setUseDefaultIcon(true);
1776 dialog = new SetIcon(icon, saveLastPath);
1777 dialog.setUseDefaultIcon(false);
1780 if (stackSelected) {
1781 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1783 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1786 dialog = new SetIcon(currentIcon, saveLastPath);
1787 dialog.setUseDefaultIcon(true);
1789 dialog = new SetIcon(icon, saveLastPath);
1790 dialog.setUseDefaultIcon(false);
1794 if (dialog.okPressed()) {
1795 saveLastPath = dialog.getPath();
1797 QIcon newIcon = dialog.getIcon();
1798 if (stackSelected) {
1799 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1800 if (newIcon == null) {
1801 newIcon = new QIcon(iconPath+"books2.png");
1803 currentSelection.setIcon(0,newIcon);
1806 if (allNotebookSelected) {
1807 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1808 if (newIcon == null) {
1809 newIcon = new QIcon(iconPath+"notebook-green.png");
1811 currentSelection.setIcon(0,newIcon);
1814 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1815 if (newIcon == null) {
1816 boolean isPublished = false;;
1817 boolean found = false;
1818 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1819 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1820 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1824 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1826 currentSelection.setIcon(0, newIcon);
1832 //***************************************************************
1833 //***************************************************************
1834 //** These functions deal with Tag menu items
1835 //***************************************************************
1836 //***************************************************************
1837 // Add a new notebook
1838 @SuppressWarnings("unused")
1839 private void addTag() {
1840 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1841 TagEdit edit = new TagEdit();
1842 edit.setTagList(listManager.getTagIndex());
1845 if (!edit.okPressed())
1848 Calendar currentTime = new GregorianCalendar();
1849 Long l = new Long(currentTime.getTimeInMillis());
1850 String randint = new String(Long.toString(l));
1852 Tag newTag = new Tag();
1853 newTag.setUpdateSequenceNum(0);
1854 newTag.setGuid(randint);
1855 newTag.setName(edit.getTag());
1856 conn.getTagTable().addTag(newTag, true);
1857 listManager.getTagIndex().add(newTag);
1858 reloadTagTree(true);
1860 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1862 @SuppressWarnings("unused")
1863 private void reloadTagTree() {
1864 reloadTagTree(false);
1866 private void reloadTagTree(boolean reload) {
1867 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1868 tagIndexUpdated(reload);
1869 boolean filter = false;
1870 listManager.countTagResults(listManager.getNoteIndex());
1871 if (notebookTree.selectedItems().size() > 0
1872 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1874 if (tagTree.selectedItems().size() > 0)
1876 tagTree.showAllTags(!filter);
1877 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1879 // Edit an existing tag
1880 @SuppressWarnings("unused")
1881 private void editTag() {
1882 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1883 TagEdit edit = new TagEdit();
1884 edit.setTitle("Edit Tag");
1885 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1886 QTreeWidgetItem currentSelection;
1887 currentSelection = selections.get(0);
1888 edit.setTag(currentSelection.text(0));
1889 edit.setTagList(listManager.getTagIndex());
1892 if (!edit.okPressed())
1895 String guid = currentSelection.text(2);
1896 currentSelection.setText(0,edit.getTag());
1898 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1899 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1900 listManager.getTagIndex().get(i).setName(edit.getTag());
1901 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1902 updateListTagName(guid);
1903 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1904 browserWindow.setTag(getTagNamesForNote(currentNote));
1905 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1909 browserWindow.setTag(getTagNamesForNote(currentNote));
1910 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1912 // Delete an existing tag
1913 @SuppressWarnings("unused")
1914 private void deleteTag() {
1915 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1917 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1918 QMessageBox.StandardButton.Yes,
1919 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1923 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1924 for (int i=selections.size()-1; i>=0; i--) {
1925 QTreeWidgetItem currentSelection;
1926 currentSelection = selections.get(i);
1927 removeTagItem(currentSelection.text(2));
1929 tagIndexUpdated(true);
1931 listManager.countTagResults(listManager.getNoteIndex());
1932 // tagTree.updateCounts(listManager.getTagCounter());
1933 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1935 // Remove a tag tree item. Go recursively down & remove the children too
1936 private void removeTagItem(String guid) {
1937 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1938 String parent = listManager.getTagIndex().get(j).getParentGuid();
1939 if (parent != null && parent.equals(guid)) {
1940 //Remove this tag's children
1941 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1944 //Now, remove this tag
1945 removeListTagName(guid);
1946 conn.getTagTable().expungeTag(guid, true);
1947 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1948 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1949 listManager.getTagIndex().remove(a);
1954 // Setup the tree containing the user's tags
1955 private void initializeTagTree() {
1956 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
1957 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
1958 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
1959 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
1960 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
1961 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
1963 // Listener when a tag is selected
1964 private void tagTreeSelection() {
1965 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
1968 clearAttributeFilter();
1969 clearSavedSearchFilter();
1971 menuBar.noteRestoreAction.setVisible(false);
1973 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1974 QTreeWidgetItem currentSelection;
1975 selectedTagGUIDs.clear();
1976 for (int i=0; i<selections.size(); i++) {
1977 currentSelection = selections.get(i);
1978 selectedTagGUIDs.add(currentSelection.text(2));
1980 if (selections.size() > 0) {
1981 menuBar.tagEditAction.setEnabled(true);
1982 menuBar.tagDeleteAction.setEnabled(true);
1983 menuBar.tagIconAction.setEnabled(true);
1986 menuBar.tagEditAction.setEnabled(false);
1987 menuBar.tagDeleteAction.setEnabled(false);
1988 menuBar.tagIconAction.setEnabled(true);
1990 listManager.setSelectedTags(selectedTagGUIDs);
1991 listManager.loadNotesIndex();
1992 noteIndexUpdated(false);
1993 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
1995 // trigger the tag index to be refreshed
1996 @SuppressWarnings("unused")
1997 private void tagIndexUpdated() {
1998 tagIndexUpdated(true);
2000 private void tagIndexUpdated(boolean reload) {
2001 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2002 if (selectedTagGUIDs == null)
2003 selectedTagGUIDs = new ArrayList<String>();
2005 listManager.reloadTagIndex();
2007 tagTree.blockSignals(true);
2009 tagTree.setIcons(conn.getTagTable().getAllIcons());
2010 tagTree.load(listManager.getTagIndex());
2012 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2013 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2015 selectedTagGUIDs.remove(i);
2017 tagTree.blockSignals(false);
2019 browserWindow.setTag(getTagNamesForNote(currentNote));
2020 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2022 // Show/Hide note information
2023 private void toggleTagWindow() {
2024 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2025 if (tagTree.isVisible())
2029 menuBar.hideTags.setChecked(tagTree.isVisible());
2030 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2031 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2033 // A note's tags have been updated
2034 @SuppressWarnings("unused")
2035 private void updateNoteTags(String guid, List<String> tags) {
2036 // Save any new tags. We'll need them later.
2037 List<String> newTags = new ArrayList<String>();
2038 for (int i=0; i<tags.size(); i++) {
2039 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2040 newTags.add(tags.get(i));
2043 listManager.saveNoteTags(guid, tags);
2044 listManager.countTagResults(listManager.getNoteIndex());
2045 StringBuffer names = new StringBuffer("");
2046 for (int i=0; i<tags.size(); i++) {
2047 names = names.append(tags.get(i));
2048 if (i<tags.size()-1) {
2049 names.append(Global.tagDelimeter + " ");
2052 browserWindow.setTag(names.toString());
2055 // Now, we need to add any new tags to the tag tree
2056 for (int i=0; i<newTags.size(); i++)
2057 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2059 // Get a string containing all tag names for a note
2060 private String getTagNamesForNote(Note n) {
2061 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2062 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2064 StringBuffer buffer = new StringBuffer(100);
2065 Vector<String> v = new Vector<String>();
2066 List<String> guids = n.getTagGuids();
2071 for (int i=0; i<guids.size(); i++) {
2072 v.add(listManager.getTagNameByGuid(guids.get(i)));
2074 Comparator<String> comparator = Collections.reverseOrder();
2075 Collections.sort(v,comparator);
2076 Collections.reverse(v);
2078 for (int i = 0; i<v.size(); i++) {
2080 buffer.append(", ");
2081 buffer.append(v.get(i));
2084 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2085 return buffer.toString();
2087 // Tags were added via dropping notes from the note list
2088 @SuppressWarnings("unused")
2089 private void tagsAdded(String noteGuid, String tagGuid) {
2090 String tagName = null;
2091 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2092 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2093 tagName = listManager.getTagIndex().get(i).getName();
2094 i=listManager.getTagIndex().size();
2097 if (tagName == null)
2100 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2101 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2102 List<String> tagNames = new ArrayList<String>();
2103 tagNames.add(new String(tagName));
2104 Note n = listManager.getMasterNoteIndex().get(i);
2105 for (int j=0; j<n.getTagNames().size(); j++) {
2106 tagNames.add(new String(n.getTagNames().get(j)));
2108 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2109 if (n.getGuid().equals(currentNoteGuid)) {
2110 Collections.sort(tagNames);
2111 String display = "";
2112 for (int j=0; j<tagNames.size(); j++) {
2113 display = display+tagNames.get(j);
2114 if (j+2<tagNames.size())
2115 display = display+Global.tagDelimeter+" ";
2117 browserWindow.setTag(display);
2119 i=listManager.getMasterNoteIndex().size();
2124 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2126 private void clearTagFilter() {
2127 tagTree.blockSignals(true);
2128 tagTree.clearSelection();
2129 menuBar.noteRestoreAction.setVisible(false);
2130 menuBar.tagEditAction.setEnabled(false);
2131 menuBar.tagDeleteAction.setEnabled(false);
2132 menuBar.tagIconAction.setEnabled(false);
2133 selectedTagGUIDs.clear();
2134 listManager.setSelectedTags(selectedTagGUIDs);
2135 tagTree.blockSignals(false);
2137 // Change the icon for a tag
2138 @SuppressWarnings("unused")
2139 private void setTagIcon() {
2140 QTreeWidgetItem currentSelection;
2141 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2142 if (selections.size() == 0)
2145 currentSelection = selections.get(0);
2146 String guid = currentSelection.text(2);
2148 QIcon currentIcon = currentSelection.icon(0);
2149 QIcon icon = conn.getTagTable().getIcon(guid);
2152 dialog = new SetIcon(currentIcon, saveLastPath);
2153 dialog.setUseDefaultIcon(true);
2155 dialog = new SetIcon(icon, saveLastPath);
2156 dialog.setUseDefaultIcon(false);
2159 if (dialog.okPressed()) {
2160 saveLastPath = dialog.getPath();
2161 QIcon newIcon = dialog.getIcon();
2162 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2163 if (newIcon == null)
2164 newIcon = new QIcon(iconPath+"tag.png");
2165 currentSelection.setIcon(0, newIcon);
2171 //***************************************************************
2172 //***************************************************************
2173 //** These functions deal with Saved Search menu items
2174 //***************************************************************
2175 //***************************************************************
2176 // Add a new notebook
2177 @SuppressWarnings("unused")
2178 private void addSavedSearch() {
2179 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2180 SavedSearchEdit edit = new SavedSearchEdit();
2181 edit.setSearchList(listManager.getSavedSearchIndex());
2184 if (!edit.okPressed())
2187 Calendar currentTime = new GregorianCalendar();
2188 Long l = new Long(currentTime.getTimeInMillis());
2189 String randint = new String(Long.toString(l));
2191 SavedSearch search = new SavedSearch();
2192 search.setUpdateSequenceNum(0);
2193 search.setGuid(randint);
2194 search.setName(edit.getName());
2195 search.setQuery(edit.getQuery());
2196 search.setFormat(QueryFormat.USER);
2197 listManager.getSavedSearchIndex().add(search);
2198 conn.getSavedSearchTable().addSavedSearch(search, true);
2199 savedSearchIndexUpdated();
2200 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2202 // Edit an existing tag
2203 @SuppressWarnings("unused")
2204 private void editSavedSearch() {
2205 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2206 SavedSearchEdit edit = new SavedSearchEdit();
2207 edit.setTitle(tr("Edit Search"));
2208 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2209 QTreeWidgetItem currentSelection;
2210 currentSelection = selections.get(0);
2211 String guid = currentSelection.text(1);
2212 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2213 edit.setName(currentSelection.text(0));
2214 edit.setQuery(s.getQuery());
2215 edit.setSearchList(listManager.getSavedSearchIndex());
2218 if (!edit.okPressed())
2221 List<SavedSearch> list = listManager.getSavedSearchIndex();
2222 SavedSearch search = null;
2223 boolean found = false;
2224 for (int i=0; i<list.size(); i++) {
2225 search = list.get(i);
2226 if (search.getGuid().equals(guid)) {
2233 search.setName(edit.getName());
2234 search.setQuery(edit.getQuery());
2235 conn.getSavedSearchTable().updateSavedSearch(search, true);
2236 savedSearchIndexUpdated();
2237 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2239 // Delete an existing tag
2240 @SuppressWarnings("unused")
2241 private void deleteSavedSearch() {
2242 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2244 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2245 QMessageBox.StandardButton.Yes,
2246 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2250 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2251 for (int i=selections.size()-1; i>=0; i--) {
2252 QTreeWidgetItem currentSelection;
2253 currentSelection = selections.get(i);
2254 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2255 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2256 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2257 listManager.getSavedSearchIndex().remove(j);
2258 j=listManager.getSavedSearchIndex().size()+1;
2261 selections.remove(i);
2263 savedSearchIndexUpdated();
2264 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2266 // Setup the tree containing the user's tags
2267 private void initializeSavedSearchTree() {
2268 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2269 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2270 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2272 // Listener when a tag is selected
2273 @SuppressWarnings("unused")
2274 private void savedSearchTreeSelection() {
2275 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2277 clearNotebookFilter();
2280 clearAttributeFilter();
2282 String currentGuid = selectedSavedSearchGUID;
2283 menuBar.savedSearchEditAction.setEnabled(true);
2284 menuBar.savedSearchDeleteAction.setEnabled(true);
2285 menuBar.savedSearchIconAction.setEnabled(true);
2286 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2287 QTreeWidgetItem currentSelection;
2288 selectedSavedSearchGUID = "";
2289 for (int i=0; i<selections.size(); i++) {
2290 currentSelection = selections.get(i);
2291 if (currentSelection.text(1).equals(currentGuid)) {
2292 currentSelection.setSelected(false);
2294 selectedSavedSearchGUID = currentSelection.text(1);
2296 // i = selections.size() +1;
2299 // There is the potential for no notebooks to be selected if this
2300 // happens then we make it look like all notebooks were selecetd.
2301 // If that happens, just select the "all notebooks"
2302 if (selections.size()==0) {
2303 clearSavedSearchFilter();
2305 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2307 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2309 private void clearSavedSearchFilter() {
2310 menuBar.savedSearchEditAction.setEnabled(false);
2311 menuBar.savedSearchDeleteAction.setEnabled(false);
2312 menuBar.savedSearchIconAction.setEnabled(false);
2313 savedSearchTree.blockSignals(true);
2314 savedSearchTree.clearSelection();
2315 savedSearchTree.blockSignals(false);
2316 selectedSavedSearchGUID = "";
2317 searchField.setEditText("");
2318 searchPerformed = false;
2319 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2321 // trigger the tag index to be refreshed
2322 private void savedSearchIndexUpdated() {
2323 if (selectedSavedSearchGUID == null)
2324 selectedSavedSearchGUID = new String();
2325 savedSearchTree.blockSignals(true);
2326 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2327 savedSearchTree.load(listManager.getSavedSearchIndex());
2328 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2329 savedSearchTree.blockSignals(false);
2331 // trigger when the saved search selection changes
2332 @SuppressWarnings("unused")
2333 private void updateSavedSearchSelection() {
2334 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2336 menuBar.savedSearchEditAction.setEnabled(true);
2337 menuBar.savedSearchDeleteAction.setEnabled(true);
2338 menuBar.savedSearchIconAction.setEnabled(true);
2339 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2341 if (selections.size() > 0) {
2342 menuBar.savedSearchEditAction.setEnabled(true);
2343 menuBar.savedSearchDeleteAction.setEnabled(true);
2344 menuBar.savedSearchIconAction.setEnabled(true);
2345 selectedSavedSearchGUID = selections.get(0).text(1);
2346 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2347 searchField.setEditText(s.getQuery());
2349 menuBar.savedSearchEditAction.setEnabled(false);
2350 menuBar.savedSearchDeleteAction.setEnabled(false);
2351 menuBar.savedSearchIconAction.setEnabled(false);
2352 selectedSavedSearchGUID = "";
2353 searchField.setEditText("");
2355 searchFieldChanged();
2357 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2361 // Show/Hide note information
2362 private void toggleSavedSearchWindow() {
2363 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2364 if (savedSearchTree.isVisible())
2365 savedSearchTree.hide();
2367 savedSearchTree.show();
2368 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2370 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2371 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2373 // Change the icon for a saved search
2374 @SuppressWarnings("unused")
2375 private void setSavedSearchIcon() {
2376 QTreeWidgetItem currentSelection;
2377 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2378 if (selections.size() == 0)
2381 currentSelection = selections.get(0);
2382 String guid = currentSelection.text(1);
2384 QIcon currentIcon = currentSelection.icon(0);
2385 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2388 dialog = new SetIcon(currentIcon, saveLastPath);
2389 dialog.setUseDefaultIcon(true);
2391 dialog = new SetIcon(icon, saveLastPath);
2392 dialog.setUseDefaultIcon(false);
2395 if (dialog.okPressed()) {
2396 saveLastPath = dialog.getPath();
2397 QIcon newIcon = dialog.getIcon();
2398 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2399 if (newIcon == null)
2400 newIcon = new QIcon(iconPath+"search.png");
2401 currentSelection.setIcon(0, newIcon);
2409 //***************************************************************
2410 //***************************************************************
2411 //** These functions deal with Help menu & tool menu items
2412 //***************************************************************
2413 //***************************************************************
2414 // Show database status
2415 @SuppressWarnings("unused")
2416 private void databaseStatus() {
2418 indexRunner.interrupt = true;
2419 int dirty = conn.getNoteTable().getDirtyCount();
2420 int unindexed = conn.getNoteTable().getUnindexedCount();
2421 DatabaseStatus status = new DatabaseStatus();
2422 status.setUnsynchronized(dirty);
2423 status.setUnindexed(unindexed);
2424 status.setNoteCount(conn.getNoteTable().getNoteCount());
2425 status.setNotebookCount(listManager.getNotebookIndex().size());
2426 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2427 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2428 status.setTagCount(listManager.getTagIndex().size());
2429 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2430 status.setWordCount(conn.getWordsTable().getWordCount());
2434 // Compact the database
2435 @SuppressWarnings("unused")
2436 private void compactDatabase() {
2437 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2438 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2439 "but please be aware that depending upon the size of your database this can be time consuming " +
2440 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2441 QMessageBox.StandardButton.Yes,
2442 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2445 setMessage("Compacting database.");
2447 listManager.compactDatabase();
2449 setMessage("Database compact is complete.");
2450 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2452 @SuppressWarnings("unused")
2453 private void accountInformation() {
2454 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2455 AccountDialog dialog = new AccountDialog();
2457 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2459 @SuppressWarnings("unused")
2460 private void releaseNotes() {
2461 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2462 QDialog dialog = new QDialog(this);
2463 QHBoxLayout layout = new QHBoxLayout();
2464 QTextEdit textBox = new QTextEdit();
2465 layout.addWidget(textBox);
2466 textBox.setReadOnly(true);
2467 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2468 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2469 QIODevice.OpenModeFlag.Text)))
2471 textBox.setText(file.readAll().toString());
2473 dialog.setWindowTitle(tr("Release Notes"));
2474 dialog.setLayout(layout);
2476 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2478 // Called when user picks Log from the help menu
2479 @SuppressWarnings("unused")
2480 private void logger() {
2481 logger.log(logger.HIGH, "Entering NeverNote.logger");
2482 QDialog dialog = new QDialog(this);
2483 QHBoxLayout layout = new QHBoxLayout();
2484 QListWidget textBox = new QListWidget();
2485 layout.addWidget(textBox);
2486 textBox.addItems(emitLog);
2488 dialog.setLayout(layout);
2489 dialog.setWindowTitle(tr("Mesasge Log"));
2491 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2493 // Menu option "help/about" was selected
2494 @SuppressWarnings("unused")
2495 private void about() {
2496 logger.log(logger.HIGH, "Entering NeverNote.about");
2497 QMessageBox.about(this,
2498 tr("About NeverNote"),
2499 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2501 +tr("<hr></center>Evernote"
2502 +"An Open Source Evernote Client.<br><br>"
2503 +"Licensed under GPL v2. <br><hr><br>"
2504 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2505 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2506 +"PDFRenderer is licened under the LGPL<br>"
2507 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2508 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2509 +"Jazzy is licened under the LGPL<br>"
2510 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2511 logger.log(logger.HIGH, "Leaving NeverNote.about");
2513 // Hide the entire left hand side
2514 @SuppressWarnings("unused")
2515 private void toggleLeftSide() {
2518 hidden = !menuBar.hideLeftSide.isChecked();
2519 menuBar.hideLeftSide.setChecked(!hidden);
2521 if (notebookTree.isVisible() != hidden)
2522 toggleNotebookWindow();
2523 if (savedSearchTree.isVisible() != hidden)
2524 toggleSavedSearchWindow();
2525 if (tagTree.isVisible() != hidden)
2527 if (attributeTree.isVisible() != hidden)
2528 toggleAttributesWindow();
2529 if (trashTree.isVisible() != hidden)
2530 toggleTrashWindow();
2532 Global.saveWindowVisible("leftPanel", hidden);
2535 public void checkForUpdates() {
2536 // Send off thread to check for a new version
2537 versionChecker = new QNetworkAccessManager(this);
2538 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2539 QNetworkRequest request = new QNetworkRequest();
2540 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2541 versionChecker.get(request);
2543 @SuppressWarnings("unused")
2544 private void upgradeFileRead(QNetworkReply reply) {
2545 if (!reply.isReadable())
2548 String winVersion = Global.version;
2549 String osxVersion = Global.version;
2550 String linuxVersion = Global.version;
2551 String linux64Version = Global.version;
2552 String version = Global.version;
2554 // Determine the versions available
2555 QByteArray data = reply.readLine();
2556 while (data != null && !reply.atEnd()) {
2557 String line = data.toString();
2559 if (line.contains(":"))
2560 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2563 if (line.toLowerCase().contains("windows"))
2564 winVersion = lineVersion;
2565 else if (line.toLowerCase().contains("os-x"))
2566 osxVersion = lineVersion;
2567 else if (line.toLowerCase().contains("linux amd64"))
2568 linux64Version = lineVersion;
2569 else if (line.toLowerCase().contains("linux i386"))
2570 linuxVersion = lineVersion;
2571 else if (line.toLowerCase().contains("default"))
2572 version = lineVersion;
2574 // Read the next line
2575 data = reply.readLine();
2578 // Now we need to determine what system we are on.
2579 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2580 version = winVersion;
2581 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2582 version = osxVersion;
2583 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2584 if (System.getProperty("os.arch").contains("amd64") ||
2585 System.getProperty("os.arch").contains("x86_64"))
2586 version = linux64Version;
2588 version = linuxVersion;
2592 for (String validVersion : Global.validVersions) {
2593 if (version.equals(validVersion))
2597 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2599 if (dialog.remindMe())
2600 Global.setCheckVersionUpgrade(true);
2602 Global.setCheckVersionUpgrade(false);
2606 //***************************************************************
2607 //***************************************************************
2608 //** These functions deal with the Toolbar
2609 //***************************************************************
2610 //***************************************************************
2611 // Text in the search bar has been cleared
2612 private void searchFieldCleared() {
2615 // This is done because we want to force a reload of
2616 // images. Some images we may want to highlight the text.
2617 readOnlyCache.clear();
2618 inkNoteCache.clear();
2620 QWebSettings.setMaximumPagesInCache(0);
2621 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2623 searchField.setEditText("");
2624 saveNoteColumnPositions();
2625 saveNoteIndexWidth();
2626 noteIndexUpdated(true);
2627 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2628 currentNote = listManager.getNoteIndex().get(0);
2629 currentNoteGuid = currentNote.getGuid();
2631 if (currentNote != null)
2632 loadNoteBrowserInformation(browserWindow);
2634 // text in the search bar changed. We only use this to tell if it was cleared,
2635 // otherwise we trigger off searchFieldChanged.
2636 @SuppressWarnings("unused")
2637 private void searchFieldTextChanged(String text) {
2638 QWebSettings.setMaximumPagesInCache(0);
2639 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2641 if (text.trim().equals("")) {
2642 searchFieldCleared();
2643 if (searchPerformed) {
2645 // This is done because we want to force a reload of
2646 // images. Some images we may want to highlight the text.
2648 readOnlyCache.clear();
2649 inkNoteCache.clear();
2651 listManager.setEnSearch("");
2652 listManager.loadNotesIndex();
2653 refreshEvernoteNote(true);
2654 noteIndexUpdated(false);
2656 searchPerformed = false;
2659 // Text in the toolbar has changed
2660 private void searchFieldChanged() {
2661 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2663 readOnlyCache.clear();
2664 inkNoteCache.clear();
2665 saveNoteColumnPositions();
2666 saveNoteIndexWidth();
2667 String text = searchField.currentText();
2668 listManager.setEnSearch(text.trim());
2669 listManager.loadNotesIndex();
2670 //--->>> noteIndexUpdated(true);
2671 noteIndexUpdated(false);
2672 refreshEvernoteNote(true);
2673 searchPerformed = true;
2674 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2677 // Build the window tool bar
2678 private void setupToolBar() {
2679 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2680 toolBar = addToolBar(tr("Tool Bar"));
2681 menuBar.setupToolBarVisible();
2682 if (!Global.isWindowVisible("toolBar"))
2683 toolBar.setVisible(false);
2685 toolBar.setVisible(true);
2687 prevButton = toolBar.addAction("Previous");
2688 QIcon prevIcon = new QIcon(iconPath+"back.png");
2689 prevButton.setIcon(prevIcon);
2690 prevButton.triggered.connect(this, "previousViewedAction()");
2691 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2693 nextButton = toolBar.addAction("Next");
2694 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2695 nextButton.setIcon(nextIcon);
2696 nextButton.triggered.connect(this, "nextViewedAction()");
2697 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2699 upButton = toolBar.addAction("Up");
2700 QIcon upIcon = new QIcon(iconPath+"up.png");
2701 upButton.setIcon(upIcon);
2702 upButton.triggered.connect(this, "upAction()");
2703 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2706 downButton = toolBar.addAction("Down");
2707 QIcon downIcon = new QIcon(iconPath+"down.png");
2708 downButton.setIcon(downIcon);
2709 downButton.triggered.connect(this, "downAction()");
2710 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2712 synchronizeButton = toolBar.addAction("Synchronize");
2713 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2714 synchronizeIconAngle = 0;
2715 synchronizeButton.triggered.connect(this, "evernoteSync()");
2716 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2718 printButton = toolBar.addAction("Print");
2719 QIcon printIcon = new QIcon(iconPath+"print.png");
2720 printButton.setIcon(printIcon);
2721 printButton.triggered.connect(this, "printNote()");
2722 togglePrintButton(Global.isToolbarButtonVisible("print"));
2724 tagButton = toolBar.addAction("Tag");
2725 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2726 tagButton.setIcon(tagIcon);
2727 tagButton.triggered.connect(browserWindow, "modifyTags()");
2728 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2730 attributeButton = toolBar.addAction("Attributes");
2731 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2732 attributeButton.setIcon(attributeIcon);
2733 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2734 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2736 emailButton = toolBar.addAction("Email");
2737 QIcon emailIcon = new QIcon(iconPath+"email.png");
2738 emailButton.setIcon(emailIcon);
2739 emailButton.triggered.connect(this, "emailNote()");
2740 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2742 deleteButton = toolBar.addAction("Delete");
2743 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2744 deleteButton.setIcon(deleteIcon);
2745 deleteButton.triggered.connect(this, "deleteNote()");
2746 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2748 newButton = toolBar.addAction("New");
2749 QIcon newIcon = new QIcon(iconPath+"new.png");
2750 newButton.triggered.connect(this, "addNote()");
2751 newButton.setIcon(newIcon);
2752 toggleNewButton(Global.isToolbarButtonVisible("new"));
2754 allNotesButton = toolBar.addAction("All Notes");
2755 QIcon allIcon = new QIcon(iconPath+"books.png");
2756 allNotesButton.triggered.connect(this, "allNotes()");
2757 allNotesButton.setIcon(allIcon);
2758 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2760 toolBar.addSeparator();
2761 toolBar.addWidget(new QLabel(tr("Quota:")));
2762 toolBar.addWidget(quotaBar);
2763 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2765 toolBar.addSeparator();
2768 zoomSpinner = new QSpinBox();
2769 zoomSpinner.setMinimum(10);
2770 zoomSpinner.setMaximum(1000);
2771 zoomSpinner.setAccelerated(true);
2772 zoomSpinner.setSingleStep(10);
2773 zoomSpinner.setValue(100);
2774 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2775 toolBar.addWidget(new QLabel(tr("Zoom")));
2776 toolBar.addWidget(zoomSpinner);
2778 //toolBar.addWidget(new QLabel(" "));
2779 toolBar.addSeparator();
2780 toolBar.addWidget(new QLabel(tr(" Search:")));
2781 toolBar.addWidget(searchField);
2782 QSizePolicy sizePolicy = new QSizePolicy();
2783 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2784 searchField.setSizePolicy(sizePolicy);
2785 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2787 searchClearButton = toolBar.addAction("Search Clear");
2788 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2789 searchClearButton.setIcon(searchClearIcon);
2790 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2791 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2793 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2795 // Update the sychronize button picture
2797 public QMenu createPopupMenu() {
2798 QMenu contextMenu = super.createPopupMenu();
2800 contextMenu.addSeparator();
2801 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2802 contextMenu.addAction(prevAction);
2803 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2805 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2806 contextMenu.addAction(nextAction);
2807 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2809 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2810 contextMenu.addAction(upAction);
2811 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2813 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2814 contextMenu.addAction(downAction);
2815 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2817 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2818 contextMenu.addAction(synchronizeAction);
2819 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2821 QAction printAction = addContextAction("print", tr("Print"));
2822 contextMenu.addAction(printAction);
2823 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2825 QAction tagAction = addContextAction("tag", tr("Tag"));
2826 contextMenu.addAction(tagAction);
2827 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2829 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2830 contextMenu.addAction(attributeAction);
2831 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2833 QAction emailAction = addContextAction("email", tr("Email"));
2834 contextMenu.addAction(emailAction);
2835 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2837 QAction deleteAction = addContextAction("delete", tr("Delete"));
2838 contextMenu.addAction(deleteAction);
2839 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2841 QAction newAction = addContextAction("new", tr("Add"));
2842 contextMenu.addAction(newAction);
2843 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2845 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2846 contextMenu.addAction(allNotesAction);
2847 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2849 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2850 contextMenu.addAction(searchClearAction);
2851 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2856 private QAction addContextAction(String config, String name) {
2857 QAction newAction = new QAction(this);
2858 newAction.setText(name);
2859 newAction.setCheckable(true);
2860 newAction.setChecked(Global.isToolbarButtonVisible(config));
2863 private void togglePrevArrowButton(Boolean toggle) {
2864 prevButton.setVisible(toggle);
2865 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2867 private void toggleNextArrowButton(Boolean toggle) {
2868 nextButton.setVisible(toggle);
2869 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2871 private void toggleUpArrowButton(Boolean toggle) {
2872 upButton.setVisible(toggle);
2873 Global.saveToolbarButtonsVisible("upArrow", toggle);
2875 private void toggleDownArrowButton(Boolean toggle) {
2876 downButton.setVisible(toggle);
2877 Global.saveToolbarButtonsVisible("downArrow", toggle);
2879 private void toggleSynchronizeButton(Boolean toggle) {
2880 synchronizeButton.setVisible(toggle);
2881 Global.saveToolbarButtonsVisible("synchronize", toggle);
2883 private void togglePrintButton(Boolean toggle) {
2884 printButton.setVisible(toggle);
2885 Global.saveToolbarButtonsVisible("print", toggle);
2887 private void toggleTagButton(Boolean toggle) {
2888 tagButton.setVisible(toggle);
2889 Global.saveToolbarButtonsVisible("tag", toggle);
2891 private void toggleAttributeButton(Boolean toggle) {
2892 attributeButton.setVisible(toggle);
2893 Global.saveToolbarButtonsVisible("attribute", toggle);
2895 private void toggleEmailButton(Boolean toggle) {
2896 emailButton.setVisible(toggle);
2897 Global.saveToolbarButtonsVisible("email", toggle);
2899 private void toggleDeleteButton(Boolean toggle) {
2900 deleteButton.setVisible(toggle);
2901 Global.saveToolbarButtonsVisible("delete", toggle);
2903 private void toggleNewButton(Boolean toggle) {
2904 newButton.setVisible(toggle);
2905 Global.saveToolbarButtonsVisible("new", toggle);
2907 private void toggleAllNotesButton(Boolean toggle) {
2908 allNotesButton.setVisible(toggle);
2909 Global.saveToolbarButtonsVisible("allNotes", toggle);
2911 private void toggleSearchClearButton(Boolean toggle) {
2912 searchClearButton.setVisible(toggle);
2913 Global.saveToolbarButtonsVisible("searchClear", toggle);
2920 @SuppressWarnings("unused")
2921 private void updateSyncButton() {
2923 if (syncIcons == null) {
2924 syncIcons = new ArrayList<QPixmap>();
2926 synchronizeIconAngle = 0;
2927 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2929 for (int i=0; i<=360; i++) {
2930 QPixmap rotatedPix = new QPixmap(pix.size());
2931 QPainter p = new QPainter(rotatedPix);
2932 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2933 QSize size = pix.size();
2934 p.translate(size.width()/2, size.height()/2);
2937 p.setBackgroundMode(BGMode.OpaqueMode);
2938 p.translate(-size.width()/2, -size.height()/2);
2939 p.drawPixmap(0,0, pix);
2941 syncIcons.add(rotatedPix);
2945 synchronizeIconAngle++;
2946 if (synchronizeIconAngle > 359)
2947 synchronizeIconAngle=0;
2948 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2951 // Synchronize with Evernote
2952 @SuppressWarnings("unused")
2953 private void evernoteSync() {
2954 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2955 if (!Global.isConnected)
2957 if (Global.isConnected)
2958 synchronizeAnimationTimer.start(5);
2959 // synchronizeAnimationTimer.start(200);
2961 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2963 private void updateQuotaBar() {
2964 long limit = Global.getUploadLimit();
2965 long amount = Global.getUploadAmount();
2966 if (amount>0 && limit>0) {
2967 int percent =(int)(amount*100/limit);
2968 quotaBar.setValue(percent);
2970 quotaBar.setValue(0);
2973 @SuppressWarnings("unused")
2974 private void zoomChanged() {
2975 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2978 //****************************************************************
2979 //****************************************************************
2980 //* System Tray functions
2981 //****************************************************************
2982 //****************************************************************
2983 private void trayToggleVisible() {
2988 if (windowMaximized)
2995 @SuppressWarnings("unused")
2996 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2997 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2998 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2999 trayToggleVisible();
3004 //***************************************************************
3005 //***************************************************************
3006 //** These functions deal with the trash tree
3007 //***************************************************************
3008 //***************************************************************
3009 // Setup the tree containing the trash.
3010 @SuppressWarnings("unused")
3011 private void trashTreeSelection() {
3012 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3014 clearNotebookFilter();
3016 clearAttributeFilter();
3017 clearSavedSearchFilter();
3019 String tempGuid = currentNoteGuid;
3021 // currentNoteGuid = "";
3022 currentNote = new Note();
3023 selectedNoteGUIDs.clear();
3024 listManager.getSelectedNotebooks().clear();
3025 listManager.getSelectedTags().clear();
3026 listManager.setSelectedSavedSearch("");
3027 browserWindow.clear();
3029 // toggle the add buttons
3030 newButton.setEnabled(!newButton.isEnabled());
3031 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3032 menuBar.noteAdd.setVisible(true);
3034 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3035 if (selections.size() == 0) {
3036 currentNoteGuid = trashNoteGuid;
3037 trashNoteGuid = tempGuid;
3038 Global.showDeleted = false;
3039 menuBar.noteRestoreAction.setEnabled(false);
3040 menuBar.noteRestoreAction.setVisible(false);
3043 currentNoteGuid = trashNoteGuid;
3044 trashNoteGuid = tempGuid;
3045 menuBar.noteRestoreAction.setEnabled(true);
3046 menuBar.noteRestoreAction.setVisible(true);
3047 Global.showDeleted = true;
3049 listManager.loadNotesIndex();
3050 noteIndexUpdated(false);
3051 //// browserWindow.setEnabled(newButton.isEnabled());
3052 browserWindow.setReadOnly(!newButton.isEnabled());
3053 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3055 // Empty the trash file
3056 @SuppressWarnings("unused")
3057 private void emptyTrash() {
3058 // browserWindow.clear();
3059 listManager.emptyTrash();
3060 if (trashTree.selectedItems().size() > 0) {
3061 listManager.getSelectedNotebooks().clear();
3062 listManager.getSelectedTags().clear();
3063 listManager.setSelectedSavedSearch("");
3064 newButton.setEnabled(!newButton.isEnabled());
3065 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3066 menuBar.noteAdd.setVisible(true);
3067 browserWindow.clear();
3070 clearNotebookFilter();
3071 clearSavedSearchFilter();
3072 clearAttributeFilter();
3074 Global.showDeleted = false;
3075 menuBar.noteRestoreAction.setEnabled(false);
3076 menuBar.noteRestoreAction.setVisible(false);
3078 listManager.loadNotesIndex();
3079 //--->>> noteIndexUpdated(true);
3080 noteIndexUpdated(false);
3083 // Show/Hide trash window
3084 private void toggleTrashWindow() {
3085 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3086 if (trashTree.isVisible())
3090 menuBar.hideTrash.setChecked(trashTree.isVisible());
3092 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3093 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3095 private void clearTrashFilter() {
3096 Global.showDeleted = false;
3097 newButton.setEnabled(true);
3098 menuBar.noteAdd.setEnabled(true);
3099 menuBar.noteAdd.setVisible(true);
3100 trashTree.blockSignals(true);
3101 trashTree.clearSelection();
3102 trashTree.blockSignals(false);
3107 //***************************************************************
3108 //***************************************************************
3109 //** These functions deal with connection settings
3110 //***************************************************************
3111 //***************************************************************
3112 // SyncRunner had a problem and things are disconnected
3113 @SuppressWarnings("unused")
3114 private void remoteErrorDisconnect() {
3115 menuBar.connectAction.setText(tr("Connect"));
3116 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3117 menuBar.synchronizeAction.setEnabled(false);
3118 Global.isConnected = false;
3119 synchronizeAnimationTimer.stop();
3122 // Do a manual connect/disconnect
3123 private void remoteConnect() {
3124 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3126 if (Global.isConnected) {
3127 Global.isConnected = false;
3128 syncRunner.enDisconnect();
3129 setupConnectMenuOptions();
3134 AESEncrypter aes = new AESEncrypter();
3136 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3137 } catch (FileNotFoundException e) {
3138 // File not found, so we'll just get empty strings anyway.
3140 String userid = aes.getUserid();
3141 String password = aes.getPassword();
3142 if (!userid.equals("") && !password.equals("")) {
3143 Global.username = userid;
3144 Global.password = password;
3147 // Show the login dialog box
3148 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3149 LoginDialog login = new LoginDialog();
3152 if (!login.okPressed()) {
3156 Global.username = login.getUserid();
3157 Global.password = login.getPassword();
3159 syncRunner.username = Global.username;
3160 syncRunner.password = Global.password;
3161 syncRunner.userStoreUrl = Global.userStoreUrl;
3162 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3163 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3165 if (Global.getProxyValue("url").equals("")) {
3166 System.setProperty("http.proxyHost","") ;
3167 System.setProperty("http.proxyPort", "") ;
3168 System.setProperty("https.proxyHost","") ;
3169 System.setProperty("https.proxyPort", "") ;
3172 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3173 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3174 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3175 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3177 if (Global.getProxyValue("userid").equals("")) {
3178 Authenticator.setDefault(new Authenticator() {
3180 protected PasswordAuthentication getPasswordAuthentication() {
3182 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3188 syncRunner.enConnect();
3189 Global.isConnected = syncRunner.isConnected;
3191 setupConnectMenuOptions();
3192 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3194 private void setupConnectMenuOptions() {
3195 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3196 if (!Global.isConnected) {
3197 menuBar.connectAction.setText(tr("Connect"));
3198 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3199 menuBar.synchronizeAction.setEnabled(false);
3201 menuBar.connectAction.setText(tr("Disconnect"));
3202 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3203 menuBar.synchronizeAction.setEnabled(true);
3205 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3210 //***************************************************************
3211 //***************************************************************
3212 //** These functions deal with the GUI Attribute tree
3213 //***************************************************************
3214 //***************************************************************
3215 @SuppressWarnings("unused")
3216 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3218 // clearTagFilter();
3219 // clearNotebookFilter();
3221 // clearSavedSearchFilter();
3223 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3224 if (item.childCount() > 0) {
3225 item.setSelected(false);
3227 Global.createdBeforeFilter.reset();
3228 Global.createdSinceFilter.reset();
3229 Global.changedBeforeFilter.reset();
3230 Global.changedSinceFilter.reset();
3231 Global.containsFilter.reset();
3232 attributeTreeSelected = item;
3233 DateAttributeFilterTable f = null;
3234 f = findDateAttributeFilterTable(item.parent());
3236 f.select(item.parent().indexOfChild(item));
3238 Global.containsFilter.select(item.parent().indexOfChild(item));
3241 listManager.loadNotesIndex();
3242 noteIndexUpdated(false);
3245 attributeTreeSelected = null;
3246 item.setSelected(false);
3247 Global.createdBeforeFilter.reset();
3248 Global.createdSinceFilter.reset();
3249 Global.changedBeforeFilter.reset();
3250 Global.changedSinceFilter.reset();
3251 Global.containsFilter.reset();
3252 listManager.loadNotesIndex();
3253 noteIndexUpdated(false);
3255 // This determines what attribute filter we need, depending upon the selection
3256 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3257 if (w.parent() != null && w.childCount() > 0) {
3258 QTreeWidgetItem parent = w.parent();
3259 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3260 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3261 return Global.createdSinceFilter;
3262 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3263 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3264 return Global.createdBeforeFilter;
3265 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3266 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3267 return Global.changedSinceFilter;
3268 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3269 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3270 return Global.changedBeforeFilter;
3275 // Show/Hide attribute search window
3276 private void toggleAttributesWindow() {
3277 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3278 if (attributeTree.isVisible())
3279 attributeTree.hide();
3281 attributeTree.show();
3282 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3284 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3285 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3287 private void clearAttributeFilter() {
3288 Global.createdBeforeFilter.reset();
3289 Global.createdSinceFilter.reset();
3290 Global.changedBeforeFilter.reset();
3291 Global.changedSinceFilter.reset();
3292 Global.containsFilter.reset();
3293 attributeTreeSelected = null;
3294 attributeTree.blockSignals(true);
3295 attributeTree.clearSelection();
3296 attributeTree.blockSignals(false);
3300 //***************************************************************
3301 //***************************************************************
3302 //** These functions deal with the GUI Note index table
3303 //***************************************************************
3304 //***************************************************************
3305 // Initialize the note list table
3306 private void initializeNoteTable() {
3307 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3308 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3309 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3310 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3312 // Show/Hide trash window
3313 @SuppressWarnings("unused")
3314 private void toggleNoteListWindow() {
3315 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3316 if (noteTableView.isVisible())
3317 noteTableView.hide();
3319 noteTableView.show();
3320 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3322 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3323 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3325 // Handle the event that a user selects a note from the table
3326 @SuppressWarnings("unused")
3327 private void noteTableSelection() {
3328 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3330 if (historyGuids.size() == 0) {
3331 historyGuids.add(currentNoteGuid);
3332 historyPosition = 1;
3334 noteTableView.showColumn(Global.noteTableGuidPosition);
3336 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3337 if (!Global.isColumnVisible("guid"))
3338 noteTableView.hideColumn(Global.noteTableGuidPosition);
3340 if (selections.size() > 0) {
3342 menuBar.noteDuplicateAction.setEnabled(true);
3343 menuBar.noteOnlineHistoryAction.setEnabled(true);
3344 menuBar.noteMergeAction.setEnabled(true);
3345 selectedNoteGUIDs.clear();
3346 if (selections.size() != 1 || Global.showDeleted) {
3347 menuBar.noteDuplicateAction.setEnabled(false);
3349 if (selections.size() != 1 || !Global.isConnected) {
3350 menuBar.noteOnlineHistoryAction.setEnabled(false);
3352 if (selections.size() == 1) {
3353 menuBar.noteMergeAction.setEnabled(false);
3355 for (int i=0; i<selections.size(); i++) {
3356 int row = selections.get(i).row();
3358 upButton.setEnabled(false);
3360 upButton.setEnabled(true);
3361 if (row < listManager.getNoteTableModel().rowCount()-1)
3362 downButton.setEnabled(true);
3364 downButton.setEnabled(false);
3365 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3366 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3367 currentNoteGuid = (String)ix.values().toArray()[0];
3368 selectedNoteGUIDs.add(currentNoteGuid);
3372 nextButton.setEnabled(true);
3373 prevButton.setEnabled(true);
3375 int endPosition = historyGuids.size()-1;
3376 for (int j=historyPosition; j<=endPosition; j++) {
3377 historyGuids.remove(historyGuids.size()-1);
3379 historyGuids.add(currentNoteGuid);
3380 historyPosition = historyGuids.size();
3382 if (historyPosition <= 1)
3383 prevButton.setEnabled(false);
3384 if (historyPosition == historyGuids.size())
3385 nextButton.setEnabled(false);
3387 fromHistory = false;
3388 scrollToGuid(currentNoteGuid);
3389 refreshEvernoteNote(true);
3390 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3392 // Trigger a refresh when the note db has been updated
3393 private void noteIndexUpdated(boolean reload) {
3394 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3396 refreshEvernoteNoteList();
3397 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3398 noteTableView.load(reload);
3399 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3401 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3402 pos = noteTableView.proxyModel.rowCount();
3405 if (noteTableView.proxyModel.rowCount() == 0)
3408 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3410 currentNoteGuid = (String)i.data();
3411 noteTableView.selectRow(pos-1);
3416 scrollToGuid(currentNoteGuid);
3417 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3419 // Called when the list of notes is updated
3420 private void refreshEvernoteNoteList() {
3421 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3422 browserWindow.setDisabled(false);
3423 if (selectedNoteGUIDs == null)
3424 selectedNoteGUIDs = new ArrayList<String>();
3425 selectedNoteGUIDs.clear(); // clear out old entries
3427 String saveCurrentNoteGuid = new String();
3428 String tempNoteGuid = new String();
3430 historyGuids.clear();
3431 historyPosition = 0;
3432 prevButton.setEnabled(false);
3433 nextButton.setEnabled(false);
3435 if (currentNoteGuid == null)
3436 currentNoteGuid = new String();
3438 //determine current note guid
3439 for (Note note : listManager.getNoteIndex()) {
3440 tempNoteGuid = note.getGuid();
3441 if (currentNoteGuid.equals(tempNoteGuid)) {
3442 saveCurrentNoteGuid = tempNoteGuid;
3446 if (listManager.getNoteIndex().size() == 0) {
3447 currentNoteGuid = "";
3449 browserWindow.clear();
3450 browserWindow.setDisabled(true);
3453 if (!saveCurrentNoteGuid.equals("")) {
3454 refreshEvernoteNote(false);
3456 currentNoteGuid = "";
3458 reloadTagTree(false);
3460 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3462 // Called when the previous arrow button is clicked
3463 @SuppressWarnings("unused")
3464 private void previousViewedAction() {
3465 if (!prevButton.isEnabled())
3467 if (historyPosition == 0)
3470 if (historyPosition <= 0)
3472 String historyGuid = historyGuids.get(historyPosition-1);
3474 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3475 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3476 if (modelIndex != null) {
3477 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3478 String tableGuid = (String)ix.values().toArray()[0];
3479 if (tableGuid.equals(historyGuid)) {
3480 noteTableView.selectRow(i);
3486 @SuppressWarnings("unused")
3487 private void nextViewedAction() {
3488 if (!nextButton.isEnabled())
3490 String historyGuid = historyGuids.get(historyPosition);
3493 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3494 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3495 if (modelIndex != null) {
3496 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3497 String tableGuid = (String)ix.values().toArray()[0];
3498 if (tableGuid.equals(historyGuid)) {
3499 noteTableView.selectRow(i);
3505 // Called when the up arrow is clicked
3506 @SuppressWarnings("unused")
3507 private void upAction() {
3508 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3509 int row = selections.get(0).row();
3511 noteTableView.selectRow(row-1);
3514 // Called when the down arrow is clicked
3515 @SuppressWarnings("unused")
3516 private void downAction() {
3517 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3518 int row = selections.get(0).row();
3519 int max = listManager.getNoteTableModel().rowCount();
3521 noteTableView.selectRow(row+1);
3524 // Update a tag string for a specific note in the list
3525 @SuppressWarnings("unused")
3526 private void updateListTags(String guid, List<String> tags) {
3527 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3528 StringBuffer tagBuffer = new StringBuffer();
3529 for (int i=0; i<tags.size(); i++) {
3530 tagBuffer.append(tags.get(i));
3531 if (i<tags.size()-1)
3532 tagBuffer.append(", ");
3535 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3536 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3537 if (modelIndex != null) {
3538 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3539 String tableGuid = (String)ix.values().toArray()[0];
3540 if (tableGuid.equals(guid)) {
3541 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3542 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3543 noteTableView.proxyModel.invalidate();
3548 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3550 // Update a title for a specific note in the list
3551 @SuppressWarnings("unused")
3552 private void updateListAuthor(String guid, String author) {
3553 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3555 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3556 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3557 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3558 if (modelIndex != null) {
3559 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3560 String tableGuid = (String)ix.values().toArray()[0];
3561 if (tableGuid.equals(guid)) {
3562 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3563 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3564 noteTableView.proxyModel.invalidate();
3570 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3572 private void updateListNoteNotebook(String guid, String notebook) {
3573 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3574 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3575 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3577 // Update a title for a specific note in the list
3578 @SuppressWarnings("unused")
3579 private void updateListSourceUrl(String guid, String url) {
3580 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3582 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3583 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3584 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3585 if (modelIndex != null) {
3586 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
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.noteTableSynchronizedPosition, "false");
3591 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3592 noteTableView.proxyModel.invalidate();
3597 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3599 @SuppressWarnings("unused")
3600 private void updateListGuid(String oldGuid, String newGuid) {
3601 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3603 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3604 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3605 if (modelIndex != null) {
3606 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3607 String tableGuid = (String)ix.values().toArray()[0];
3608 if (tableGuid.equals(oldGuid)) {
3609 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3610 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3615 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3617 private void updateListTagName(String guid) {
3618 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3620 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3621 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3622 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3624 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3625 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3626 if (modelIndex != null) {
3627 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3628 String noteGuid = (String)ix.values().toArray()[0];
3629 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3630 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3631 i=listManager.getNoteTableModel().rowCount();
3637 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3639 private void removeListTagName(String guid) {
3640 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3642 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3643 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3644 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3645 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3646 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3649 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3650 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3651 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3652 if (modelIndex != null) {
3653 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3654 String noteGuid = (String)ix.values().toArray()[0];
3655 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3656 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3657 i=listManager.getNoteTableModel().rowCount();
3663 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3665 private void updateListNotebookName(String oldName, String newName) {
3666 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3668 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3669 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3670 if (modelIndex != null) {
3671 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3672 String tableName = (String)ix.values().toArray()[0];
3673 if (tableName.equalsIgnoreCase(oldName)) {
3674 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3678 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3680 @SuppressWarnings("unused")
3681 private void updateListDateCreated(String guid, QDateTime date) {
3682 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3684 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3685 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3686 if (modelIndex != null) {
3687 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3688 String tableGuid = (String)ix.values().toArray()[0];
3689 if (tableGuid.equals(guid)) {
3690 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3691 noteTableView.proxyModel.invalidate();
3696 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3698 @SuppressWarnings("unused")
3699 private void updateListDateSubject(String guid, QDateTime date) {
3700 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3702 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3703 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3704 if (modelIndex != null) {
3705 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3706 String tableGuid = (String)ix.values().toArray()[0];
3707 if (tableGuid.equals(guid)) {
3708 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3709 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3710 noteTableView.proxyModel.invalidate();
3715 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3717 private void updateListDateChanged(String guid, QDateTime date) {
3718 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3720 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3721 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3722 if (modelIndex != null) {
3723 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3724 String tableGuid = (String)ix.values().toArray()[0];
3725 if (tableGuid.equals(guid)) {
3726 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3727 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3732 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3734 private void updateListDateChanged() {
3735 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3736 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3737 updateListDateChanged(currentNoteGuid, date);
3738 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3741 private void scrollToCurrentGuid() {
3742 //scrollToGuid(currentNoteGuid);
3743 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3744 if (selections.size() == 0)
3746 QModelIndex index = selections.get(0);
3747 int row = selections.get(0).row();
3748 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3751 // Scroll to a particular index item
3752 private void scrollToGuid(String guid) {
3753 if (currentNote == null || guid == null)
3755 if (currentNote.isActive() && Global.showDeleted) {
3756 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3757 if (!listManager.getNoteIndex().get(i).isActive()) {
3758 currentNote = listManager.getNoteIndex().get(i);
3759 currentNoteGuid = currentNote.getGuid();
3760 i = listManager.getNoteIndex().size();
3765 if (!currentNote.isActive() && !Global.showDeleted) {
3766 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3767 if (listManager.getNoteIndex().get(i).isActive()) {
3768 currentNote = listManager.getNoteIndex().get(i);
3769 currentNoteGuid = currentNote.getGuid();
3770 i = listManager.getNoteIndex().size();
3776 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3777 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3778 if (currentNoteGuid.equals(index.data())) {
3779 // noteTableView.setCurrentIndex(index);
3780 noteTableView.selectRow(i);
3781 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3782 i=listManager.getNoteTableModel().rowCount();
3785 noteTableView.repaint();
3787 // Show/Hide columns
3788 private void showColumns() {
3789 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3790 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3791 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3792 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3793 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3794 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3795 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3796 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3797 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3798 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3799 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3801 // Title color has changed
3802 @SuppressWarnings("unused")
3803 private void titleColorChanged(Integer color) {
3804 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3806 QColor backgroundColor = new QColor();
3807 QColor foregroundColor = new QColor(QColor.black);
3808 backgroundColor.setRgb(color);
3810 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3811 foregroundColor.setRgb(QColor.white.rgb());
3813 if (selectedNoteGUIDs.size() == 0)
3814 selectedNoteGUIDs.add(currentNoteGuid);
3816 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3817 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3818 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3819 if (modelIndex != null) {
3820 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3821 String tableGuid = (String)ix.values().toArray()[0];
3822 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3823 for (int k=0; k<Global.noteTableColumnCount; k++) {
3824 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3825 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3826 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3828 i=listManager.getNoteTableModel().rowCount();
3833 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3835 // Wide list was chosen
3836 public void narrowListView() {
3837 saveNoteColumnPositions();
3838 saveNoteIndexWidth();
3840 int sortCol = noteTableView.proxyModel.sortColumn();
3841 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3842 Global.setSortColumn(sortCol);
3843 Global.setSortOrder(sortOrder);
3845 Global.setListView(Global.View_List_Narrow);
3847 menuBar.wideListView.blockSignals(true);
3848 menuBar.narrowListView.blockSignals(true);
3850 menuBar.wideListView.setChecked(false);
3851 menuBar.narrowListView.setChecked(true);
3853 menuBar.wideListView.blockSignals(false);
3854 menuBar.narrowListView.blockSignals(false);
3856 mainLeftRightSplitter.addWidget(noteTableView);
3857 mainLeftRightSplitter.addWidget(browserWindow);
3858 restoreWindowState(false);
3859 noteTableView.repositionColumns();
3860 noteTableView.resizeColumnWidths();
3861 noteTableView.resizeRowHeights();
3863 sortCol = Global.getSortColumn();
3864 sortOrder = Global.getSortOrder();
3865 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3868 noteTableView.load(false);
3869 scrollToCurrentGuid();
3871 public void wideListView() {
3872 int sortCol = noteTableView.proxyModel.sortColumn();
3873 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3874 Global.setSortColumn(sortCol);
3875 Global.setSortOrder(sortOrder);
3878 saveNoteColumnPositions();
3879 saveNoteIndexWidth();
3880 Global.setListView(Global.View_List_Wide);
3882 menuBar.wideListView.blockSignals(true);
3883 menuBar.narrowListView.blockSignals(true);
3885 menuBar.wideListView.setChecked(true);
3886 menuBar.narrowListView.setChecked(false);
3888 menuBar.wideListView.blockSignals(false);
3889 menuBar.narrowListView.blockSignals(false);
3890 browserIndexSplitter.setVisible(true);
3891 browserIndexSplitter.addWidget(noteTableView);
3892 browserIndexSplitter.addWidget(browserWindow);
3893 restoreWindowState(false);
3894 noteTableView.repositionColumns();
3895 noteTableView.resizeColumnWidths();
3896 noteTableView.resizeRowHeights();
3898 sortCol = Global.getSortColumn();
3899 sortOrder = Global.getSortOrder();
3900 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3903 noteTableView.load(false);
3904 scrollToCurrentGuid();
3908 //***************************************************************
3909 //***************************************************************
3910 //** External editor window functions
3911 //***************************************************************
3912 //***************************************************************
3913 private void listDoubleClick() {
3915 if (externalWindows.containsKey(currentNoteGuid)) {
3916 externalWindows.get(currentNoteGuid).raise();
3919 // We have a new external editor to create
3920 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3921 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3922 newBrowser.setWindowIcon(appIcon);
3923 externalWindows.put(currentNoteGuid, newBrowser);
3924 showEditorButtons(newBrowser.getBrowserWindow());
3925 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3926 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3927 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3928 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3929 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3930 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3932 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3933 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3934 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3938 @SuppressWarnings("unused")
3939 private void externalWindowTitleEdited(String guid, String text) {
3940 if (guid.equals(currentNoteGuid)) {
3941 browserWindow.setTitle(text);
3944 @SuppressWarnings({ "rawtypes", "unused" })
3945 private void externalWindowTagsEdited(String guid, List values) {
3946 StringBuffer line = new StringBuffer(100);
3947 for (int i=0; i<values.size(); i++) {
3949 line.append(Global.tagDelimeter+" ");
3950 line.append(values.get(i));
3952 if (guid.equals(currentNoteGuid)) {
3953 browserWindow.setTag(line.toString());
3956 @SuppressWarnings("unused")
3957 private void externalWindowClosing(String guid) {
3958 externalWindows.remove(guid);
3963 //***************************************************************
3964 //***************************************************************
3965 //** These functions deal with Note specific things
3966 //***************************************************************
3967 //***************************************************************
3968 @SuppressWarnings("unused")
3969 private void setNoteDirty() {
3970 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
3972 // Find if the note is being edited externally. If it is, update it.
3973 if (externalWindows.containsKey(currentNoteGuid)) {
3974 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3975 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
3976 ExternalBrowse window = externalWindows.get(currentNoteGuid);
3977 window.getBrowserWindow().getBrowser().setContent(unicode);
3980 // If the note is dirty, then it is unsynchronized by default.
3984 // Set the note as dirty and check if its status is synchronized in the display table
3986 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
3987 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
3991 // If this wasn't already marked as unsynchronized, then we need to update the table
3992 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
3993 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
3994 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3995 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3996 if (modelIndex != null) {
3997 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3998 String tableGuid = (String)ix.values().toArray()[0];
3999 if (tableGuid.equals(currentNoteGuid)) {
4000 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4006 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4008 @SuppressWarnings("unused")
4009 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4010 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4011 QByteArray unicode = codec.fromUnicode(content);
4012 noteCache.remove(guid);
4013 noteCache.put(guid, unicode.toString());
4014 if (guid.equals(currentNoteGuid)) {
4016 browserWindow.getBrowser().setContent(unicode);
4019 thumbnailRunner.addWork("GENERATE "+ guid);
4020 saveNote(guid, browser);
4024 private void saveNote() {
4026 saveNote(currentNoteGuid, browserWindow);
4027 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4031 private void saveNote(String guid, BrowserWindow window) {
4032 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4033 logger.log(logger.EXTREME, "Note is dirty.");
4036 logger.log(logger.EXTREME, "Saving to cache");
4037 QTextCodec codec = QTextCodec.codecForLocale();
4038 // QTextDecoder decoder = codec.makeDecoder();
4039 codec = QTextCodec.codecForName("UTF-8");
4040 QByteArray unicode = codec.fromUnicode(window.getContent());
4041 noteCache.put(guid, unicode.toString());
4043 logger.log(logger.EXTREME, "updating list manager");
4044 listManager.updateNoteContent(guid, window.getContent());
4045 logger.log(logger.EXTREME, "Updating title");
4046 listManager.updateNoteTitle(guid, window.getTitle());
4047 updateListDateChanged();
4049 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4050 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4051 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4052 currentNote = listManager.getNoteIndex().get(i);
4053 i = listManager.getNoteIndex().size();
4058 // Get a note from Evernote (and put it in the browser)
4059 private void refreshEvernoteNote(boolean reload) {
4060 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4062 if (Global.disableViewing) {
4063 browserWindow.setEnabled(false);
4068 if (Global.showDeleted)
4070 Global.cryptCounter =0;
4071 if (currentNoteGuid.equals("")) {
4072 browserWindow.setReadOnly(true);
4080 browserWindow.loadingData(true);
4082 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4083 if (currentNote == null)
4086 loadNoteBrowserInformation(browserWindow);
4089 private void loadNoteBrowserInformation(BrowserWindow browser) {
4090 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4091 formatter.setNote(currentNote, Global.pdfPreview());
4092 formatter.setHighlight(listManager.getEnSearch());
4094 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4095 js = new QByteArray();
4096 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4097 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4098 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>");
4099 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4100 js.append("<style> img { max-width:100%; }</style>");
4101 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4102 js.append("</head>");
4103 formatter.setNote(currentNote, Global.pdfPreview());
4104 js.append(formatter.rebuildNoteHTML());
4105 js.append("</HTML>");
4106 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4107 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4108 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4109 browser.getBrowser().setContent(js);
4110 noteCache.put(currentNoteGuid, js.toString());
4112 if (formatter.resourceError)
4113 resourceErrorMessage();
4114 readOnly = formatter.readOnly;
4115 inkNote = formatter.inkNote;
4117 readOnlyCache.put(currentNoteGuid, true);
4119 inkNoteCache.put(currentNoteGuid, true);
4121 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4122 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4123 js = new QByteArray(cachedContent);
4124 browser.getBrowser().setContent(js);
4125 if (readOnlyCache.containsKey(currentNoteGuid))
4127 if (inkNoteCache.containsKey(currentNoteGuid))
4130 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4131 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4134 if (readOnly || inkNote)
4135 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4137 browser.getBrowser().page().setContentEditable(true);
4138 browser.setReadOnly(readOnly);
4139 deleteButton.setEnabled(!readOnly);
4140 tagButton.setEnabled(!readOnly);
4141 menuBar.noteDelete.setEnabled(!readOnly);
4142 menuBar.noteTags.setEnabled(!readOnly);
4143 browser.setNote(currentNote);
4145 if (conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4146 deleteButton.setEnabled(false);
4147 menuBar.notebookDeleteAction.setEnabled(false);
4149 deleteButton.setEnabled(true);
4150 menuBar.notebookDeleteAction.setEnabled(true);
4153 // Build a list of non-closed notebooks
4154 List<Notebook> nbooks = new ArrayList<Notebook>();
4155 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4156 boolean found=false;
4157 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4158 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4162 nbooks.add(listManager.getNotebookIndex().get(i));
4165 browser.setTitle(currentNote.getTitle());
4166 browser.setTag(getTagNamesForNote(currentNote));
4167 browser.setAuthor(currentNote.getAttributes().getAuthor());
4169 browser.setAltered(currentNote.getUpdated());
4170 browser.setCreation(currentNote.getCreated());
4171 if (currentNote.getAttributes().getSubjectDate() > 0)
4172 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4174 browser.setSubjectDate(currentNote.getCreated());
4175 browser.setUrl(currentNote.getAttributes().getSourceURL());
4177 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4178 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4179 browser.setAllTags(tagList);
4181 browser.setCurrentTags(currentNote.getTagNames());
4183 scrollToGuid(currentNoteGuid);
4185 browser.loadingData(false);
4186 if (thumbnailViewer.isActiveWindow())
4189 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4190 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4193 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4195 // Save a generated thumbnail
4196 private void toggleNoteInformation() {
4197 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4198 browserWindow.toggleInformation();
4199 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4200 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4201 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4203 // Listener triggered when a print button is pressed
4204 @SuppressWarnings("unused")
4205 private void printNote() {
4206 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4208 QPrintDialog dialog = new QPrintDialog();
4209 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4210 QPrinter printer = dialog.printer();
4211 browserWindow.getBrowser().print(printer);
4213 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4216 // Listener triggered when the email button is pressed
4217 @SuppressWarnings("unused")
4218 private void emailNote() {
4219 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4221 if (Desktop.isDesktopSupported()) {
4222 Desktop desktop = Desktop.getDesktop();
4224 String text2 = browserWindow.getContentsToEmail();
4225 QUrl url = new QUrl("mailto:");
4226 url.addQueryItem("subject", currentNote.getTitle());
4227 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4228 url.addQueryItem("body", text2);
4229 QDesktopServices.openUrl(url);
4233 if (desktop.isSupported(Desktop.Action.MAIL)) {
4234 URI uriMailTo = null;
4236 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4237 String text = browserWindow.getContentsToEmail();
4238 //text = "<b>" +text +"</b>";
4239 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4240 +"&BODY=" +text, null);
4241 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4242 +"&ATTACHMENT=d:/test.pdf", null);
4243 desktop.mail(uriMailTo);
4244 } catch (URISyntaxException e) {
4245 e.printStackTrace();
4246 } catch (IOException e) {
4247 e.printStackTrace();
4254 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4256 // Reindex all notes
4257 @SuppressWarnings("unused")
4258 private void fullReindex() {
4259 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4260 indexRunner.addWork("REINDEXALL");
4261 setMessage(tr("Database will be reindexed."));
4262 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4264 // Listener when a user wants to reindex a specific note
4265 @SuppressWarnings("unused")
4266 private void reindexNote() {
4267 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4268 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4269 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4271 if (selectedNotebookGUIDs.size() > 1)
4272 setMessage(tr("Notes will be reindexed."));
4274 setMessage(tr("Note will be reindexed."));
4275 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4278 @SuppressWarnings("unused")
4279 private void deleteNote() {
4280 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4281 if (currentNote == null)
4283 if (currentNoteGuid.equals(""))
4286 // If we are deleting non-trash notes
4287 if (currentNote.isActive()) {
4288 if (Global.verifyDelete()) {
4289 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4290 QMessageBox.StandardButton.Yes,
4291 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4295 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4296 selectedNoteGUIDs.add(currentNoteGuid);
4297 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4298 listManager.deleteNote(selectedNoteGUIDs.get(i));
4301 // If we are deleting from the trash.
4302 if (Global.verifyDelete()) {
4303 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4304 QMessageBox.StandardButton.Yes,
4305 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4309 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4310 selectedNoteGUIDs.add(currentNoteGuid);
4311 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4312 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4313 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4314 if (modelIndex != null) {
4315 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4316 String tableGuid = (String)ix.values().toArray()[0];
4317 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4318 listManager.getNoteTableModel().removeRow(j);
4323 listManager.expungeNote(selectedNoteGUIDs.get(i));
4326 currentNoteGuid = "";
4327 listManager.loadNotesIndex();
4328 noteIndexUpdated(false);
4329 refreshEvernoteNote(true);
4330 scrollToGuid(currentNoteGuid);
4331 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4334 @SuppressWarnings("unused")
4335 private void addNote() {
4336 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4337 // browserWindow.setEnabled(true);
4338 browserWindow.setReadOnly(false);
4340 Calendar currentTime = new GregorianCalendar();
4341 StringBuffer noteString = new StringBuffer(100);
4342 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4343 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4346 if (Global.overrideDefaultFont()) {
4347 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4348 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4349 noteString.append("<br clear=\"none\" />\n");
4350 noteString.append("</span>\n</font>\n");
4352 noteString.append("<br clear=\"none\" />\n");
4353 noteString.append("</en-note>");
4355 Long l = new Long(currentTime.getTimeInMillis());
4356 String randint = new String(Long.toString(l));
4358 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4360 // for the first non-archived notebook. Finally, if nothing else we
4361 // pick the first notebook in the list.
4362 String notebook = null;
4363 listManager.getNotebookIndex().get(0).getGuid();
4364 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4365 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4366 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4367 notebook = currentSelectedNotebook.text(2);
4369 boolean found = false;
4370 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4371 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4372 boolean match = false;
4373 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4374 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4376 j = listManager.getArchiveNotebookIndex().size();
4380 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4382 // Now we have a list of good notebooks, so we can look for the default
4384 for (int i=0; i<goodNotebooks.size(); i++) {
4385 if (goodNotebooks.get(i).isDefaultNotebook()) {
4386 notebook = goodNotebooks.get(i).getGuid();
4388 i = goodNotebooks.size();
4392 if (goodNotebooks.size() > 0 && !found)
4393 notebook = goodNotebooks.get(0).getGuid();
4396 notebook = listManager.getNotebookIndex().get(0).getGuid();
4399 Note newNote = new Note();
4400 newNote.setUpdateSequenceNum(0);
4401 newNote.setGuid(randint);
4402 newNote.setNotebookGuid(notebook);
4403 newNote.setTitle("");
4404 newNote.setContent(noteString.toString());
4405 newNote.setDeleted(0);
4406 newNote.setCreated(System.currentTimeMillis());
4407 newNote.setUpdated(System.currentTimeMillis());
4408 newNote.setActive(true);
4409 NoteAttributes na = new NoteAttributes();
4410 na.setLatitude(0.0);
4411 na.setLongitude(0.0);
4412 na.setAltitude(0.0);
4413 newNote.setAttributes(new NoteAttributes());
4414 newNote.setTagGuids(new ArrayList<String>());
4415 newNote.setTagNames(new ArrayList<String>());
4417 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4418 if (Global.newNoteWithSelectedTags()) {
4419 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4420 QTreeWidgetItem currentSelection;
4421 for (int i=0; i<selections.size(); i++) {
4422 currentSelection = selections.get(i);
4423 newNote.getTagGuids().add(currentSelection.text(2));
4424 newNote.getTagNames().add(currentSelection.text(0));
4428 conn.getNoteTable().addNote(newNote, true);
4429 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4430 listManager.addNote(newNote);
4431 // noteTableView.insertRow(newNote, true, -1);
4433 currentNote = newNote;
4434 currentNoteGuid = currentNote.getGuid();
4435 refreshEvernoteNote(true);
4436 listManager.countNotebookResults(listManager.getNoteIndex());
4437 browserWindow.titleLabel.setFocus();
4438 browserWindow.titleLabel.selectAll();
4439 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4441 // If the window is hidden, then we want to popup this in an external window &
4444 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4446 // Restore a note from the trash;
4447 @SuppressWarnings("unused")
4448 private void restoreNote() {
4450 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4451 selectedNoteGUIDs.add(currentNoteGuid);
4452 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4453 listManager.restoreNote(selectedNoteGUIDs.get(i));
4455 currentNoteGuid = "";
4456 listManager.loadNotesIndex();
4457 noteIndexUpdated(false);
4460 // Search a note for specific txt
4461 @SuppressWarnings("unused")
4462 private void findText() {
4464 find.setFocusOnTextField();
4466 @SuppressWarnings("unused")
4467 private void doFindText() {
4468 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4471 @SuppressWarnings("unused")
4472 private void updateNoteTitle(String guid, String title) {
4473 listManager.setNoteSynchronized(guid, false);
4475 // Signal received that note content has changed. Normally we just need the guid to remove
4476 // it from the cache.
4477 @SuppressWarnings("unused")
4478 private void invalidateNoteCache(String guid, String content) {
4479 String v = noteCache.remove(guid);
4480 // if (guid.equals(currentNoteGuid) && !noteDirty)
4481 refreshEvernoteNote(true);
4483 // Signal received that a note guid has changed
4484 @SuppressWarnings("unused")
4485 private void noteGuidChanged(String oldGuid, String newGuid) {
4486 if (noteCache.containsKey(oldGuid)) {
4487 if (!oldGuid.equals(currentNoteGuid)) {
4488 String cache = noteCache.get(oldGuid);
4489 noteCache.put(newGuid, cache);
4490 noteCache.remove(oldGuid);
4492 noteCache.remove(oldGuid);
4493 noteCache.put(newGuid, browserWindow.getContent());
4497 listManager.updateNoteGuid(oldGuid, newGuid, false);
4498 if (currentNoteGuid.equals(oldGuid)) {
4499 if (currentNote != null)
4500 currentNote.setGuid(newGuid);
4501 currentNoteGuid = newGuid;
4504 if (externalWindows.containsKey(oldGuid)) {
4505 ExternalBrowse b = externalWindows.get(oldGuid);
4506 externalWindows.remove(oldGuid);
4507 b.getBrowserWindow().getNote().setGuid(newGuid);
4508 externalWindows.put(newGuid, b);
4511 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4512 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4513 noteTableView.proxyModel.addGuid(newGuid);
4514 i=listManager.getNoteIndex().size();
4518 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4519 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4520 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4521 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4525 // Toggle the note editor button bar
4526 private void toggleEditorButtonBar() {
4527 if (browserWindow.buttonsVisible) {
4528 browserWindow.hideButtons();
4529 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4530 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4532 browserWindow.buttonsVisible = true;
4533 showEditorButtons(browserWindow);
4535 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4537 // Show editor buttons
4538 private void showEditorButtons(BrowserWindow browser) {
4539 browser.buttonLayout.setVisible(true);
4540 browser.undoAction.setVisible(false);
4542 browser.undoButton.setVisible(false);
4544 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4545 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4546 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4547 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4548 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4549 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4550 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4551 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4552 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4553 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4554 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4555 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4556 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4557 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4558 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4559 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4560 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4561 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4562 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4563 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4564 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4565 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4566 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4568 private void duplicateNote(String guid) {
4570 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
4571 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4572 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4573 oldNote.setResources(resList);
4574 duplicateNote(oldNote);
4576 private void duplicateNote(Note oldNote) {
4578 // Now that we have a good notebook guid, we need to move the conflicting note
4579 // to the local notebook
4580 Calendar currentTime = new GregorianCalendar();
4581 Long l = new Long(currentTime.getTimeInMillis());
4582 String newGuid = new String(Long.toString(l));
4584 Note newNote = oldNote.deepCopy();
4585 newNote.setUpdateSequenceNum(0);
4586 newNote.setGuid(newGuid);
4587 newNote.setDeleted(0);
4588 newNote.setActive(true);
4589 List<Resource> resList = oldNote.getResources();
4590 if (resList == null)
4591 resList = new ArrayList<Resource>();
4593 for (int i=0; i<resList.size(); i++) {
4595 while (l == prevGuid) {
4596 currentTime = new GregorianCalendar();
4597 l = new Long(currentTime.getTimeInMillis());
4600 String newResGuid = new String(Long.toString(l));
4601 resList.get(i).setNoteGuid(newGuid);
4602 resList.get(i).setGuid(newResGuid);
4603 resList.get(i).setUpdateSequenceNum(0);
4604 resList.get(i).setActive(true);
4605 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
4607 newNote.setResources(resList);
4608 listManager.addNote(newNote);
4609 conn.getNoteTable().addNote(newNote, true);
4610 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4611 noteTableView.insertRow(newNote, true, -1);
4612 listManager.countNotebookResults(listManager.getNoteIndex());
4616 @SuppressWarnings("unused")
4617 private void allNotes() {
4618 clearAttributeFilter();
4619 clearNotebookFilter();
4620 clearSavedSearchFilter();
4623 searchField.clear();
4624 if (Global.mimicEvernoteInterface) {
4625 notebookTree.selectGuid("");
4627 notebookTreeSelection();
4630 @SuppressWarnings("unused")
4631 private void mergeNotes() {
4632 logger.log(logger.HIGH, "Merging notes");
4635 String masterGuid = null;
4636 List<String> sources = new ArrayList<String>();
4638 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4639 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4640 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4641 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4643 masterGuid = (String)ix.values().toArray()[0];
4645 sources.add((String)ix.values().toArray()[0]);
4648 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4649 logger.log(logger.EXTREME, "Children count: "+sources.size());
4650 mergeNoteContents(masterGuid, sources);
4651 currentNoteGuid = masterGuid;
4652 noteIndexUpdated(false);
4653 refreshEvernoteNote(true);
4656 private void mergeNoteContents(String targetGuid, List<String> sources) {
4657 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4658 String newContent = target.getContent();
4659 newContent = newContent.replace("</en-note>", "<br></br>");
4661 for (int i=0; i<sources.size(); i++) {
4662 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4663 if (source.isSetTitle()) {
4664 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4666 String sourceContent = source.getContent();
4667 logger.log(logger.EXTREME, "Merging contents into note");
4668 logger.log(logger.EXTREME, sourceContent);
4669 logger.log(logger.EXTREME, "End of content");
4670 int startOfNote = sourceContent.indexOf("<en-note>");
4671 sourceContent = sourceContent.substring(startOfNote+9);
4672 int endOfNote = sourceContent.indexOf("</en-note>");
4673 sourceContent = sourceContent.substring(0,endOfNote);
4674 newContent = newContent + sourceContent;
4675 logger.log(logger.EXTREME, "New note content");
4676 logger.log(logger.EXTREME, newContent);
4677 logger.log(logger.EXTREME, "End of content");
4678 for (int j=0; j<source.getResourcesSize(); j++) {
4679 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4680 Resource r = source.getResources().get(j);
4681 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4683 Calendar currentTime = new GregorianCalendar();
4684 Long l = new Long(currentTime.getTimeInMillis());
4688 while (l == prevGuid) {
4689 currentTime = new GregorianCalendar();
4690 l = new Long(currentTime.getTimeInMillis());
4692 String newResGuid = new String(Long.toString(l));
4693 newRes.setNoteGuid(targetGuid);
4694 newRes.setGuid(newResGuid);
4695 newRes.setUpdateSequenceNum(0);
4696 newRes.setActive(true);
4697 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4700 logger.log(logger.EXTREME, "Updating note");
4701 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4702 for (int i=0; i<sources.size(); i++) {
4703 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4704 listManager.deleteNote(sources.get(i));
4706 logger.log(logger.EXTREME, "Exiting merge note");
4708 // A resource within a note has had a guid change
4709 @SuppressWarnings("unused")
4710 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4711 if (!oldGuid.equals(newGuid))
4712 Global.resourceMap.put(oldGuid, newGuid);
4714 // View a thumbnail of the note
4715 public void thumbnailView() {
4717 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4718 QFile thumbnail = new QFile(thumbnailName);
4719 if (!thumbnail.exists()) {
4721 QImage img = new QImage();
4722 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4723 thumbnailViewer.setThumbnail(img);
4725 thumbnailViewer.setThumbnail(thumbnailName);
4726 if (!thumbnailViewer.isVisible())
4727 thumbnailViewer.showFullScreen();
4729 // An error happened while saving a note. Inform the user
4730 @SuppressWarnings("unused")
4731 private void saveRunnerError(String guid, String msg) {
4733 String title = "*Unknown*";
4734 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4735 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4736 title = listManager.getMasterNoteIndex().get(i).getTitle();
4737 i=listManager.getMasterNoteIndex().size();
4740 msg = "An error has happened while saving the note \"" +title+
4741 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4742 "As a result, changes to the note may not be saved properly in the database."+
4743 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4744 "\nbe lost. Please review the note to recover any critical data before restarting.";
4746 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4749 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4750 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4751 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4752 // Find an idle preview object
4753 for (int i=0; i<thumbGenerators.size(); i++) {
4754 if (thumbGenerators.get(i).mutex.tryLock()) {
4755 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4756 thumbGenerators.get(i).loadContent(guid, html, zoom);
4760 if (thumbGenerators.size() >= 1) {
4761 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4765 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4766 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4767 thumbGenerators.add(preview);
4769 if (preview.mutex.tryLock()) {
4770 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4771 preview.loadContent(guid, html, zoom);
4773 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4778 //**********************************************************
4779 //**********************************************************
4780 //* Online user actions
4781 //**********************************************************
4782 //**********************************************************
4783 private void setupOnlineMenu() {
4784 if (!Global.isConnected) {
4785 menuBar.noteOnlineHistoryAction.setEnabled(false);
4786 menuBar.selectiveSyncAction.setEnabled(false);
4789 menuBar.noteOnlineHistoryAction.setEnabled(true);
4790 menuBar.selectiveSyncAction.setEnabled(true);
4793 @SuppressWarnings("unused")
4794 private void viewNoteHistory() {
4795 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4797 if (currentNote.getUpdateSequenceNum() == 0) {
4798 setMessage(tr("Note has never been synchronized."));
4799 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4803 setMessage(tr("Getting Note History"));
4805 Note currentOnlineNote = null;
4808 if (Global.isPremium())
4809 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4811 versions = new ArrayList<NoteVersionId>();
4812 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4813 } catch (EDAMUserException e) {
4814 setMessage("EDAMUserException: " +e.getMessage());
4816 } catch (EDAMSystemException e) {
4817 setMessage("EDAMSystemException: " +e.getMessage());
4819 } catch (EDAMNotFoundException e) {
4820 setMessage(tr("Note not found on server."));
4821 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4823 } catch (TException e) {
4824 setMessage("EDAMTransactionException: " +e.getMessage());
4828 // If we've gotten this far, we have a good note.
4829 if (historyWindow == null) {
4830 historyWindow = new OnlineNoteHistory(logger, conn);
4831 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4832 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4833 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4835 historyWindow.historyCombo.clear();
4837 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4838 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4840 historyWindow.setCurrent(isDirty);
4842 loadHistoryWindowContent(currentOnlineNote);
4843 historyWindow.load(versions);
4844 setMessage(tr("History retrieved"));
4846 historyWindow.exec();
4848 private Note reloadHistoryWindow(String selection) {
4850 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4851 String dateTimeFormat = new String(fmt);
4852 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4856 for (int i=0; i<versions.size(); i++) {
4857 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4858 if (versionDate.toString().equals(selection))
4862 if (index > -1 || selection.indexOf("Current") > -1) {
4863 Note historyNote = null;
4866 usn = versions.get(index).getUpdateSequenceNum();
4867 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4869 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4870 } catch (EDAMUserException e) {
4871 setMessage("EDAMUserException: " +e.getMessage());
4874 } catch (EDAMSystemException e) {
4875 setMessage("EDAMSystemException: " +e.getMessage());
4878 } catch (EDAMNotFoundException e) {
4879 setMessage("EDAMNotFoundException: " +e.getMessage());
4882 } catch (TException e) {
4883 setMessage("EDAMTransactionException: " +e.getMessage());
4889 if (historyNote != null)
4890 historyWindow.setContent(historyNote);
4896 private void loadHistoryWindowContent(Note note) {
4897 note.setUpdateSequenceNum(0);
4898 historyWindow.setContent(note);
4900 @SuppressWarnings("unused")
4901 private void restoreHistoryNoteAsNew() {
4902 setMessage(tr("Restoring as new note."));
4903 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4904 setMessage(tr("Note has been restored as a new note."));
4906 @SuppressWarnings("unused")
4907 private void restoreHistoryNote() {
4908 setMessage(tr("Restoring note."));
4909 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
4910 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
4913 for (int i=0; i<n.getResourcesSize(); i++) {
4914 n.getResources().get(i).setActive(true);
4915 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
4917 listManager.addNote(n);
4918 conn.getNoteTable().addNote(n, true);
4919 refreshEvernoteNote(true);
4920 setMessage(tr("Note has been restored."));
4922 @SuppressWarnings("unused")
4923 private void setupSelectiveSync() {
4925 // Get a list of valid notebooks
4926 List<Notebook> notebooks = null;
4927 List<Tag> tags = null;
4928 List<LinkedNotebook> linkedNotebooks = null;
4930 notebooks = syncRunner.noteStore.listNotebooks(syncRunner.authToken);
4931 tags = syncRunner.noteStore.listTags(syncRunner.authToken);
4932 linkedNotebooks = syncRunner.noteStore.listLinkedNotebooks(syncRunner.authToken);
4933 } catch (EDAMUserException e) {
4934 setMessage("EDAMUserException: " +e.getMessage());
4936 } catch (EDAMSystemException e) {
4937 setMessage("EDAMSystemException: " +e.getMessage());
4939 } catch (TException e) {
4940 setMessage("EDAMTransactionException: " +e.getMessage());
4942 } catch (EDAMNotFoundException e) {
4943 setMessage("EDAMNotFoundException: " +e.getMessage());
4947 // Split up notebooks into synchronized & non-synchronized
4948 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
4949 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4951 for (int i=notebooks.size()-1; i>=0; i--) {
4952 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
4953 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
4954 ignoredBooks.add(notebooks.get(i));
4955 j=dbIgnoredNotebooks.size();
4960 // split up tags into synchronized & non-synchronized
4961 List<Tag> ignoredTags = new ArrayList<Tag>();
4962 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
4964 for (int i=tags.size()-1; i>=0; i--) {
4965 for (int j=0; j<dbIgnoredTags.size(); j++) {
4966 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
4967 ignoredTags.add(tags.get(i));
4968 j=dbIgnoredTags.size();
4973 // split up linked notebooks into synchronized & non-synchronized
4974 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
4975 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
4976 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
4977 String notebookGuid = linkedNotebooks.get(i).getGuid();
4978 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
4979 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
4980 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
4981 j=dbIgnoredLinkedNotebooks.size();
4986 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
4988 if (!ignore.okClicked())
4993 // Clear out old notebooks & add the new ones
4994 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4995 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
4996 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
4999 List<String> newNotebooks = new ArrayList<String>();
5000 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5001 String text = ignore.getIgnoredBookList().takeItem(i).text();
5002 for (int j=0; j<notebooks.size(); j++) {
5003 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5004 Notebook n = notebooks.get(j);
5005 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5007 newNotebooks.add(n.getGuid());
5012 // Clear out old tags & add new ones
5013 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5014 for (int i=0; i<oldIgnoreTags.size(); i++) {
5015 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5018 List<String> newTags = new ArrayList<String>();
5019 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5020 String text = ignore.getIgnoredTagList().takeItem(i).text();
5021 for (int j=0; j<tags.size(); j++) {
5022 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5023 Tag t = tags.get(j);
5024 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5025 newTags.add(t.getGuid());
5031 // Clear out old tags & add new ones
5032 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5033 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5034 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5037 List<String> newLinked = new ArrayList<String>();
5038 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5039 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5040 for (int j=0; j<linkedNotebooks.size(); j++) {
5041 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5042 LinkedNotebook t = linkedNotebooks.get(j);
5043 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5044 newLinked.add(t.getGuid());
5045 j=linkedNotebooks.size();
5050 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5056 //**********************************************************
5057 //**********************************************************
5058 //* XML Modifying methods
5059 //**********************************************************
5060 //**********************************************************
5061 // An error has happended fetching a resource. let the user know
5062 private void resourceErrorMessage() {
5065 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5066 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5067 "In a perfect world this wouldn't happen, but it has.\n" +
5068 "It is embarasing when a program like me, designed to save all your\n"+
5069 "precious data, has a problem finding data.\n\n" +
5070 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5071 "In the mean time, I'm not going to let you make changes to this note.\n" +
5072 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5073 "this note on the Evernote servers. Sorry."+
5074 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5076 browserWindow.setReadOnly(true);
5082 //**********************************************************
5083 //**********************************************************
5085 //**********************************************************
5086 //**********************************************************
5087 // We should now do a sync with Evernote
5088 private void syncTimer() {
5089 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5090 syncRunner.syncNeeded = true;
5091 syncRunner.disableUploads = Global.disableUploads;
5093 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5095 private void syncStart() {
5096 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5098 if (!syncRunning && Global.isConnected) {
5099 syncRunner.setConnected(true);
5100 syncRunner.setKeepRunning(Global.keepRunning);
5101 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5103 if (syncThreadsReady > 0) {
5104 thumbnailRunner.interrupt = true;
5105 saveNoteIndexWidth();
5106 saveNoteColumnPositions();
5107 if (syncRunner.addWork("SYNC")) {
5109 syncRunner.syncNeeded = true;
5114 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5116 @SuppressWarnings("unused")
5117 private void syncThreadComplete(Boolean refreshNeeded) {
5118 setMessage(tr("Finalizing Synchronization"));
5120 syncRunning = false;
5121 syncRunner.syncNeeded = false;
5122 synchronizeAnimationTimer.stop();
5123 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5125 if (currentNote == null) {
5126 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5128 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5129 noteIndexUpdated(false);
5130 noteTableView.selectionModel().blockSignals(true);
5131 scrollToGuid(currentNoteGuid);
5132 noteTableView.selectionModel().blockSignals(false);
5133 refreshEvernoteNote(false);
5134 scrollToGuid(currentNoteGuid);
5136 if (!syncRunner.error)
5137 setMessage(tr("Synchronization Complete"));
5139 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5140 logger.log(logger.MEDIUM, "Sync complete.");
5142 public void saveUploadAmount(long t) {
5143 Global.saveUploadAmount(t);
5145 public void saveUserInformation(User user) {
5146 Global.saveUserInformation(user);
5148 public void saveEvernoteUpdateCount(int i) {
5149 Global.saveEvernoteUpdateCount(i);
5151 public void refreshLists() {
5152 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5154 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5155 tagIndexUpdated(true);
5156 notebookIndexUpdated();
5157 savedSearchIndexUpdated();
5158 listManager.loadNotesIndex();
5160 noteTableView.selectionModel().blockSignals(true);
5161 noteIndexUpdated(true);
5162 noteTableView.selectionModel().blockSignals(false);
5163 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5167 @SuppressWarnings("unused")
5168 private void authTimer() {
5169 Calendar cal = Calendar.getInstance();
5171 // If we are not connected let's get out of here
5172 if (!Global.isConnected)
5175 // If this is the first time through, then we need to set this
5176 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5177 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5179 // long now = new Date().getTime();
5180 // if (now > Global.authRefreshTime && Global.isConnected) {
5181 syncRunner.authRefreshNeeded = true;
5185 @SuppressWarnings("unused")
5186 private void authRefreshComplete(boolean goodSync) {
5187 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5188 Global.isConnected = syncRunner.isConnected;
5190 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5191 authTimer.start(1000*60*15);
5192 logger.log(logger.LOW, "Authentication token has been renewed");
5193 // setMessage("Authentication token has been renewed.");
5195 authTimer.start(1000*60*5);
5196 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5197 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5199 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5203 @SuppressWarnings("unused")
5204 private synchronized void indexTimer() {
5205 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5208 if (!indexDisabled && indexRunner.idle) {
5209 thumbnailRunner.interrupt = true;
5210 indexRunner.addWork("SCAN");
5212 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5215 @SuppressWarnings("unused")
5216 private void indexStarted() {
5217 setMessage(tr("Indexing notes"));
5219 @SuppressWarnings("unused")
5220 private void indexComplete() {
5221 setMessage(tr("Index complete"));
5223 @SuppressWarnings("unused")
5224 private synchronized void toggleNoteIndexing() {
5225 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5226 indexDisabled = !indexDisabled;
5228 setMessage(tr("Indexing is now enabled."));
5230 setMessage(tr("Indexing is now disabled."));
5231 menuBar.disableIndexing.setChecked(indexDisabled);
5232 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5235 @SuppressWarnings("unused")
5236 private void threadMonitorCheck() {
5241 alive = listManager.threadCheck(Global.tagCounterThreadId);
5244 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5245 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5246 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5247 disableTagThreadCheck = true;
5252 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5254 notebookThreadDeadCount++;
5255 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5256 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5257 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5258 disableNotebookThreadCheck=true;
5261 notebookThreadDeadCount=0;
5263 alive = listManager.threadCheck(Global.trashCounterThreadId);
5266 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5267 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5268 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5269 disableTrashThreadCheck = true;
5274 alive = listManager.threadCheck(Global.saveThreadId);
5276 saveThreadDeadCount++;
5277 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5278 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5279 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5280 disableSaveThreadCheck = true;
5283 saveThreadDeadCount=0;
5285 if (!syncThread.isAlive()) {
5286 syncThreadDeadCount++;
5287 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5288 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5289 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5290 disableSyncThreadCheck = true;
5293 syncThreadDeadCount=0;
5295 if (!indexThread.isAlive()) {
5296 indexThreadDeadCount++;
5297 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5298 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5299 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5300 disableIndexThreadCheck = true;
5303 indexThreadDeadCount=0;
5308 private void thumbnailTimer() {
5309 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5310 thumbnailRunner.addWork("SCAN");
5314 //**************************************************
5315 //* Backup & Restore
5316 //**************************************************
5317 @SuppressWarnings("unused")
5318 private void databaseBackup() {
5319 QFileDialog fd = new QFileDialog(this);
5320 fd.setFileMode(FileMode.AnyFile);
5321 fd.setConfirmOverwrite(true);
5322 fd.setWindowTitle(tr("Backup Database"));
5323 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5324 fd.setAcceptMode(AcceptMode.AcceptSave);
5325 if (saveLastPath == null || saveLastPath.equals(""))
5326 fd.setDirectory(System.getProperty("user.home"));
5328 fd.setDirectory(saveLastPath);
5329 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5335 saveLastPath = fd.selectedFiles().get(0);
5336 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5337 setMessage(tr("Backing up database"));
5339 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5341 ExportData noteWriter = new ExportData(conn, true);
5342 String fileName = fd.selectedFiles().get(0);
5344 if (!fileName.endsWith(".nnex"))
5345 fileName = fileName +".nnex";
5346 noteWriter.exportData(fileName);
5347 setMessage(tr("Database backup completed."));
5352 @SuppressWarnings("unused")
5353 private void databaseRestore() {
5354 if (QMessageBox.question(this, tr("Confirmation"),
5355 tr("This is used to restore a database from backups.\n" +
5356 "It is HIGHLY recommened that this only be used to populate\n" +
5357 "an empty database. Restoring into a database that\n already has data" +
5358 " can cause problems.\n\nAre you sure you want to continue?"),
5359 QMessageBox.StandardButton.Yes,
5360 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5365 QFileDialog fd = new QFileDialog(this);
5366 fd.setFileMode(FileMode.ExistingFile);
5367 fd.setConfirmOverwrite(true);
5368 fd.setWindowTitle(tr("Restore Database"));
5369 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5370 fd.setAcceptMode(AcceptMode.AcceptOpen);
5371 if (saveLastPath == null || saveLastPath.equals(""))
5372 fd.setDirectory(System.getProperty("user.home"));
5374 fd.setDirectory(saveLastPath);
5375 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5381 saveLastPath = fd.selectedFiles().get(0);
5382 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5384 setMessage(tr("Restoring database"));
5385 ImportData noteReader = new ImportData(conn, true);
5386 noteReader.importData(fd.selectedFiles().get(0));
5388 if (noteReader.lastError != 0) {
5389 setMessage(noteReader.getErrorMessage());
5390 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5395 listManager.loadNoteTitleColors();
5397 refreshEvernoteNote(true);
5398 setMessage(tr("Database has been restored."));
5401 @SuppressWarnings("unused")
5402 private void exportNotes() {
5403 QFileDialog fd = new QFileDialog(this);
5404 fd.setFileMode(FileMode.AnyFile);
5405 fd.setConfirmOverwrite(true);
5406 fd.setWindowTitle(tr("Backup Database"));
5407 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5408 fd.setAcceptMode(AcceptMode.AcceptSave);
5409 fd.setDirectory(System.getProperty("user.home"));
5410 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5416 setMessage(tr("Exporting Notes"));
5419 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5420 selectedNoteGUIDs.add(currentNoteGuid);
5422 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5423 String fileName = fd.selectedFiles().get(0);
5425 if (!fileName.endsWith(".nnex"))
5426 fileName = fileName +".nnex";
5427 noteWriter.exportData(fileName);
5428 setMessage(tr("Export completed."));
5434 @SuppressWarnings("unused")
5435 private void importNotes() {
5436 QFileDialog fd = new QFileDialog(this);
5437 fd.setFileMode(FileMode.ExistingFile);
5438 fd.setConfirmOverwrite(true);
5439 fd.setWindowTitle(tr("Import Notes"));
5440 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5441 fd.setAcceptMode(AcceptMode.AcceptOpen);
5442 if (saveLastPath == null || saveLastPath.equals(""))
5443 fd.setDirectory(System.getProperty("user.home"));
5445 fd.setDirectory(saveLastPath);
5446 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5452 setMessage("Importing Notes");
5455 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5456 selectedNoteGUIDs.add(currentNoteGuid);
5458 ImportData noteReader = new ImportData(conn, false);
5459 String fileName = fd.selectedFiles().get(0);
5460 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5462 if (!fileName.endsWith(".nnex"))
5463 fileName = fileName +".nnex";
5464 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5465 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5467 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5469 noteReader.importData(fileName);
5471 if (noteReader.lastError != 0) {
5472 setMessage(noteReader.getErrorMessage());
5473 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5478 listManager.loadNoteTitleColors();
5480 refreshEvernoteNote(false);
5481 setMessage(tr("Notes have been imported."));
5484 setMessage("Import completed.");
5491 //**************************************************
5492 //* Duplicate a note
5493 //**************************************************
5494 @SuppressWarnings("unused")
5495 private void duplicateNote() {
5497 duplicateNote(currentNoteGuid);
5502 //**************************************************
5504 //**************************************************
5505 public void setupFolderImports() {
5506 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5508 if (importKeepWatcher == null)
5509 importKeepWatcher = new QFileSystemWatcher();
5510 if (importDeleteWatcher == null) {
5511 importDeleteWatcher = new QFileSystemWatcher();
5512 for (int i=0; i<records.size(); i++) {
5513 if (!records.get(i).keep)
5514 folderImportDelete(records.get(i).folder);
5520 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5521 for (int i=0; i<records.size(); i++) {
5522 if (records.get(i).keep)
5523 importKeepWatcher.addPath(records.get(i).folder);
5525 importDeleteWatcher.addPath(records.get(i).folder);
5528 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5529 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5531 // Look at the files already there so we don't import them again if a new file is created
5532 if (importedFiles == null) {
5533 importedFiles = new ArrayList<String>();
5534 for (int j=0; j<records.size(); j++) {
5535 QDir dir = new QDir(records.get(j).folder);
5536 List<QFileInfo> list = dir.entryInfoList();
5537 for (int k=0; k<list.size(); k++) {
5538 if (list.get(k).isFile())
5539 importedFiles.add(list.get(k).absoluteFilePath());
5544 public void folderImport() {
5545 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5546 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5548 if (!dialog.okClicked())
5551 // We have some sort of update.
5552 if (importKeepWatcher.directories().size() > 0)
5553 importKeepWatcher.removePaths(importKeepWatcher.directories());
5554 if (importDeleteWatcher.directories().size() > 0)
5555 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5557 conn.getWatchFolderTable().expungeAll();
5558 // Start building from the table
5559 for (int i=0; i<dialog.table.rowCount(); i++) {
5560 QTableWidgetItem item = dialog.table.item(i, 0);
5561 String dir = item.text();
5562 item = dialog.table.item(i, 1);
5563 String notebook = item.text();
5564 item = dialog.table.item(i, 2);
5566 if (item.text().equalsIgnoreCase("Keep"))
5571 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5572 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5574 setupFolderImports();
5577 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5579 String whichOS = System.getProperty("os.name");
5580 if (whichOS.contains("Windows"))
5581 dirName = dirName.replace('/','\\');
5583 FileImporter importer = new FileImporter(logger, conn);
5585 QDir dir = new QDir(dirName);
5586 List<QFileInfo> list = dir.entryInfoList();
5587 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5589 for (int i=0; i<list.size(); i++){
5591 boolean redundant = false;
5592 // Check if we've already imported this one or if it existed before
5593 for (int j=0; j<importedFiles.size(); j++) {
5594 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5599 importer.setFileInfo(list.get(i));
5600 importer.setFileName(list.get(i).absoluteFilePath());
5603 if (list.get(i).isFile() && importer.isValidType()) {
5605 if (!importer.importFile()) {
5606 // If we can't get to the file, it is probably locked. We'll try again later.
5607 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5608 importFilesKeep.add(list.get(i).absoluteFilePath());
5612 Note newNote = importer.getNote();
5613 newNote.setNotebookGuid(notebook);
5614 newNote.setTitle(dir.at(i));
5615 listManager.addNote(newNote);
5616 conn.getNoteTable().addNote(newNote, true);
5617 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5618 noteTableView.insertRow(newNote, true, -1);
5619 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5620 listManager.countNotebookResults(listManager.getNoteIndex());
5621 importedFiles.add(list.get(i).absoluteFilePath());
5629 public void folderImportDelete(String dirName) {
5631 String whichOS = System.getProperty("os.name");
5632 if (whichOS.contains("Windows"))
5633 dirName = dirName.replace('/','\\');
5635 FileImporter importer = new FileImporter(logger, conn);
5636 QDir dir = new QDir(dirName);
5637 List<QFileInfo> list = dir.entryInfoList();
5638 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5640 for (int i=0; i<list.size(); i++){
5641 importer.setFileInfo(list.get(i));
5642 importer.setFileName(list.get(i).absoluteFilePath());
5644 if (list.get(i).isFile() && importer.isValidType()) {
5646 if (!importer.importFile()) {
5647 // If we can't get to the file, it is probably locked. We'll try again later.
5648 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5649 importFilesKeep.add(list.get(i).absoluteFilePath());
5653 Note newNote = importer.getNote();
5654 newNote.setNotebookGuid(notebook);
5655 newNote.setTitle(dir.at(i));
5656 listManager.addNote(newNote);
5657 conn.getNoteTable().addNote(newNote, true);
5658 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5659 noteTableView.insertRow(newNote, true, -1);
5660 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5661 listManager.countNotebookResults(listManager.getNoteIndex());
5662 dir.remove(dir.at(i));
5668 //**************************************************
5670 //**************************************************
5671 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5672 logger.log(logger.HIGH, "Entering exernalFileEdited");
5674 // Strip URL prefix and base dir path
5675 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5676 String name = fileName.replace(dPath, "");
5677 int pos = name.lastIndexOf('.');
5680 guid = guid.substring(0,pos);
5682 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5684 guid = name.substring(0, pos);
5687 QFile file = new QFile(fileName);
5688 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5689 // If we can't get to the file, it is probably locked. We'll try again later.
5690 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5691 externalFiles.add(fileName);
5694 QByteArray binData = file.readAll();
5696 if (binData.size() == 0) {
5697 // If we can't get to the file, it is probably locked. We'll try again later.
5698 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5699 externalFiles.add(fileName);
5703 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5705 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5706 if (r == null || r.getData() == null || r.getData().getBody() == null)
5708 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5709 MessageDigest md = MessageDigest.getInstance("MD5");
5710 md.update(binData.toByteArray());
5711 byte[] hash = md.digest();
5712 String newHash = Global.byteArrayToHexString(hash);
5713 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5714 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5716 if (externalWindows.containsKey(r.getNoteGuid())) {
5717 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5718 r.getGuid(), oldHash, newHash);
5720 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5721 Data data = r.getData();
5722 data.setBody(binData.toByteArray());
5723 data.setBodyHash(hash);
5724 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5726 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5728 if (r.getNoteGuid().equals(currentNoteGuid)) {
5729 QWebSettings.setMaximumPagesInCache(0);
5730 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5731 refreshEvernoteNote(true);
5732 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5735 if (externalWindows.containsKey(r.getNoteGuid())) {
5736 QWebSettings.setMaximumPagesInCache(0);
5737 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5738 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5742 logger.log(logger.HIGH, "Exiting externalFielEdited");
5744 // This is a timer event that tries to save any external files that were edited. This
5745 // is only needed if we couldn't save a file earlier.
5746 public void externalFileEditedSaver() {
5747 for (int i=externalFiles.size()-1; i>=0; i--) {
5749 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5750 externalFileEdited(externalFiles.get(i));
5751 externalFiles.remove(i);
5752 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5754 for (int i=0; i<importFilesKeep.size(); i++) {
5756 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5757 folderImportKeep(importFilesKeep.get(i));
5758 importFilesKeep.remove(i);
5759 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5761 for (int i=0; i<importFilesDelete.size(); i++) {
5762 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5763 folderImportDelete(importFilesDelete.get(i));
5764 importFilesDelete.remove(i);
5771 // If an attachment on the current note was edited, we need to update the current notes's hash
5772 // Update a note content's hash. This happens if a resource is edited outside of NN
5773 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5774 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5776 for (;position>-1;) {
5777 endPos = browser.getContent().indexOf(">", position+1);
5778 String oldSegment = browser.getContent().substring(position,endPos);
5779 int hashPos = oldSegment.indexOf("hash=\"");
5780 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5781 String hash = oldSegment.substring(hashPos+6, hashEnd);
5782 if (hash.equalsIgnoreCase(oldHash)) {
5783 String newSegment = oldSegment.replace(oldHash, newHash);
5784 String content = browser.getContent().substring(0,position) +
5786 browser.getContent().substring(endPos);
5787 browser.getBrowser().setContent(new QByteArray(content));;
5790 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5795 //*************************************************
5796 //* Minimize to tray
5797 //*************************************************
5799 public void changeEvent(QEvent e) {
5800 if (e.type() == QEvent.Type.WindowStateChange) {
5801 if (isMinimized() && Global.showTrayIcon()) {
5803 QTimer.singleShot(10, this, "hide()");
5807 windowMaximized = true;
5809 windowMaximized = false;
5813 //*************************************************
5814 //* Check database userid & passwords
5815 //*************************************************
5816 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5817 Connection connection;
5820 Class.forName("org.h2.Driver");
5821 } catch (ClassNotFoundException e1) {
5822 e1.printStackTrace();
5827 String passwordString = null;
5828 if (cypherPassword==null || cypherPassword.trim().equals(""))
5829 passwordString = userPassword;
5831 passwordString = cypherPassword+" "+userPassword;
5832 connection = DriverManager.getConnection(url,userid,passwordString);
5833 } catch (SQLException e) {
5838 } catch (SQLException e) {
5839 e.printStackTrace();