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 if (Global.version.equals(version))
2595 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2597 if (dialog.remindMe())
2598 Global.setCheckVersionUpgrade(true);
2600 Global.setCheckVersionUpgrade(false);
2604 //***************************************************************
2605 //***************************************************************
2606 //** These functions deal with the Toolbar
2607 //***************************************************************
2608 //***************************************************************
2609 // Text in the search bar has been cleared
2610 private void searchFieldCleared() {
2613 // This is done because we want to force a reload of
2614 // images. Some images we may want to highlight the text.
2615 readOnlyCache.clear();
2616 inkNoteCache.clear();
2618 QWebSettings.setMaximumPagesInCache(0);
2619 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2621 searchField.setEditText("");
2622 saveNoteColumnPositions();
2623 saveNoteIndexWidth();
2624 noteIndexUpdated(true);
2625 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2626 currentNote = listManager.getNoteIndex().get(0);
2627 currentNoteGuid = currentNote.getGuid();
2629 if (currentNote != null)
2630 loadNoteBrowserInformation(browserWindow);
2632 // text in the search bar changed. We only use this to tell if it was cleared,
2633 // otherwise we trigger off searchFieldChanged.
2634 @SuppressWarnings("unused")
2635 private void searchFieldTextChanged(String text) {
2636 QWebSettings.setMaximumPagesInCache(0);
2637 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2639 if (text.trim().equals("")) {
2640 searchFieldCleared();
2641 if (searchPerformed) {
2643 // This is done because we want to force a reload of
2644 // images. Some images we may want to highlight the text.
2646 readOnlyCache.clear();
2647 inkNoteCache.clear();
2649 listManager.setEnSearch("");
2650 listManager.loadNotesIndex();
2651 refreshEvernoteNote(true);
2652 noteIndexUpdated(false);
2654 searchPerformed = false;
2657 // Text in the toolbar has changed
2658 private void searchFieldChanged() {
2659 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2661 readOnlyCache.clear();
2662 inkNoteCache.clear();
2663 saveNoteColumnPositions();
2664 saveNoteIndexWidth();
2665 String text = searchField.currentText();
2666 listManager.setEnSearch(text.trim());
2667 listManager.loadNotesIndex();
2668 //--->>> noteIndexUpdated(true);
2669 noteIndexUpdated(false);
2670 refreshEvernoteNote(true);
2671 searchPerformed = true;
2672 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2675 // Build the window tool bar
2676 private void setupToolBar() {
2677 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2678 toolBar = addToolBar(tr("Tool Bar"));
2679 menuBar.setupToolBarVisible();
2680 if (!Global.isWindowVisible("toolBar"))
2681 toolBar.setVisible(false);
2683 toolBar.setVisible(true);
2685 prevButton = toolBar.addAction("Previous");
2686 QIcon prevIcon = new QIcon(iconPath+"back.png");
2687 prevButton.setIcon(prevIcon);
2688 prevButton.triggered.connect(this, "previousViewedAction()");
2689 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2691 nextButton = toolBar.addAction("Next");
2692 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2693 nextButton.setIcon(nextIcon);
2694 nextButton.triggered.connect(this, "nextViewedAction()");
2695 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2697 upButton = toolBar.addAction("Up");
2698 QIcon upIcon = new QIcon(iconPath+"up.png");
2699 upButton.setIcon(upIcon);
2700 upButton.triggered.connect(this, "upAction()");
2701 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2704 downButton = toolBar.addAction("Down");
2705 QIcon downIcon = new QIcon(iconPath+"down.png");
2706 downButton.setIcon(downIcon);
2707 downButton.triggered.connect(this, "downAction()");
2708 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2710 synchronizeButton = toolBar.addAction("Synchronize");
2711 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2712 synchronizeIconAngle = 0;
2713 synchronizeButton.triggered.connect(this, "evernoteSync()");
2714 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2716 printButton = toolBar.addAction("Print");
2717 QIcon printIcon = new QIcon(iconPath+"print.png");
2718 printButton.setIcon(printIcon);
2719 printButton.triggered.connect(this, "printNote()");
2720 togglePrintButton(Global.isToolbarButtonVisible("print"));
2722 tagButton = toolBar.addAction("Tag");
2723 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2724 tagButton.setIcon(tagIcon);
2725 tagButton.triggered.connect(browserWindow, "modifyTags()");
2726 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2728 attributeButton = toolBar.addAction("Attributes");
2729 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2730 attributeButton.setIcon(attributeIcon);
2731 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2732 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2734 emailButton = toolBar.addAction("Email");
2735 QIcon emailIcon = new QIcon(iconPath+"email.png");
2736 emailButton.setIcon(emailIcon);
2737 emailButton.triggered.connect(this, "emailNote()");
2738 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2740 deleteButton = toolBar.addAction("Delete");
2741 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2742 deleteButton.setIcon(deleteIcon);
2743 deleteButton.triggered.connect(this, "deleteNote()");
2744 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2746 newButton = toolBar.addAction("New");
2747 QIcon newIcon = new QIcon(iconPath+"new.png");
2748 newButton.triggered.connect(this, "addNote()");
2749 newButton.setIcon(newIcon);
2750 toggleNewButton(Global.isToolbarButtonVisible("new"));
2752 allNotesButton = toolBar.addAction("All Notes");
2753 QIcon allIcon = new QIcon(iconPath+"books.png");
2754 allNotesButton.triggered.connect(this, "allNotes()");
2755 allNotesButton.setIcon(allIcon);
2756 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2758 toolBar.addSeparator();
2759 toolBar.addWidget(new QLabel(tr("Quota:")));
2760 toolBar.addWidget(quotaBar);
2761 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2763 toolBar.addSeparator();
2766 zoomSpinner = new QSpinBox();
2767 zoomSpinner.setMinimum(10);
2768 zoomSpinner.setMaximum(1000);
2769 zoomSpinner.setAccelerated(true);
2770 zoomSpinner.setSingleStep(10);
2771 zoomSpinner.setValue(100);
2772 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2773 toolBar.addWidget(new QLabel(tr("Zoom")));
2774 toolBar.addWidget(zoomSpinner);
2776 //toolBar.addWidget(new QLabel(" "));
2777 toolBar.addSeparator();
2778 toolBar.addWidget(new QLabel(tr(" Search:")));
2779 toolBar.addWidget(searchField);
2780 QSizePolicy sizePolicy = new QSizePolicy();
2781 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2782 searchField.setSizePolicy(sizePolicy);
2783 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2785 searchClearButton = toolBar.addAction("Search Clear");
2786 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2787 searchClearButton.setIcon(searchClearIcon);
2788 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2789 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2791 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2793 // Update the sychronize button picture
2795 public QMenu createPopupMenu() {
2796 QMenu contextMenu = super.createPopupMenu();
2798 contextMenu.addSeparator();
2799 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2800 contextMenu.addAction(prevAction);
2801 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2803 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2804 contextMenu.addAction(nextAction);
2805 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2807 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2808 contextMenu.addAction(upAction);
2809 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2811 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2812 contextMenu.addAction(downAction);
2813 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2815 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2816 contextMenu.addAction(synchronizeAction);
2817 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2819 QAction printAction = addContextAction("print", tr("Print"));
2820 contextMenu.addAction(printAction);
2821 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2823 QAction tagAction = addContextAction("tag", tr("Tag"));
2824 contextMenu.addAction(tagAction);
2825 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2827 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2828 contextMenu.addAction(attributeAction);
2829 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2831 QAction emailAction = addContextAction("email", tr("Email"));
2832 contextMenu.addAction(emailAction);
2833 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2835 QAction deleteAction = addContextAction("delete", tr("Delete"));
2836 contextMenu.addAction(deleteAction);
2837 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2839 QAction newAction = addContextAction("new", tr("Add"));
2840 contextMenu.addAction(newAction);
2841 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2843 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2844 contextMenu.addAction(allNotesAction);
2845 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2847 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2848 contextMenu.addAction(searchClearAction);
2849 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2854 private QAction addContextAction(String config, String name) {
2855 QAction newAction = new QAction(this);
2856 newAction.setText(name);
2857 newAction.setCheckable(true);
2858 newAction.setChecked(Global.isToolbarButtonVisible(config));
2861 private void togglePrevArrowButton(Boolean toggle) {
2862 prevButton.setVisible(toggle);
2863 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2865 private void toggleNextArrowButton(Boolean toggle) {
2866 nextButton.setVisible(toggle);
2867 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2869 private void toggleUpArrowButton(Boolean toggle) {
2870 upButton.setVisible(toggle);
2871 Global.saveToolbarButtonsVisible("upArrow", toggle);
2873 private void toggleDownArrowButton(Boolean toggle) {
2874 downButton.setVisible(toggle);
2875 Global.saveToolbarButtonsVisible("downArrow", toggle);
2877 private void toggleSynchronizeButton(Boolean toggle) {
2878 synchronizeButton.setVisible(toggle);
2879 Global.saveToolbarButtonsVisible("synchronize", toggle);
2881 private void togglePrintButton(Boolean toggle) {
2882 printButton.setVisible(toggle);
2883 Global.saveToolbarButtonsVisible("print", toggle);
2885 private void toggleTagButton(Boolean toggle) {
2886 tagButton.setVisible(toggle);
2887 Global.saveToolbarButtonsVisible("tag", toggle);
2889 private void toggleAttributeButton(Boolean toggle) {
2890 attributeButton.setVisible(toggle);
2891 Global.saveToolbarButtonsVisible("attribute", toggle);
2893 private void toggleEmailButton(Boolean toggle) {
2894 emailButton.setVisible(toggle);
2895 Global.saveToolbarButtonsVisible("email", toggle);
2897 private void toggleDeleteButton(Boolean toggle) {
2898 deleteButton.setVisible(toggle);
2899 Global.saveToolbarButtonsVisible("delete", toggle);
2901 private void toggleNewButton(Boolean toggle) {
2902 newButton.setVisible(toggle);
2903 Global.saveToolbarButtonsVisible("new", toggle);
2905 private void toggleAllNotesButton(Boolean toggle) {
2906 allNotesButton.setVisible(toggle);
2907 Global.saveToolbarButtonsVisible("allNotes", toggle);
2909 private void toggleSearchClearButton(Boolean toggle) {
2910 searchClearButton.setVisible(toggle);
2911 Global.saveToolbarButtonsVisible("searchClear", toggle);
2918 @SuppressWarnings("unused")
2919 private void updateSyncButton() {
2921 if (syncIcons == null) {
2922 syncIcons = new ArrayList<QPixmap>();
2924 synchronizeIconAngle = 0;
2925 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2927 for (int i=0; i<=360; i++) {
2928 QPixmap rotatedPix = new QPixmap(pix.size());
2929 QPainter p = new QPainter(rotatedPix);
2930 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2931 QSize size = pix.size();
2932 p.translate(size.width()/2, size.height()/2);
2935 p.setBackgroundMode(BGMode.OpaqueMode);
2936 p.translate(-size.width()/2, -size.height()/2);
2937 p.drawPixmap(0,0, pix);
2939 syncIcons.add(rotatedPix);
2943 synchronizeIconAngle++;
2944 if (synchronizeIconAngle > 359)
2945 synchronizeIconAngle=0;
2946 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2949 // Synchronize with Evernote
2950 @SuppressWarnings("unused")
2951 private void evernoteSync() {
2952 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2953 if (!Global.isConnected)
2955 if (Global.isConnected)
2956 synchronizeAnimationTimer.start(5);
2957 // synchronizeAnimationTimer.start(200);
2959 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
2961 private void updateQuotaBar() {
2962 long limit = Global.getUploadLimit();
2963 long amount = Global.getUploadAmount();
2964 if (amount>0 && limit>0) {
2965 int percent =(int)(amount*100/limit);
2966 quotaBar.setValue(percent);
2968 quotaBar.setValue(0);
2971 @SuppressWarnings("unused")
2972 private void zoomChanged() {
2973 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
2976 //****************************************************************
2977 //****************************************************************
2978 //* System Tray functions
2979 //****************************************************************
2980 //****************************************************************
2981 private void trayToggleVisible() {
2986 if (windowMaximized)
2993 @SuppressWarnings("unused")
2994 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
2995 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
2996 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
2997 trayToggleVisible();
3002 //***************************************************************
3003 //***************************************************************
3004 //** These functions deal with the trash tree
3005 //***************************************************************
3006 //***************************************************************
3007 // Setup the tree containing the trash.
3008 @SuppressWarnings("unused")
3009 private void trashTreeSelection() {
3010 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3012 clearNotebookFilter();
3014 clearAttributeFilter();
3015 clearSavedSearchFilter();
3017 String tempGuid = currentNoteGuid;
3019 // currentNoteGuid = "";
3020 currentNote = new Note();
3021 selectedNoteGUIDs.clear();
3022 listManager.getSelectedNotebooks().clear();
3023 listManager.getSelectedTags().clear();
3024 listManager.setSelectedSavedSearch("");
3025 browserWindow.clear();
3027 // toggle the add buttons
3028 newButton.setEnabled(!newButton.isEnabled());
3029 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3030 menuBar.noteAdd.setVisible(true);
3032 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3033 if (selections.size() == 0) {
3034 currentNoteGuid = trashNoteGuid;
3035 trashNoteGuid = tempGuid;
3036 Global.showDeleted = false;
3037 menuBar.noteRestoreAction.setEnabled(false);
3038 menuBar.noteRestoreAction.setVisible(false);
3041 currentNoteGuid = trashNoteGuid;
3042 trashNoteGuid = tempGuid;
3043 menuBar.noteRestoreAction.setEnabled(true);
3044 menuBar.noteRestoreAction.setVisible(true);
3045 Global.showDeleted = true;
3047 listManager.loadNotesIndex();
3048 noteIndexUpdated(false);
3049 //// browserWindow.setEnabled(newButton.isEnabled());
3050 browserWindow.setReadOnly(!newButton.isEnabled());
3051 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3053 // Empty the trash file
3054 @SuppressWarnings("unused")
3055 private void emptyTrash() {
3056 // browserWindow.clear();
3057 listManager.emptyTrash();
3058 if (trashTree.selectedItems().size() > 0) {
3059 listManager.getSelectedNotebooks().clear();
3060 listManager.getSelectedTags().clear();
3061 listManager.setSelectedSavedSearch("");
3062 newButton.setEnabled(!newButton.isEnabled());
3063 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3064 menuBar.noteAdd.setVisible(true);
3065 browserWindow.clear();
3068 clearNotebookFilter();
3069 clearSavedSearchFilter();
3070 clearAttributeFilter();
3072 Global.showDeleted = false;
3073 menuBar.noteRestoreAction.setEnabled(false);
3074 menuBar.noteRestoreAction.setVisible(false);
3076 listManager.loadNotesIndex();
3077 //--->>> noteIndexUpdated(true);
3078 noteIndexUpdated(false);
3081 // Show/Hide trash window
3082 private void toggleTrashWindow() {
3083 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3084 if (trashTree.isVisible())
3088 menuBar.hideTrash.setChecked(trashTree.isVisible());
3090 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3091 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3093 private void clearTrashFilter() {
3094 Global.showDeleted = false;
3095 newButton.setEnabled(true);
3096 menuBar.noteAdd.setEnabled(true);
3097 menuBar.noteAdd.setVisible(true);
3098 trashTree.blockSignals(true);
3099 trashTree.clearSelection();
3100 trashTree.blockSignals(false);
3105 //***************************************************************
3106 //***************************************************************
3107 //** These functions deal with connection settings
3108 //***************************************************************
3109 //***************************************************************
3110 // SyncRunner had a problem and things are disconnected
3111 @SuppressWarnings("unused")
3112 private void remoteErrorDisconnect() {
3113 menuBar.connectAction.setText(tr("Connect"));
3114 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3115 menuBar.synchronizeAction.setEnabled(false);
3116 Global.isConnected = false;
3117 synchronizeAnimationTimer.stop();
3120 // Do a manual connect/disconnect
3121 private void remoteConnect() {
3122 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3124 if (Global.isConnected) {
3125 Global.isConnected = false;
3126 syncRunner.enDisconnect();
3127 setupConnectMenuOptions();
3132 AESEncrypter aes = new AESEncrypter();
3134 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3135 } catch (FileNotFoundException e) {
3136 // File not found, so we'll just get empty strings anyway.
3138 String userid = aes.getUserid();
3139 String password = aes.getPassword();
3140 if (!userid.equals("") && !password.equals("")) {
3141 Global.username = userid;
3142 Global.password = password;
3145 // Show the login dialog box
3146 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3147 LoginDialog login = new LoginDialog();
3150 if (!login.okPressed()) {
3154 Global.username = login.getUserid();
3155 Global.password = login.getPassword();
3157 syncRunner.username = Global.username;
3158 syncRunner.password = Global.password;
3159 syncRunner.userStoreUrl = Global.userStoreUrl;
3160 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3161 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3163 if (Global.getProxyValue("url").equals("")) {
3164 System.setProperty("http.proxyHost","") ;
3165 System.setProperty("http.proxyPort", "") ;
3166 System.setProperty("https.proxyHost","") ;
3167 System.setProperty("https.proxyPort", "") ;
3170 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3171 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3172 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3173 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3175 if (Global.getProxyValue("userid").equals("")) {
3176 Authenticator.setDefault(new Authenticator() {
3178 protected PasswordAuthentication getPasswordAuthentication() {
3180 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3186 syncRunner.enConnect();
3187 Global.isConnected = syncRunner.isConnected;
3189 setupConnectMenuOptions();
3190 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3192 private void setupConnectMenuOptions() {
3193 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3194 if (!Global.isConnected) {
3195 menuBar.connectAction.setText(tr("Connect"));
3196 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3197 menuBar.synchronizeAction.setEnabled(false);
3199 menuBar.connectAction.setText(tr("Disconnect"));
3200 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3201 menuBar.synchronizeAction.setEnabled(true);
3203 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3208 //***************************************************************
3209 //***************************************************************
3210 //** These functions deal with the GUI Attribute tree
3211 //***************************************************************
3212 //***************************************************************
3213 @SuppressWarnings("unused")
3214 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3216 // clearTagFilter();
3217 // clearNotebookFilter();
3219 // clearSavedSearchFilter();
3221 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3222 if (item.childCount() > 0) {
3223 item.setSelected(false);
3225 Global.createdBeforeFilter.reset();
3226 Global.createdSinceFilter.reset();
3227 Global.changedBeforeFilter.reset();
3228 Global.changedSinceFilter.reset();
3229 Global.containsFilter.reset();
3230 attributeTreeSelected = item;
3231 DateAttributeFilterTable f = null;
3232 f = findDateAttributeFilterTable(item.parent());
3234 f.select(item.parent().indexOfChild(item));
3236 Global.containsFilter.select(item.parent().indexOfChild(item));
3239 listManager.loadNotesIndex();
3240 noteIndexUpdated(false);
3243 attributeTreeSelected = null;
3244 item.setSelected(false);
3245 Global.createdBeforeFilter.reset();
3246 Global.createdSinceFilter.reset();
3247 Global.changedBeforeFilter.reset();
3248 Global.changedSinceFilter.reset();
3249 Global.containsFilter.reset();
3250 listManager.loadNotesIndex();
3251 noteIndexUpdated(false);
3253 // This determines what attribute filter we need, depending upon the selection
3254 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3255 if (w.parent() != null && w.childCount() > 0) {
3256 QTreeWidgetItem parent = w.parent();
3257 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3258 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3259 return Global.createdSinceFilter;
3260 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3261 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3262 return Global.createdBeforeFilter;
3263 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3264 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3265 return Global.changedSinceFilter;
3266 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3267 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3268 return Global.changedBeforeFilter;
3273 // Show/Hide attribute search window
3274 private void toggleAttributesWindow() {
3275 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3276 if (attributeTree.isVisible())
3277 attributeTree.hide();
3279 attributeTree.show();
3280 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3282 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3283 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3285 private void clearAttributeFilter() {
3286 Global.createdBeforeFilter.reset();
3287 Global.createdSinceFilter.reset();
3288 Global.changedBeforeFilter.reset();
3289 Global.changedSinceFilter.reset();
3290 Global.containsFilter.reset();
3291 attributeTreeSelected = null;
3292 attributeTree.blockSignals(true);
3293 attributeTree.clearSelection();
3294 attributeTree.blockSignals(false);
3298 //***************************************************************
3299 //***************************************************************
3300 //** These functions deal with the GUI Note index table
3301 //***************************************************************
3302 //***************************************************************
3303 // Initialize the note list table
3304 private void initializeNoteTable() {
3305 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3306 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3307 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3308 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3310 // Show/Hide trash window
3311 @SuppressWarnings("unused")
3312 private void toggleNoteListWindow() {
3313 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3314 if (noteTableView.isVisible())
3315 noteTableView.hide();
3317 noteTableView.show();
3318 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3320 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3321 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3323 // Handle the event that a user selects a note from the table
3324 @SuppressWarnings("unused")
3325 private void noteTableSelection() {
3326 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3328 if (historyGuids.size() == 0) {
3329 historyGuids.add(currentNoteGuid);
3330 historyPosition = 1;
3332 noteTableView.showColumn(Global.noteTableGuidPosition);
3334 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3335 if (!Global.isColumnVisible("guid"))
3336 noteTableView.hideColumn(Global.noteTableGuidPosition);
3338 if (selections.size() > 0) {
3340 menuBar.noteDuplicateAction.setEnabled(true);
3341 menuBar.noteOnlineHistoryAction.setEnabled(true);
3342 menuBar.noteMergeAction.setEnabled(true);
3343 selectedNoteGUIDs.clear();
3344 if (selections.size() != 1 || Global.showDeleted) {
3345 menuBar.noteDuplicateAction.setEnabled(false);
3347 if (selections.size() != 1 || !Global.isConnected) {
3348 menuBar.noteOnlineHistoryAction.setEnabled(false);
3350 if (selections.size() == 1) {
3351 menuBar.noteMergeAction.setEnabled(false);
3353 for (int i=0; i<selections.size(); i++) {
3354 int row = selections.get(i).row();
3356 upButton.setEnabled(false);
3358 upButton.setEnabled(true);
3359 if (row < listManager.getNoteTableModel().rowCount()-1)
3360 downButton.setEnabled(true);
3362 downButton.setEnabled(false);
3363 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3364 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3365 currentNoteGuid = (String)ix.values().toArray()[0];
3366 selectedNoteGUIDs.add(currentNoteGuid);
3370 nextButton.setEnabled(true);
3371 prevButton.setEnabled(true);
3373 int endPosition = historyGuids.size()-1;
3374 for (int j=historyPosition; j<=endPosition; j++) {
3375 historyGuids.remove(historyGuids.size()-1);
3377 historyGuids.add(currentNoteGuid);
3378 historyPosition = historyGuids.size();
3380 if (historyPosition <= 1)
3381 prevButton.setEnabled(false);
3382 if (historyPosition == historyGuids.size())
3383 nextButton.setEnabled(false);
3385 fromHistory = false;
3386 scrollToGuid(currentNoteGuid);
3387 refreshEvernoteNote(true);
3388 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3390 // Trigger a refresh when the note db has been updated
3391 private void noteIndexUpdated(boolean reload) {
3392 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3394 refreshEvernoteNoteList();
3395 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3396 noteTableView.load(reload);
3397 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3399 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3400 pos = noteTableView.proxyModel.rowCount();
3403 if (noteTableView.proxyModel.rowCount() == 0)
3406 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3408 currentNoteGuid = (String)i.data();
3409 noteTableView.selectRow(pos-1);
3414 scrollToGuid(currentNoteGuid);
3415 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3417 // Called when the list of notes is updated
3418 private void refreshEvernoteNoteList() {
3419 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3420 browserWindow.setDisabled(false);
3421 if (selectedNoteGUIDs == null)
3422 selectedNoteGUIDs = new ArrayList<String>();
3423 selectedNoteGUIDs.clear(); // clear out old entries
3425 String saveCurrentNoteGuid = new String();
3426 String tempNoteGuid = new String();
3428 historyGuids.clear();
3429 historyPosition = 0;
3430 prevButton.setEnabled(false);
3431 nextButton.setEnabled(false);
3433 if (currentNoteGuid == null)
3434 currentNoteGuid = new String();
3436 //determine current note guid
3437 for (Note note : listManager.getNoteIndex()) {
3438 tempNoteGuid = note.getGuid();
3439 if (currentNoteGuid.equals(tempNoteGuid)) {
3440 saveCurrentNoteGuid = tempNoteGuid;
3444 if (listManager.getNoteIndex().size() == 0) {
3445 currentNoteGuid = "";
3447 browserWindow.clear();
3448 browserWindow.setDisabled(true);
3451 if (!saveCurrentNoteGuid.equals("")) {
3452 refreshEvernoteNote(false);
3454 currentNoteGuid = "";
3456 reloadTagTree(false);
3458 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3460 // Called when the previous arrow button is clicked
3461 @SuppressWarnings("unused")
3462 private void previousViewedAction() {
3463 if (!prevButton.isEnabled())
3465 if (historyPosition == 0)
3468 if (historyPosition <= 0)
3470 String historyGuid = historyGuids.get(historyPosition-1);
3472 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3473 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3474 if (modelIndex != null) {
3475 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3476 String tableGuid = (String)ix.values().toArray()[0];
3477 if (tableGuid.equals(historyGuid)) {
3478 noteTableView.selectRow(i);
3484 @SuppressWarnings("unused")
3485 private void nextViewedAction() {
3486 if (!nextButton.isEnabled())
3488 String historyGuid = historyGuids.get(historyPosition);
3491 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3492 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3493 if (modelIndex != null) {
3494 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3495 String tableGuid = (String)ix.values().toArray()[0];
3496 if (tableGuid.equals(historyGuid)) {
3497 noteTableView.selectRow(i);
3503 // Called when the up arrow is clicked
3504 @SuppressWarnings("unused")
3505 private void upAction() {
3506 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3507 int row = selections.get(0).row();
3509 noteTableView.selectRow(row-1);
3512 // Called when the down arrow is clicked
3513 @SuppressWarnings("unused")
3514 private void downAction() {
3515 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3516 int row = selections.get(0).row();
3517 int max = listManager.getNoteTableModel().rowCount();
3519 noteTableView.selectRow(row+1);
3522 // Update a tag string for a specific note in the list
3523 @SuppressWarnings("unused")
3524 private void updateListTags(String guid, List<String> tags) {
3525 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3526 StringBuffer tagBuffer = new StringBuffer();
3527 for (int i=0; i<tags.size(); i++) {
3528 tagBuffer.append(tags.get(i));
3529 if (i<tags.size()-1)
3530 tagBuffer.append(", ");
3533 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3534 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3535 if (modelIndex != null) {
3536 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3537 String tableGuid = (String)ix.values().toArray()[0];
3538 if (tableGuid.equals(guid)) {
3539 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3540 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3541 noteTableView.proxyModel.invalidate();
3546 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3548 // Update a title for a specific note in the list
3549 @SuppressWarnings("unused")
3550 private void updateListAuthor(String guid, String author) {
3551 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3553 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3554 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3555 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3556 if (modelIndex != null) {
3557 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3558 String tableGuid = (String)ix.values().toArray()[0];
3559 if (tableGuid.equals(guid)) {
3560 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3561 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3562 noteTableView.proxyModel.invalidate();
3568 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3570 private void updateListNoteNotebook(String guid, String notebook) {
3571 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3572 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3573 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3575 // Update a title for a specific note in the list
3576 @SuppressWarnings("unused")
3577 private void updateListSourceUrl(String guid, String url) {
3578 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3580 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3581 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3582 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3583 if (modelIndex != null) {
3584 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3585 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3586 String tableGuid = (String)ix.values().toArray()[0];
3587 if (tableGuid.equals(guid)) {
3588 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3589 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3590 noteTableView.proxyModel.invalidate();
3595 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3597 @SuppressWarnings("unused")
3598 private void updateListGuid(String oldGuid, String newGuid) {
3599 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3601 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3602 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3603 if (modelIndex != null) {
3604 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3605 String tableGuid = (String)ix.values().toArray()[0];
3606 if (tableGuid.equals(oldGuid)) {
3607 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3608 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3613 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3615 private void updateListTagName(String guid) {
3616 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3618 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3619 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3620 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3622 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3623 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3624 if (modelIndex != null) {
3625 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3626 String noteGuid = (String)ix.values().toArray()[0];
3627 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3628 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3629 i=listManager.getNoteTableModel().rowCount();
3635 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3637 private void removeListTagName(String guid) {
3638 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3640 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3641 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3642 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3643 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3644 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3647 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3648 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3649 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3650 if (modelIndex != null) {
3651 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3652 String noteGuid = (String)ix.values().toArray()[0];
3653 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3654 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3655 i=listManager.getNoteTableModel().rowCount();
3661 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3663 private void updateListNotebookName(String oldName, String newName) {
3664 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3666 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3667 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3668 if (modelIndex != null) {
3669 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3670 String tableName = (String)ix.values().toArray()[0];
3671 if (tableName.equalsIgnoreCase(oldName)) {
3672 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3676 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3678 @SuppressWarnings("unused")
3679 private void updateListDateCreated(String guid, QDateTime date) {
3680 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3682 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3683 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3684 if (modelIndex != null) {
3685 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3686 String tableGuid = (String)ix.values().toArray()[0];
3687 if (tableGuid.equals(guid)) {
3688 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3689 noteTableView.proxyModel.invalidate();
3694 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3696 @SuppressWarnings("unused")
3697 private void updateListDateSubject(String guid, QDateTime date) {
3698 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3700 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3701 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3702 if (modelIndex != null) {
3703 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3704 String tableGuid = (String)ix.values().toArray()[0];
3705 if (tableGuid.equals(guid)) {
3706 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3707 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3708 noteTableView.proxyModel.invalidate();
3713 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3715 private void updateListDateChanged(String guid, QDateTime date) {
3716 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3718 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3719 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3720 if (modelIndex != null) {
3721 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3722 String tableGuid = (String)ix.values().toArray()[0];
3723 if (tableGuid.equals(guid)) {
3724 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3725 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3730 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3732 private void updateListDateChanged() {
3733 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3734 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3735 updateListDateChanged(currentNoteGuid, date);
3736 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3739 private void scrollToCurrentGuid() {
3740 //scrollToGuid(currentNoteGuid);
3741 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3742 if (selections.size() == 0)
3744 QModelIndex index = selections.get(0);
3745 int row = selections.get(0).row();
3746 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3749 // Scroll to a particular index item
3750 private void scrollToGuid(String guid) {
3751 if (currentNote == null || guid == null)
3753 if (currentNote.isActive() && Global.showDeleted) {
3754 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3755 if (!listManager.getNoteIndex().get(i).isActive()) {
3756 currentNote = listManager.getNoteIndex().get(i);
3757 currentNoteGuid = currentNote.getGuid();
3758 i = listManager.getNoteIndex().size();
3763 if (!currentNote.isActive() && !Global.showDeleted) {
3764 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3765 if (listManager.getNoteIndex().get(i).isActive()) {
3766 currentNote = listManager.getNoteIndex().get(i);
3767 currentNoteGuid = currentNote.getGuid();
3768 i = listManager.getNoteIndex().size();
3774 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3775 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3776 if (currentNoteGuid.equals(index.data())) {
3777 // noteTableView.setCurrentIndex(index);
3778 noteTableView.selectRow(i);
3779 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3780 i=listManager.getNoteTableModel().rowCount();
3783 noteTableView.repaint();
3785 // Show/Hide columns
3786 private void showColumns() {
3787 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3788 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3789 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3790 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3791 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3792 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3793 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3794 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3795 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3796 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3797 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3799 // Title color has changed
3800 @SuppressWarnings("unused")
3801 private void titleColorChanged(Integer color) {
3802 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3804 QColor backgroundColor = new QColor();
3805 QColor foregroundColor = new QColor(QColor.black);
3806 backgroundColor.setRgb(color);
3808 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3809 foregroundColor.setRgb(QColor.white.rgb());
3811 if (selectedNoteGUIDs.size() == 0)
3812 selectedNoteGUIDs.add(currentNoteGuid);
3814 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3815 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3816 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3817 if (modelIndex != null) {
3818 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3819 String tableGuid = (String)ix.values().toArray()[0];
3820 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3821 for (int k=0; k<Global.noteTableColumnCount; k++) {
3822 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3823 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3824 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3826 i=listManager.getNoteTableModel().rowCount();
3831 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3833 // Wide list was chosen
3834 public void narrowListView() {
3835 saveNoteColumnPositions();
3836 saveNoteIndexWidth();
3838 int sortCol = noteTableView.proxyModel.sortColumn();
3839 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3840 Global.setSortColumn(sortCol);
3841 Global.setSortOrder(sortOrder);
3843 Global.setListView(Global.View_List_Narrow);
3845 menuBar.wideListView.blockSignals(true);
3846 menuBar.narrowListView.blockSignals(true);
3848 menuBar.wideListView.setChecked(false);
3849 menuBar.narrowListView.setChecked(true);
3851 menuBar.wideListView.blockSignals(false);
3852 menuBar.narrowListView.blockSignals(false);
3854 mainLeftRightSplitter.addWidget(noteTableView);
3855 mainLeftRightSplitter.addWidget(browserWindow);
3856 restoreWindowState(false);
3857 noteTableView.repositionColumns();
3858 noteTableView.resizeColumnWidths();
3859 noteTableView.resizeRowHeights();
3861 sortCol = Global.getSortColumn();
3862 sortOrder = Global.getSortOrder();
3863 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3866 noteTableView.load(false);
3867 scrollToCurrentGuid();
3869 public void wideListView() {
3870 int sortCol = noteTableView.proxyModel.sortColumn();
3871 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3872 Global.setSortColumn(sortCol);
3873 Global.setSortOrder(sortOrder);
3876 saveNoteColumnPositions();
3877 saveNoteIndexWidth();
3878 Global.setListView(Global.View_List_Wide);
3880 menuBar.wideListView.blockSignals(true);
3881 menuBar.narrowListView.blockSignals(true);
3883 menuBar.wideListView.setChecked(true);
3884 menuBar.narrowListView.setChecked(false);
3886 menuBar.wideListView.blockSignals(false);
3887 menuBar.narrowListView.blockSignals(false);
3888 browserIndexSplitter.setVisible(true);
3889 browserIndexSplitter.addWidget(noteTableView);
3890 browserIndexSplitter.addWidget(browserWindow);
3891 restoreWindowState(false);
3892 noteTableView.repositionColumns();
3893 noteTableView.resizeColumnWidths();
3894 noteTableView.resizeRowHeights();
3896 sortCol = Global.getSortColumn();
3897 sortOrder = Global.getSortOrder();
3898 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3901 noteTableView.load(false);
3902 scrollToCurrentGuid();
3906 //***************************************************************
3907 //***************************************************************
3908 //** External editor window functions
3909 //***************************************************************
3910 //***************************************************************
3911 private void listDoubleClick() {
3913 if (externalWindows.containsKey(currentNoteGuid)) {
3914 externalWindows.get(currentNoteGuid).raise();
3917 // We have a new external editor to create
3918 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3919 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3920 newBrowser.setWindowIcon(appIcon);
3921 externalWindows.put(currentNoteGuid, newBrowser);
3922 showEditorButtons(newBrowser.getBrowserWindow());
3923 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3924 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3925 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3926 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3927 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3928 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3930 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3931 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3932 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3936 @SuppressWarnings("unused")
3937 private void externalWindowTitleEdited(String guid, String text) {
3938 if (guid.equals(currentNoteGuid)) {
3939 browserWindow.setTitle(text);
3942 @SuppressWarnings({ "rawtypes", "unused" })
3943 private void externalWindowTagsEdited(String guid, List values) {
3944 StringBuffer line = new StringBuffer(100);
3945 for (int i=0; i<values.size(); i++) {
3947 line.append(Global.tagDelimeter+" ");
3948 line.append(values.get(i));
3950 if (guid.equals(currentNoteGuid)) {
3951 browserWindow.setTag(line.toString());
3954 @SuppressWarnings("unused")
3955 private void externalWindowClosing(String guid) {
3956 externalWindows.remove(guid);
3961 //***************************************************************
3962 //***************************************************************
3963 //** These functions deal with Note specific things
3964 //***************************************************************
3965 //***************************************************************
3966 @SuppressWarnings("unused")
3967 private void setNoteDirty() {
3968 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
3970 // Find if the note is being edited externally. If it is, update it.
3971 if (externalWindows.containsKey(currentNoteGuid)) {
3972 QTextCodec codec = QTextCodec.codecForName("UTF-8");
3973 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
3974 ExternalBrowse window = externalWindows.get(currentNoteGuid);
3975 window.getBrowserWindow().getBrowser().setContent(unicode);
3978 // If the note is dirty, then it is unsynchronized by default.
3982 // Set the note as dirty and check if its status is synchronized in the display table
3984 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
3985 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
3989 // If this wasn't already marked as unsynchronized, then we need to update the table
3990 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
3991 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
3992 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3993 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3994 if (modelIndex != null) {
3995 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3996 String tableGuid = (String)ix.values().toArray()[0];
3997 if (tableGuid.equals(currentNoteGuid)) {
3998 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4004 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4006 @SuppressWarnings("unused")
4007 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4008 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4009 QByteArray unicode = codec.fromUnicode(content);
4010 noteCache.remove(guid);
4011 noteCache.put(guid, unicode.toString());
4012 if (guid.equals(currentNoteGuid)) {
4014 browserWindow.getBrowser().setContent(unicode);
4017 thumbnailRunner.addWork("GENERATE "+ guid);
4018 saveNote(guid, browser);
4022 private void saveNote() {
4024 saveNote(currentNoteGuid, browserWindow);
4025 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4029 private void saveNote(String guid, BrowserWindow window) {
4030 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4031 logger.log(logger.EXTREME, "Note is dirty.");
4034 logger.log(logger.EXTREME, "Saving to cache");
4035 QTextCodec codec = QTextCodec.codecForLocale();
4036 // QTextDecoder decoder = codec.makeDecoder();
4037 codec = QTextCodec.codecForName("UTF-8");
4038 QByteArray unicode = codec.fromUnicode(window.getContent());
4039 noteCache.put(guid, unicode.toString());
4041 logger.log(logger.EXTREME, "updating list manager");
4042 listManager.updateNoteContent(guid, window.getContent());
4043 logger.log(logger.EXTREME, "Updating title");
4044 listManager.updateNoteTitle(guid, window.getTitle());
4045 updateListDateChanged();
4047 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4048 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4049 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4050 currentNote = listManager.getNoteIndex().get(i);
4051 i = listManager.getNoteIndex().size();
4056 // Get a note from Evernote (and put it in the browser)
4057 private void refreshEvernoteNote(boolean reload) {
4058 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4060 if (Global.disableViewing) {
4061 browserWindow.setEnabled(false);
4066 if (Global.showDeleted)
4068 Global.cryptCounter =0;
4069 if (currentNoteGuid.equals("")) {
4070 browserWindow.setReadOnly(true);
4078 browserWindow.loadingData(true);
4080 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4081 if (currentNote == null)
4084 loadNoteBrowserInformation(browserWindow);
4087 private void loadNoteBrowserInformation(BrowserWindow browser) {
4088 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4089 formatter.setNote(currentNote, Global.pdfPreview());
4090 formatter.setHighlight(listManager.getEnSearch());
4092 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4093 js = new QByteArray();
4094 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4095 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4096 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>");
4097 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4098 js.append("<style> img { max-width:100%; }</style>");
4099 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4100 js.append("</head>");
4101 formatter.setNote(currentNote, Global.pdfPreview());
4102 js.append(formatter.rebuildNoteHTML());
4103 js.append("</HTML>");
4104 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4105 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4106 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4107 browser.getBrowser().setContent(js);
4108 noteCache.put(currentNoteGuid, js.toString());
4110 if (formatter.resourceError)
4111 resourceErrorMessage();
4112 readOnly = formatter.readOnly;
4113 inkNote = formatter.inkNote;
4115 readOnlyCache.put(currentNoteGuid, true);
4117 inkNoteCache.put(currentNoteGuid, true);
4119 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4120 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4121 js = new QByteArray(cachedContent);
4122 browser.getBrowser().setContent(js);
4123 if (readOnlyCache.containsKey(currentNoteGuid))
4125 if (inkNoteCache.containsKey(currentNoteGuid))
4128 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4129 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4132 if (readOnly || inkNote)
4133 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4135 browser.getBrowser().page().setContentEditable(true);
4136 browser.setReadOnly(readOnly);
4137 deleteButton.setEnabled(!readOnly);
4138 tagButton.setEnabled(!readOnly);
4139 menuBar.noteDelete.setEnabled(!readOnly);
4140 menuBar.noteTags.setEnabled(!readOnly);
4141 browser.setNote(currentNote);
4143 if (conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4144 deleteButton.setEnabled(false);
4145 menuBar.notebookDeleteAction.setEnabled(false);
4147 deleteButton.setEnabled(true);
4148 menuBar.notebookDeleteAction.setEnabled(true);
4151 // Build a list of non-closed notebooks
4152 List<Notebook> nbooks = new ArrayList<Notebook>();
4153 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4154 boolean found=false;
4155 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4156 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4160 nbooks.add(listManager.getNotebookIndex().get(i));
4163 browser.setTitle(currentNote.getTitle());
4164 browser.setTag(getTagNamesForNote(currentNote));
4165 browser.setAuthor(currentNote.getAttributes().getAuthor());
4167 browser.setAltered(currentNote.getUpdated());
4168 browser.setCreation(currentNote.getCreated());
4169 if (currentNote.getAttributes().getSubjectDate() > 0)
4170 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4172 browser.setSubjectDate(currentNote.getCreated());
4173 browser.setUrl(currentNote.getAttributes().getSourceURL());
4175 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4176 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4177 browser.setAllTags(tagList);
4179 browser.setCurrentTags(currentNote.getTagNames());
4181 scrollToGuid(currentNoteGuid);
4183 browser.loadingData(false);
4184 if (thumbnailViewer.isActiveWindow())
4187 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4188 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4191 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4193 // Save a generated thumbnail
4194 private void toggleNoteInformation() {
4195 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4196 browserWindow.toggleInformation();
4197 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4198 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4199 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4201 // Listener triggered when a print button is pressed
4202 @SuppressWarnings("unused")
4203 private void printNote() {
4204 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4206 QPrintDialog dialog = new QPrintDialog();
4207 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4208 QPrinter printer = dialog.printer();
4209 browserWindow.getBrowser().print(printer);
4211 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4214 // Listener triggered when the email button is pressed
4215 @SuppressWarnings("unused")
4216 private void emailNote() {
4217 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4219 if (Desktop.isDesktopSupported()) {
4220 Desktop desktop = Desktop.getDesktop();
4222 String text2 = browserWindow.getContentsToEmail();
4223 QUrl url = new QUrl("mailto:");
4224 url.addQueryItem("subject", currentNote.getTitle());
4225 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4226 url.addQueryItem("body", text2);
4227 QDesktopServices.openUrl(url);
4231 if (desktop.isSupported(Desktop.Action.MAIL)) {
4232 URI uriMailTo = null;
4234 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4235 String text = browserWindow.getContentsToEmail();
4236 //text = "<b>" +text +"</b>";
4237 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4238 +"&BODY=" +text, null);
4239 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4240 +"&ATTACHMENT=d:/test.pdf", null);
4241 desktop.mail(uriMailTo);
4242 } catch (URISyntaxException e) {
4243 e.printStackTrace();
4244 } catch (IOException e) {
4245 e.printStackTrace();
4252 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4254 // Reindex all notes
4255 @SuppressWarnings("unused")
4256 private void fullReindex() {
4257 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4258 indexRunner.addWork("REINDEXALL");
4259 setMessage(tr("Database will be reindexed."));
4260 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4262 // Listener when a user wants to reindex a specific note
4263 @SuppressWarnings("unused")
4264 private void reindexNote() {
4265 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4266 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4267 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4269 if (selectedNotebookGUIDs.size() > 1)
4270 setMessage(tr("Notes will be reindexed."));
4272 setMessage(tr("Note will be reindexed."));
4273 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4276 @SuppressWarnings("unused")
4277 private void deleteNote() {
4278 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4279 if (currentNote == null)
4281 if (currentNoteGuid.equals(""))
4284 // If we are deleting non-trash notes
4285 if (currentNote.isActive()) {
4286 if (Global.verifyDelete()) {
4287 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4288 QMessageBox.StandardButton.Yes,
4289 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4293 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4294 selectedNoteGUIDs.add(currentNoteGuid);
4295 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4296 listManager.deleteNote(selectedNoteGUIDs.get(i));
4299 // If we are deleting from the trash.
4300 if (Global.verifyDelete()) {
4301 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4302 QMessageBox.StandardButton.Yes,
4303 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4307 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4308 selectedNoteGUIDs.add(currentNoteGuid);
4309 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4310 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4311 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4312 if (modelIndex != null) {
4313 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4314 String tableGuid = (String)ix.values().toArray()[0];
4315 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4316 listManager.getNoteTableModel().removeRow(j);
4321 listManager.expungeNote(selectedNoteGUIDs.get(i));
4324 currentNoteGuid = "";
4325 listManager.loadNotesIndex();
4326 noteIndexUpdated(false);
4327 refreshEvernoteNote(true);
4328 scrollToGuid(currentNoteGuid);
4329 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4332 @SuppressWarnings("unused")
4333 private void addNote() {
4334 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4335 // browserWindow.setEnabled(true);
4336 browserWindow.setReadOnly(false);
4338 Calendar currentTime = new GregorianCalendar();
4339 StringBuffer noteString = new StringBuffer(100);
4340 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4341 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4344 if (Global.overrideDefaultFont()) {
4345 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4346 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4347 noteString.append("<br clear=\"none\" />\n");
4348 noteString.append("</span>\n</font>\n");
4350 noteString.append("<br clear=\"none\" />\n");
4351 noteString.append("</en-note>");
4353 Long l = new Long(currentTime.getTimeInMillis());
4354 String randint = new String(Long.toString(l));
4356 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4358 // for the first non-archived notebook. Finally, if nothing else we
4359 // pick the first notebook in the list.
4360 String notebook = null;
4361 listManager.getNotebookIndex().get(0).getGuid();
4362 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4363 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4364 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4365 notebook = currentSelectedNotebook.text(2);
4367 boolean found = false;
4368 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4369 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4370 boolean match = false;
4371 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4372 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4374 j = listManager.getArchiveNotebookIndex().size();
4378 goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4380 // Now we have a list of good notebooks, so we can look for the default
4382 for (int i=0; i<goodNotebooks.size(); i++) {
4383 if (goodNotebooks.get(i).isDefaultNotebook()) {
4384 notebook = goodNotebooks.get(i).getGuid();
4386 i = goodNotebooks.size();
4390 if (goodNotebooks.size() > 0 && !found)
4391 notebook = goodNotebooks.get(0).getGuid();
4394 notebook = listManager.getNotebookIndex().get(0).getGuid();
4397 Note newNote = new Note();
4398 newNote.setUpdateSequenceNum(0);
4399 newNote.setGuid(randint);
4400 newNote.setNotebookGuid(notebook);
4401 newNote.setTitle("");
4402 newNote.setContent(noteString.toString());
4403 newNote.setDeleted(0);
4404 newNote.setCreated(System.currentTimeMillis());
4405 newNote.setUpdated(System.currentTimeMillis());
4406 newNote.setActive(true);
4407 NoteAttributes na = new NoteAttributes();
4408 na.setLatitude(0.0);
4409 na.setLongitude(0.0);
4410 na.setAltitude(0.0);
4411 newNote.setAttributes(new NoteAttributes());
4412 newNote.setTagGuids(new ArrayList<String>());
4413 newNote.setTagNames(new ArrayList<String>());
4415 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4416 if (Global.newNoteWithSelectedTags()) {
4417 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4418 QTreeWidgetItem currentSelection;
4419 for (int i=0; i<selections.size(); i++) {
4420 currentSelection = selections.get(i);
4421 newNote.getTagGuids().add(currentSelection.text(2));
4422 newNote.getTagNames().add(currentSelection.text(0));
4426 conn.getNoteTable().addNote(newNote, true);
4427 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4428 listManager.addNote(newNote);
4429 // noteTableView.insertRow(newNote, true, -1);
4431 currentNote = newNote;
4432 currentNoteGuid = currentNote.getGuid();
4433 refreshEvernoteNote(true);
4434 listManager.countNotebookResults(listManager.getNoteIndex());
4435 browserWindow.titleLabel.setFocus();
4436 browserWindow.titleLabel.selectAll();
4437 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4439 // If the window is hidden, then we want to popup this in an external window &
4442 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4444 // Restore a note from the trash;
4445 @SuppressWarnings("unused")
4446 private void restoreNote() {
4448 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4449 selectedNoteGUIDs.add(currentNoteGuid);
4450 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4451 listManager.restoreNote(selectedNoteGUIDs.get(i));
4453 currentNoteGuid = "";
4454 listManager.loadNotesIndex();
4455 noteIndexUpdated(false);
4458 // Search a note for specific txt
4459 @SuppressWarnings("unused")
4460 private void findText() {
4462 find.setFocusOnTextField();
4464 @SuppressWarnings("unused")
4465 private void doFindText() {
4466 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4469 @SuppressWarnings("unused")
4470 private void updateNoteTitle(String guid, String title) {
4471 listManager.setNoteSynchronized(guid, false);
4473 // Signal received that note content has changed. Normally we just need the guid to remove
4474 // it from the cache.
4475 @SuppressWarnings("unused")
4476 private void invalidateNoteCache(String guid, String content) {
4477 String v = noteCache.remove(guid);
4478 // if (guid.equals(currentNoteGuid) && !noteDirty)
4479 refreshEvernoteNote(true);
4481 // Signal received that a note guid has changed
4482 @SuppressWarnings("unused")
4483 private void noteGuidChanged(String oldGuid, String newGuid) {
4484 if (noteCache.containsKey(oldGuid)) {
4485 if (!oldGuid.equals(currentNoteGuid)) {
4486 String cache = noteCache.get(oldGuid);
4487 noteCache.put(newGuid, cache);
4488 noteCache.remove(oldGuid);
4490 noteCache.remove(oldGuid);
4491 noteCache.put(newGuid, browserWindow.getContent());
4495 listManager.updateNoteGuid(oldGuid, newGuid, false);
4496 if (currentNoteGuid.equals(oldGuid)) {
4497 if (currentNote != null)
4498 currentNote.setGuid(newGuid);
4499 currentNoteGuid = newGuid;
4502 if (externalWindows.containsKey(oldGuid)) {
4503 ExternalBrowse b = externalWindows.get(oldGuid);
4504 externalWindows.remove(oldGuid);
4505 b.getBrowserWindow().getNote().setGuid(newGuid);
4506 externalWindows.put(newGuid, b);
4509 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4510 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4511 noteTableView.proxyModel.addGuid(newGuid);
4512 i=listManager.getNoteIndex().size();
4516 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4517 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4518 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4519 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4523 // Toggle the note editor button bar
4524 private void toggleEditorButtonBar() {
4525 if (browserWindow.buttonsVisible) {
4526 browserWindow.hideButtons();
4527 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4528 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4530 browserWindow.buttonsVisible = true;
4531 showEditorButtons(browserWindow);
4533 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4535 // Show editor buttons
4536 private void showEditorButtons(BrowserWindow browser) {
4537 browser.buttonLayout.setVisible(true);
4538 browser.undoAction.setVisible(false);
4540 browser.undoButton.setVisible(false);
4542 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4543 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4544 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4545 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4546 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4547 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4548 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4549 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4550 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4551 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4552 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4553 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4554 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4555 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4556 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4557 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4558 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4559 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4560 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4561 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4562 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4563 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4564 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4566 private void duplicateNote(String guid) {
4568 Note oldNote = conn.getNoteTable().getNote(guid, true, true, false, false, false);
4569 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4570 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4571 oldNote.setResources(resList);
4572 duplicateNote(oldNote);
4574 private void duplicateNote(Note oldNote) {
4576 // Now that we have a good notebook guid, we need to move the conflicting note
4577 // to the local notebook
4578 Calendar currentTime = new GregorianCalendar();
4579 Long l = new Long(currentTime.getTimeInMillis());
4580 String newGuid = new String(Long.toString(l));
4582 Note newNote = oldNote.deepCopy();
4583 newNote.setUpdateSequenceNum(0);
4584 newNote.setGuid(newGuid);
4585 newNote.setDeleted(0);
4586 newNote.setActive(true);
4587 List<Resource> resList = oldNote.getResources();
4588 if (resList == null)
4589 resList = new ArrayList<Resource>();
4591 for (int i=0; i<resList.size(); i++) {
4593 while (l == prevGuid) {
4594 currentTime = new GregorianCalendar();
4595 l = new Long(currentTime.getTimeInMillis());
4598 String newResGuid = new String(Long.toString(l));
4599 resList.get(i).setNoteGuid(newGuid);
4600 resList.get(i).setGuid(newResGuid);
4601 resList.get(i).setUpdateSequenceNum(0);
4602 resList.get(i).setActive(true);
4603 conn.getNoteTable().noteResourceTable.saveNoteResource(new Resource(resList.get(i).deepCopy()), true);
4605 newNote.setResources(resList);
4606 listManager.addNote(newNote);
4607 conn.getNoteTable().addNote(newNote, true);
4608 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4609 noteTableView.insertRow(newNote, true, -1);
4610 listManager.countNotebookResults(listManager.getNoteIndex());
4614 @SuppressWarnings("unused")
4615 private void allNotes() {
4616 clearAttributeFilter();
4617 clearNotebookFilter();
4618 clearSavedSearchFilter();
4621 searchField.clear();
4622 if (Global.mimicEvernoteInterface) {
4623 notebookTree.selectGuid("");
4625 notebookTreeSelection();
4628 @SuppressWarnings("unused")
4629 private void mergeNotes() {
4630 logger.log(logger.HIGH, "Merging notes");
4633 String masterGuid = null;
4634 List<String> sources = new ArrayList<String>();
4636 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4637 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4638 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4639 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4641 masterGuid = (String)ix.values().toArray()[0];
4643 sources.add((String)ix.values().toArray()[0]);
4646 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4647 logger.log(logger.EXTREME, "Children count: "+sources.size());
4648 mergeNoteContents(masterGuid, sources);
4649 currentNoteGuid = masterGuid;
4650 noteIndexUpdated(false);
4651 refreshEvernoteNote(true);
4654 private void mergeNoteContents(String targetGuid, List<String> sources) {
4655 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4656 String newContent = target.getContent();
4657 newContent = newContent.replace("</en-note>", "<br></br>");
4659 for (int i=0; i<sources.size(); i++) {
4660 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4661 if (source.isSetTitle()) {
4662 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4664 String sourceContent = source.getContent();
4665 logger.log(logger.EXTREME, "Merging contents into note");
4666 logger.log(logger.EXTREME, sourceContent);
4667 logger.log(logger.EXTREME, "End of content");
4668 int startOfNote = sourceContent.indexOf("<en-note>");
4669 sourceContent = sourceContent.substring(startOfNote+9);
4670 int endOfNote = sourceContent.indexOf("</en-note>");
4671 sourceContent = sourceContent.substring(0,endOfNote);
4672 newContent = newContent + sourceContent;
4673 logger.log(logger.EXTREME, "New note content");
4674 logger.log(logger.EXTREME, newContent);
4675 logger.log(logger.EXTREME, "End of content");
4676 for (int j=0; j<source.getResourcesSize(); j++) {
4677 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4678 Resource r = source.getResources().get(j);
4679 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4681 Calendar currentTime = new GregorianCalendar();
4682 Long l = new Long(currentTime.getTimeInMillis());
4686 while (l == prevGuid) {
4687 currentTime = new GregorianCalendar();
4688 l = new Long(currentTime.getTimeInMillis());
4690 String newResGuid = new String(Long.toString(l));
4691 newRes.setNoteGuid(targetGuid);
4692 newRes.setGuid(newResGuid);
4693 newRes.setUpdateSequenceNum(0);
4694 newRes.setActive(true);
4695 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4698 logger.log(logger.EXTREME, "Updating note");
4699 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4700 for (int i=0; i<sources.size(); i++) {
4701 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4702 listManager.deleteNote(sources.get(i));
4704 logger.log(logger.EXTREME, "Exiting merge note");
4706 // A resource within a note has had a guid change
4707 @SuppressWarnings("unused")
4708 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4709 if (!oldGuid.equals(newGuid))
4710 Global.resourceMap.put(oldGuid, newGuid);
4712 // View a thumbnail of the note
4713 public void thumbnailView() {
4715 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4716 QFile thumbnail = new QFile(thumbnailName);
4717 if (!thumbnail.exists()) {
4719 QImage img = new QImage();
4720 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4721 thumbnailViewer.setThumbnail(img);
4723 thumbnailViewer.setThumbnail(thumbnailName);
4724 if (!thumbnailViewer.isVisible())
4725 thumbnailViewer.showFullScreen();
4727 // An error happened while saving a note. Inform the user
4728 @SuppressWarnings("unused")
4729 private void saveRunnerError(String guid, String msg) {
4731 String title = "*Unknown*";
4732 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4733 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4734 title = listManager.getMasterNoteIndex().get(i).getTitle();
4735 i=listManager.getMasterNoteIndex().size();
4738 msg = "An error has happened while saving the note \"" +title+
4739 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4740 "As a result, changes to the note may not be saved properly in the database."+
4741 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4742 "\nbe lost. Please review the note to recover any critical data before restarting.";
4744 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4747 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4748 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4749 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4750 // Find an idle preview object
4751 for (int i=0; i<thumbGenerators.size(); i++) {
4752 if (thumbGenerators.get(i).mutex.tryLock()) {
4753 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4754 thumbGenerators.get(i).loadContent(guid, html, zoom);
4758 if (thumbGenerators.size() >= 1) {
4759 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4763 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4764 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4765 thumbGenerators.add(preview);
4767 if (preview.mutex.tryLock()) {
4768 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4769 preview.loadContent(guid, html, zoom);
4771 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4776 //**********************************************************
4777 //**********************************************************
4778 //* Online user actions
4779 //**********************************************************
4780 //**********************************************************
4781 private void setupOnlineMenu() {
4782 if (!Global.isConnected) {
4783 menuBar.noteOnlineHistoryAction.setEnabled(false);
4784 menuBar.selectiveSyncAction.setEnabled(false);
4787 menuBar.noteOnlineHistoryAction.setEnabled(true);
4788 menuBar.selectiveSyncAction.setEnabled(true);
4791 @SuppressWarnings("unused")
4792 private void viewNoteHistory() {
4793 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4795 if (currentNote.getUpdateSequenceNum() == 0) {
4796 setMessage(tr("Note has never been synchronized."));
4797 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4801 setMessage(tr("Getting Note History"));
4803 Note currentOnlineNote = null;
4806 if (Global.isPremium())
4807 versions = syncRunner.noteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4809 versions = new ArrayList<NoteVersionId>();
4810 currentOnlineNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4811 } catch (EDAMUserException e) {
4812 setMessage("EDAMUserException: " +e.getMessage());
4814 } catch (EDAMSystemException e) {
4815 setMessage("EDAMSystemException: " +e.getMessage());
4817 } catch (EDAMNotFoundException e) {
4818 setMessage(tr("Note not found on server."));
4819 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4821 } catch (TException e) {
4822 setMessage("EDAMTransactionException: " +e.getMessage());
4826 // If we've gotten this far, we have a good note.
4827 if (historyWindow == null) {
4828 historyWindow = new OnlineNoteHistory(logger, conn);
4829 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4830 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4831 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4833 historyWindow.historyCombo.clear();
4835 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4836 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4838 historyWindow.setCurrent(isDirty);
4840 loadHistoryWindowContent(currentOnlineNote);
4841 historyWindow.load(versions);
4842 setMessage(tr("History retrieved"));
4844 historyWindow.exec();
4846 private Note reloadHistoryWindow(String selection) {
4848 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4849 String dateTimeFormat = new String(fmt);
4850 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4854 for (int i=0; i<versions.size(); i++) {
4855 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4856 if (versionDate.toString().equals(selection))
4860 if (index > -1 || selection.indexOf("Current") > -1) {
4861 Note historyNote = null;
4864 usn = versions.get(index).getUpdateSequenceNum();
4865 historyNote = syncRunner.noteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4867 historyNote = syncRunner.noteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4868 } catch (EDAMUserException e) {
4869 setMessage("EDAMUserException: " +e.getMessage());
4872 } catch (EDAMSystemException e) {
4873 setMessage("EDAMSystemException: " +e.getMessage());
4876 } catch (EDAMNotFoundException e) {
4877 setMessage("EDAMNotFoundException: " +e.getMessage());
4880 } catch (TException e) {
4881 setMessage("EDAMTransactionException: " +e.getMessage());
4887 if (historyNote != null)
4888 historyWindow.setContent(historyNote);
4894 private void loadHistoryWindowContent(Note note) {
4895 note.setUpdateSequenceNum(0);
4896 historyWindow.setContent(note);
4898 @SuppressWarnings("unused")
4899 private void restoreHistoryNoteAsNew() {
4900 setMessage(tr("Restoring as new note."));
4901 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4902 setMessage(tr("Note has been restored as a new note."));
4904 @SuppressWarnings("unused")
4905 private void restoreHistoryNote() {
4906 setMessage(tr("Restoring note."));
4907 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
4908 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
4911 for (int i=0; i<n.getResourcesSize(); i++) {
4912 n.getResources().get(i).setActive(true);
4913 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
4915 listManager.addNote(n);
4916 conn.getNoteTable().addNote(n, true);
4917 refreshEvernoteNote(true);
4918 setMessage(tr("Note has been restored."));
4920 @SuppressWarnings("unused")
4921 private void setupSelectiveSync() {
4923 // Get a list of valid notebooks
4924 List<Notebook> notebooks = null;
4925 List<Tag> tags = null;
4926 List<LinkedNotebook> linkedNotebooks = null;
4928 notebooks = syncRunner.noteStore.listNotebooks(syncRunner.authToken);
4929 tags = syncRunner.noteStore.listTags(syncRunner.authToken);
4930 linkedNotebooks = syncRunner.noteStore.listLinkedNotebooks(syncRunner.authToken);
4931 } catch (EDAMUserException e) {
4932 setMessage("EDAMUserException: " +e.getMessage());
4934 } catch (EDAMSystemException e) {
4935 setMessage("EDAMSystemException: " +e.getMessage());
4937 } catch (TException e) {
4938 setMessage("EDAMTransactionException: " +e.getMessage());
4940 } catch (EDAMNotFoundException e) {
4941 setMessage("EDAMNotFoundException: " +e.getMessage());
4945 // Split up notebooks into synchronized & non-synchronized
4946 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
4947 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4949 for (int i=notebooks.size()-1; i>=0; i--) {
4950 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
4951 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
4952 ignoredBooks.add(notebooks.get(i));
4953 j=dbIgnoredNotebooks.size();
4958 // split up tags into synchronized & non-synchronized
4959 List<Tag> ignoredTags = new ArrayList<Tag>();
4960 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
4962 for (int i=tags.size()-1; i>=0; i--) {
4963 for (int j=0; j<dbIgnoredTags.size(); j++) {
4964 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
4965 ignoredTags.add(tags.get(i));
4966 j=dbIgnoredTags.size();
4971 // split up linked notebooks into synchronized & non-synchronized
4972 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
4973 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
4974 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
4975 String notebookGuid = linkedNotebooks.get(i).getGuid();
4976 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
4977 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
4978 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
4979 j=dbIgnoredLinkedNotebooks.size();
4984 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
4986 if (!ignore.okClicked())
4991 // Clear out old notebooks & add the new ones
4992 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
4993 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
4994 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
4997 List<String> newNotebooks = new ArrayList<String>();
4998 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
4999 String text = ignore.getIgnoredBookList().takeItem(i).text();
5000 for (int j=0; j<notebooks.size(); j++) {
5001 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5002 Notebook n = notebooks.get(j);
5003 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5005 newNotebooks.add(n.getGuid());
5010 // Clear out old tags & add new ones
5011 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5012 for (int i=0; i<oldIgnoreTags.size(); i++) {
5013 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5016 List<String> newTags = new ArrayList<String>();
5017 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5018 String text = ignore.getIgnoredTagList().takeItem(i).text();
5019 for (int j=0; j<tags.size(); j++) {
5020 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5021 Tag t = tags.get(j);
5022 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5023 newTags.add(t.getGuid());
5029 // Clear out old tags & add new ones
5030 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5031 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5032 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5035 List<String> newLinked = new ArrayList<String>();
5036 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5037 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5038 for (int j=0; j<linkedNotebooks.size(); j++) {
5039 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5040 LinkedNotebook t = linkedNotebooks.get(j);
5041 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5042 newLinked.add(t.getGuid());
5043 j=linkedNotebooks.size();
5048 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5054 //**********************************************************
5055 //**********************************************************
5056 //* XML Modifying methods
5057 //**********************************************************
5058 //**********************************************************
5059 // An error has happended fetching a resource. let the user know
5060 private void resourceErrorMessage() {
5063 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5064 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5065 "In a perfect world this wouldn't happen, but it has.\n" +
5066 "It is embarasing when a program like me, designed to save all your\n"+
5067 "precious data, has a problem finding data.\n\n" +
5068 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5069 "In the mean time, I'm not going to let you make changes to this note.\n" +
5070 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5071 "this note on the Evernote servers. Sorry."+
5072 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5074 browserWindow.setReadOnly(true);
5080 //**********************************************************
5081 //**********************************************************
5083 //**********************************************************
5084 //**********************************************************
5085 // We should now do a sync with Evernote
5086 private void syncTimer() {
5087 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5088 syncRunner.syncNeeded = true;
5089 syncRunner.disableUploads = Global.disableUploads;
5091 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5093 private void syncStart() {
5094 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5096 if (!syncRunning && Global.isConnected) {
5097 syncRunner.setConnected(true);
5098 syncRunner.setKeepRunning(Global.keepRunning);
5099 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5101 if (syncThreadsReady > 0) {
5102 thumbnailRunner.interrupt = true;
5103 saveNoteIndexWidth();
5104 saveNoteColumnPositions();
5105 if (syncRunner.addWork("SYNC")) {
5107 syncRunner.syncNeeded = true;
5112 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5114 @SuppressWarnings("unused")
5115 private void syncThreadComplete(Boolean refreshNeeded) {
5116 setMessage(tr("Finalizing Synchronization"));
5118 syncRunning = false;
5119 syncRunner.syncNeeded = false;
5120 synchronizeAnimationTimer.stop();
5121 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5123 if (currentNote == null) {
5124 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5126 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5127 noteIndexUpdated(false);
5128 noteTableView.selectionModel().blockSignals(true);
5129 scrollToGuid(currentNoteGuid);
5130 noteTableView.selectionModel().blockSignals(false);
5131 refreshEvernoteNote(false);
5132 scrollToGuid(currentNoteGuid);
5134 if (!syncRunner.error)
5135 setMessage(tr("Synchronization Complete"));
5137 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5138 logger.log(logger.MEDIUM, "Sync complete.");
5140 public void saveUploadAmount(long t) {
5141 Global.saveUploadAmount(t);
5143 public void saveUserInformation(User user) {
5144 Global.saveUserInformation(user);
5146 public void saveEvernoteUpdateCount(int i) {
5147 Global.saveEvernoteUpdateCount(i);
5149 public void refreshLists() {
5150 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5152 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5153 tagIndexUpdated(true);
5154 notebookIndexUpdated();
5155 savedSearchIndexUpdated();
5156 listManager.loadNotesIndex();
5158 noteTableView.selectionModel().blockSignals(true);
5159 noteIndexUpdated(true);
5160 noteTableView.selectionModel().blockSignals(false);
5161 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5165 @SuppressWarnings("unused")
5166 private void authTimer() {
5167 Calendar cal = Calendar.getInstance();
5169 // If we are not connected let's get out of here
5170 if (!Global.isConnected)
5173 // If this is the first time through, then we need to set this
5174 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5175 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5177 // long now = new Date().getTime();
5178 // if (now > Global.authRefreshTime && Global.isConnected) {
5179 syncRunner.authRefreshNeeded = true;
5183 @SuppressWarnings("unused")
5184 private void authRefreshComplete(boolean goodSync) {
5185 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5186 Global.isConnected = syncRunner.isConnected;
5188 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5189 authTimer.start(1000*60*15);
5190 logger.log(logger.LOW, "Authentication token has been renewed");
5191 // setMessage("Authentication token has been renewed.");
5193 authTimer.start(1000*60*5);
5194 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5195 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5197 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5201 @SuppressWarnings("unused")
5202 private synchronized void indexTimer() {
5203 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5206 if (!indexDisabled && indexRunner.idle) {
5207 thumbnailRunner.interrupt = true;
5208 indexRunner.addWork("SCAN");
5210 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5213 @SuppressWarnings("unused")
5214 private void indexStarted() {
5215 setMessage(tr("Indexing notes"));
5217 @SuppressWarnings("unused")
5218 private void indexComplete() {
5219 setMessage(tr("Index complete"));
5221 @SuppressWarnings("unused")
5222 private synchronized void toggleNoteIndexing() {
5223 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5224 indexDisabled = !indexDisabled;
5226 setMessage(tr("Indexing is now enabled."));
5228 setMessage(tr("Indexing is now disabled."));
5229 menuBar.disableIndexing.setChecked(indexDisabled);
5230 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5233 @SuppressWarnings("unused")
5234 private void threadMonitorCheck() {
5239 alive = listManager.threadCheck(Global.tagCounterThreadId);
5242 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5243 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5244 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5245 disableTagThreadCheck = true;
5250 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5252 notebookThreadDeadCount++;
5253 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5254 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5255 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5256 disableNotebookThreadCheck=true;
5259 notebookThreadDeadCount=0;
5261 alive = listManager.threadCheck(Global.trashCounterThreadId);
5264 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5265 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5266 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5267 disableTrashThreadCheck = true;
5272 alive = listManager.threadCheck(Global.saveThreadId);
5274 saveThreadDeadCount++;
5275 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5276 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5277 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5278 disableSaveThreadCheck = true;
5281 saveThreadDeadCount=0;
5283 if (!syncThread.isAlive()) {
5284 syncThreadDeadCount++;
5285 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5286 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5287 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5288 disableSyncThreadCheck = true;
5291 syncThreadDeadCount=0;
5293 if (!indexThread.isAlive()) {
5294 indexThreadDeadCount++;
5295 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5296 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5297 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5298 disableIndexThreadCheck = true;
5301 indexThreadDeadCount=0;
5306 private void thumbnailTimer() {
5307 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5308 thumbnailRunner.addWork("SCAN");
5312 //**************************************************
5313 //* Backup & Restore
5314 //**************************************************
5315 @SuppressWarnings("unused")
5316 private void databaseBackup() {
5317 QFileDialog fd = new QFileDialog(this);
5318 fd.setFileMode(FileMode.AnyFile);
5319 fd.setConfirmOverwrite(true);
5320 fd.setWindowTitle(tr("Backup Database"));
5321 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5322 fd.setAcceptMode(AcceptMode.AcceptSave);
5323 if (saveLastPath == null || saveLastPath.equals(""))
5324 fd.setDirectory(System.getProperty("user.home"));
5326 fd.setDirectory(saveLastPath);
5327 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5333 saveLastPath = fd.selectedFiles().get(0);
5334 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5335 setMessage(tr("Backing up database"));
5337 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5339 ExportData noteWriter = new ExportData(conn, true);
5340 String fileName = fd.selectedFiles().get(0);
5342 if (!fileName.endsWith(".nnex"))
5343 fileName = fileName +".nnex";
5344 noteWriter.exportData(fileName);
5345 setMessage(tr("Database backup completed."));
5350 @SuppressWarnings("unused")
5351 private void databaseRestore() {
5352 if (QMessageBox.question(this, tr("Confirmation"),
5353 tr("This is used to restore a database from backups.\n" +
5354 "It is HIGHLY recommened that this only be used to populate\n" +
5355 "an empty database. Restoring into a database that\n already has data" +
5356 " can cause problems.\n\nAre you sure you want to continue?"),
5357 QMessageBox.StandardButton.Yes,
5358 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5363 QFileDialog fd = new QFileDialog(this);
5364 fd.setFileMode(FileMode.ExistingFile);
5365 fd.setConfirmOverwrite(true);
5366 fd.setWindowTitle(tr("Restore Database"));
5367 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5368 fd.setAcceptMode(AcceptMode.AcceptOpen);
5369 if (saveLastPath == null || saveLastPath.equals(""))
5370 fd.setDirectory(System.getProperty("user.home"));
5372 fd.setDirectory(saveLastPath);
5373 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5379 saveLastPath = fd.selectedFiles().get(0);
5380 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5382 setMessage(tr("Restoring database"));
5383 ImportData noteReader = new ImportData(conn, true);
5384 noteReader.importData(fd.selectedFiles().get(0));
5386 if (noteReader.lastError != 0) {
5387 setMessage(noteReader.getErrorMessage());
5388 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5393 listManager.loadNoteTitleColors();
5395 refreshEvernoteNote(true);
5396 setMessage(tr("Database has been restored."));
5399 @SuppressWarnings("unused")
5400 private void exportNotes() {
5401 QFileDialog fd = new QFileDialog(this);
5402 fd.setFileMode(FileMode.AnyFile);
5403 fd.setConfirmOverwrite(true);
5404 fd.setWindowTitle(tr("Backup Database"));
5405 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5406 fd.setAcceptMode(AcceptMode.AcceptSave);
5407 fd.setDirectory(System.getProperty("user.home"));
5408 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5414 setMessage(tr("Exporting Notes"));
5417 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5418 selectedNoteGUIDs.add(currentNoteGuid);
5420 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5421 String fileName = fd.selectedFiles().get(0);
5423 if (!fileName.endsWith(".nnex"))
5424 fileName = fileName +".nnex";
5425 noteWriter.exportData(fileName);
5426 setMessage(tr("Export completed."));
5432 @SuppressWarnings("unused")
5433 private void importNotes() {
5434 QFileDialog fd = new QFileDialog(this);
5435 fd.setFileMode(FileMode.ExistingFile);
5436 fd.setConfirmOverwrite(true);
5437 fd.setWindowTitle(tr("Import Notes"));
5438 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5439 fd.setAcceptMode(AcceptMode.AcceptOpen);
5440 if (saveLastPath == null || saveLastPath.equals(""))
5441 fd.setDirectory(System.getProperty("user.home"));
5443 fd.setDirectory(saveLastPath);
5444 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5450 setMessage("Importing Notes");
5453 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5454 selectedNoteGUIDs.add(currentNoteGuid);
5456 ImportData noteReader = new ImportData(conn, false);
5457 String fileName = fd.selectedFiles().get(0);
5458 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5460 if (!fileName.endsWith(".nnex"))
5461 fileName = fileName +".nnex";
5462 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5463 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5465 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5467 noteReader.importData(fileName);
5469 if (noteReader.lastError != 0) {
5470 setMessage(noteReader.getErrorMessage());
5471 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5476 listManager.loadNoteTitleColors();
5478 refreshEvernoteNote(false);
5479 setMessage(tr("Notes have been imported."));
5482 setMessage("Import completed.");
5489 //**************************************************
5490 //* Duplicate a note
5491 //**************************************************
5492 @SuppressWarnings("unused")
5493 private void duplicateNote() {
5495 duplicateNote(currentNoteGuid);
5500 //**************************************************
5502 //**************************************************
5503 public void setupFolderImports() {
5504 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5506 if (importKeepWatcher == null)
5507 importKeepWatcher = new QFileSystemWatcher();
5508 if (importDeleteWatcher == null) {
5509 importDeleteWatcher = new QFileSystemWatcher();
5510 for (int i=0; i<records.size(); i++) {
5511 if (!records.get(i).keep)
5512 folderImportDelete(records.get(i).folder);
5518 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5519 for (int i=0; i<records.size(); i++) {
5520 if (records.get(i).keep)
5521 importKeepWatcher.addPath(records.get(i).folder);
5523 importDeleteWatcher.addPath(records.get(i).folder);
5526 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5527 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5529 // Look at the files already there so we don't import them again if a new file is created
5530 if (importedFiles == null) {
5531 importedFiles = new ArrayList<String>();
5532 for (int j=0; j<records.size(); j++) {
5533 QDir dir = new QDir(records.get(j).folder);
5534 List<QFileInfo> list = dir.entryInfoList();
5535 for (int k=0; k<list.size(); k++) {
5536 if (list.get(k).isFile())
5537 importedFiles.add(list.get(k).absoluteFilePath());
5542 public void folderImport() {
5543 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5544 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5546 if (!dialog.okClicked())
5549 // We have some sort of update.
5550 if (importKeepWatcher.directories().size() > 0)
5551 importKeepWatcher.removePaths(importKeepWatcher.directories());
5552 if (importDeleteWatcher.directories().size() > 0)
5553 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5555 conn.getWatchFolderTable().expungeAll();
5556 // Start building from the table
5557 for (int i=0; i<dialog.table.rowCount(); i++) {
5558 QTableWidgetItem item = dialog.table.item(i, 0);
5559 String dir = item.text();
5560 item = dialog.table.item(i, 1);
5561 String notebook = item.text();
5562 item = dialog.table.item(i, 2);
5564 if (item.text().equalsIgnoreCase("Keep"))
5569 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5570 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5572 setupFolderImports();
5575 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5577 String whichOS = System.getProperty("os.name");
5578 if (whichOS.contains("Windows"))
5579 dirName = dirName.replace('/','\\');
5581 FileImporter importer = new FileImporter(logger, conn);
5583 QDir dir = new QDir(dirName);
5584 List<QFileInfo> list = dir.entryInfoList();
5585 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5587 for (int i=0; i<list.size(); i++){
5589 boolean redundant = false;
5590 // Check if we've already imported this one or if it existed before
5591 for (int j=0; j<importedFiles.size(); j++) {
5592 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5597 importer.setFileInfo(list.get(i));
5598 importer.setFileName(list.get(i).absoluteFilePath());
5601 if (list.get(i).isFile() && importer.isValidType()) {
5603 if (!importer.importFile()) {
5604 // If we can't get to the file, it is probably locked. We'll try again later.
5605 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5606 importFilesKeep.add(list.get(i).absoluteFilePath());
5610 Note newNote = importer.getNote();
5611 newNote.setNotebookGuid(notebook);
5612 newNote.setTitle(dir.at(i));
5613 listManager.addNote(newNote);
5614 conn.getNoteTable().addNote(newNote, true);
5615 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5616 noteTableView.insertRow(newNote, true, -1);
5617 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5618 listManager.countNotebookResults(listManager.getNoteIndex());
5619 importedFiles.add(list.get(i).absoluteFilePath());
5627 public void folderImportDelete(String dirName) {
5629 String whichOS = System.getProperty("os.name");
5630 if (whichOS.contains("Windows"))
5631 dirName = dirName.replace('/','\\');
5633 FileImporter importer = new FileImporter(logger, conn);
5634 QDir dir = new QDir(dirName);
5635 List<QFileInfo> list = dir.entryInfoList();
5636 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5638 for (int i=0; i<list.size(); i++){
5639 importer.setFileInfo(list.get(i));
5640 importer.setFileName(list.get(i).absoluteFilePath());
5642 if (list.get(i).isFile() && importer.isValidType()) {
5644 if (!importer.importFile()) {
5645 // If we can't get to the file, it is probably locked. We'll try again later.
5646 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5647 importFilesKeep.add(list.get(i).absoluteFilePath());
5651 Note newNote = importer.getNote();
5652 newNote.setNotebookGuid(notebook);
5653 newNote.setTitle(dir.at(i));
5654 listManager.addNote(newNote);
5655 conn.getNoteTable().addNote(newNote, true);
5656 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5657 noteTableView.insertRow(newNote, true, -1);
5658 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5659 listManager.countNotebookResults(listManager.getNoteIndex());
5660 dir.remove(dir.at(i));
5666 //**************************************************
5668 //**************************************************
5669 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5670 logger.log(logger.HIGH, "Entering exernalFileEdited");
5672 // Strip URL prefix and base dir path
5673 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5674 String name = fileName.replace(dPath, "");
5675 int pos = name.lastIndexOf('.');
5678 guid = guid.substring(0,pos);
5680 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5682 guid = name.substring(0, pos);
5685 QFile file = new QFile(fileName);
5686 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5687 // If we can't get to the file, it is probably locked. We'll try again later.
5688 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5689 externalFiles.add(fileName);
5692 QByteArray binData = file.readAll();
5694 if (binData.size() == 0) {
5695 // If we can't get to the file, it is probably locked. We'll try again later.
5696 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5697 externalFiles.add(fileName);
5701 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5703 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5704 if (r == null || r.getData() == null || r.getData().getBody() == null)
5706 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5707 MessageDigest md = MessageDigest.getInstance("MD5");
5708 md.update(binData.toByteArray());
5709 byte[] hash = md.digest();
5710 String newHash = Global.byteArrayToHexString(hash);
5711 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5712 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5714 if (externalWindows.containsKey(r.getNoteGuid())) {
5715 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5716 r.getGuid(), oldHash, newHash);
5718 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5719 Data data = r.getData();
5720 data.setBody(binData.toByteArray());
5721 data.setBodyHash(hash);
5722 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5724 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5726 if (r.getNoteGuid().equals(currentNoteGuid)) {
5727 QWebSettings.setMaximumPagesInCache(0);
5728 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5729 refreshEvernoteNote(true);
5730 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5733 if (externalWindows.containsKey(r.getNoteGuid())) {
5734 QWebSettings.setMaximumPagesInCache(0);
5735 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5736 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5740 logger.log(logger.HIGH, "Exiting externalFielEdited");
5742 // This is a timer event that tries to save any external files that were edited. This
5743 // is only needed if we couldn't save a file earlier.
5744 public void externalFileEditedSaver() {
5745 for (int i=externalFiles.size()-1; i>=0; i--) {
5747 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5748 externalFileEdited(externalFiles.get(i));
5749 externalFiles.remove(i);
5750 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5752 for (int i=0; i<importFilesKeep.size(); i++) {
5754 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5755 folderImportKeep(importFilesKeep.get(i));
5756 importFilesKeep.remove(i);
5757 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5759 for (int i=0; i<importFilesDelete.size(); i++) {
5760 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5761 folderImportDelete(importFilesDelete.get(i));
5762 importFilesDelete.remove(i);
5769 // If an attachment on the current note was edited, we need to update the current notes's hash
5770 // Update a note content's hash. This happens if a resource is edited outside of NN
5771 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5772 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5774 for (;position>-1;) {
5775 endPos = browser.getContent().indexOf(">", position+1);
5776 String oldSegment = browser.getContent().substring(position,endPos);
5777 int hashPos = oldSegment.indexOf("hash=\"");
5778 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5779 String hash = oldSegment.substring(hashPos+6, hashEnd);
5780 if (hash.equalsIgnoreCase(oldHash)) {
5781 String newSegment = oldSegment.replace(oldHash, newHash);
5782 String content = browser.getContent().substring(0,position) +
5784 browser.getContent().substring(endPos);
5785 browser.getBrowser().setContent(new QByteArray(content));;
5788 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5793 //*************************************************
5794 //* Minimize to tray
5795 //*************************************************
5797 public void changeEvent(QEvent e) {
5798 if (e.type() == QEvent.Type.WindowStateChange) {
5799 if (isMinimized() && Global.showTrayIcon()) {
5801 QTimer.singleShot(10, this, "hide()");
5805 windowMaximized = true;
5807 windowMaximized = false;
5811 //*************************************************
5812 //* Check database userid & passwords
5813 //*************************************************
5814 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5815 Connection connection;
5818 Class.forName("org.h2.Driver");
5819 } catch (ClassNotFoundException e1) {
5820 e1.printStackTrace();
5825 String passwordString = null;
5826 if (cypherPassword==null || cypherPassword.trim().equals(""))
5827 passwordString = userPassword;
5829 passwordString = cypherPassword+" "+userPassword;
5830 connection = DriverManager.getConnection(url,userid,passwordString);
5831 } catch (SQLException e) {
5836 } catch (SQLException e) {
5837 e.printStackTrace();