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.QCursor;
99 import com.trolltech.qt.gui.QDesktopServices;
100 import com.trolltech.qt.gui.QDialog;
101 import com.trolltech.qt.gui.QFileDialog;
102 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
103 import com.trolltech.qt.gui.QFileDialog.FileMode;
104 import com.trolltech.qt.gui.QGridLayout;
105 import com.trolltech.qt.gui.QHBoxLayout;
106 import com.trolltech.qt.gui.QIcon;
107 import com.trolltech.qt.gui.QImage;
108 import com.trolltech.qt.gui.QKeySequence;
109 import com.trolltech.qt.gui.QLabel;
110 import com.trolltech.qt.gui.QMainWindow;
111 import com.trolltech.qt.gui.QMenu;
112 import com.trolltech.qt.gui.QMessageBox;
113 import com.trolltech.qt.gui.QMessageBox.StandardButton;
114 import com.trolltech.qt.gui.QPainter;
115 import com.trolltech.qt.gui.QPalette.ColorRole;
116 import com.trolltech.qt.gui.QPixmap;
117 import com.trolltech.qt.gui.QPrintDialog;
118 import com.trolltech.qt.gui.QPrinter;
119 import com.trolltech.qt.gui.QShortcut;
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.LogFileDialog;
147 import cx.fbn.nevernote.dialog.LoginDialog;
148 import cx.fbn.nevernote.dialog.NotebookArchive;
149 import cx.fbn.nevernote.dialog.NotebookEdit;
150 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
151 import cx.fbn.nevernote.dialog.PublishNotebook;
152 import cx.fbn.nevernote.dialog.SavedSearchEdit;
153 import cx.fbn.nevernote.dialog.SetIcon;
154 import cx.fbn.nevernote.dialog.ShareNotebook;
155 import cx.fbn.nevernote.dialog.StackNotebook;
156 import cx.fbn.nevernote.dialog.TagEdit;
157 import cx.fbn.nevernote.dialog.ThumbnailViewer;
158 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
159 import cx.fbn.nevernote.dialog.WatchFolder;
160 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
161 import cx.fbn.nevernote.filters.FilterEditorTags;
162 import cx.fbn.nevernote.gui.AttributeTreeWidget;
163 import cx.fbn.nevernote.gui.BrowserWindow;
164 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
165 import cx.fbn.nevernote.gui.ExternalBrowse;
166 import cx.fbn.nevernote.gui.MainMenuBar;
167 import cx.fbn.nevernote.gui.NotebookTreeWidget;
168 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
169 import cx.fbn.nevernote.gui.SearchPanel;
170 import cx.fbn.nevernote.gui.TableView;
171 import cx.fbn.nevernote.gui.TagTreeWidget;
172 import cx.fbn.nevernote.gui.Thumbnailer;
173 import cx.fbn.nevernote.gui.TrashTreeWidget;
174 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
175 import cx.fbn.nevernote.sql.DatabaseConnection;
176 import cx.fbn.nevernote.sql.WatchFolderRecord;
177 import cx.fbn.nevernote.threads.IndexRunner;
178 import cx.fbn.nevernote.threads.SyncRunner;
179 import cx.fbn.nevernote.threads.ThumbnailRunner;
180 import cx.fbn.nevernote.utilities.AESEncrypter;
181 import cx.fbn.nevernote.utilities.ApplicationLogger;
182 import cx.fbn.nevernote.utilities.FileImporter;
183 import cx.fbn.nevernote.utilities.FileUtils;
184 import cx.fbn.nevernote.utilities.ListManager;
185 import cx.fbn.nevernote.utilities.SyncTimes;
186 import cx.fbn.nevernote.xml.ExportData;
187 import cx.fbn.nevernote.xml.ImportData;
188 import cx.fbn.nevernote.xml.NoteFormatter;
191 public class NeverNote extends QMainWindow{
193 QStatusBar statusBar; // Application status bar
195 DatabaseConnection conn;
197 MainMenuBar menuBar; // Main menu bar
198 FindDialog find; // Text search in note dialog
199 List<String> emitLog; // Messages displayed in the status bar;
200 QSystemTrayIcon trayIcon; // little tray icon
201 QMenu trayMenu; // System tray menu
202 QAction trayExitAction; // Exit the application
203 QAction trayShowAction; // toggle the show/hide action
204 QAction trayAddNoteAction; // Add a note from the system tray
205 QNetworkAccessManager versionChecker; // Used when checking for new versions
207 NotebookTreeWidget notebookTree; // List of notebooks
208 AttributeTreeWidget attributeTree; // List of note attributes
209 TagTreeWidget tagTree; // list of user created tags
210 SavedSearchTreeWidget savedSearchTree; // list of saved searches
211 TrashTreeWidget trashTree; // Trashcan
212 TableView noteTableView; // List of notes (the widget).
214 public BrowserWindow browserWindow; // Window containing browser & labels
215 public QToolBar toolBar; // The tool bar under the menu
216 QComboBox searchField; // search filter bar on the toolbar;
217 QShortcut searchShortcut; // Shortcut to search bar
218 boolean searchPerformed = false; // Search was done?
219 QuotaProgressBar quotaBar; // The current quota usage
221 ApplicationLogger logger;
222 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
223 List<String> selectedTagGUIDs; // List of selected tag GUIDs
224 List<String> selectedNoteGUIDs; // List of selected notes
225 String selectedSavedSearchGUID; // Currently selected saved searches
226 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
228 NoteFilter filter; // Note filter
229 String currentNoteGuid; // GUID of the current note
230 Note currentNote; // The currently viewed note
231 boolean noteDirty; // Has the note been changed?
232 boolean inkNote; // if this is an ink note, it is read only
233 boolean readOnly; // Is this note read-only?
236 ListManager listManager; // DB runnable task
238 List<QTemporaryFile> tempFiles; // Array of temporary files;
240 QTimer indexTimer; // timer to start the index thread
241 IndexRunner indexRunner; // thread to index notes
244 QTimer syncTimer; // Sync on an interval
245 QTimer syncDelayTimer; // Sync delay to free up database
246 SyncRunner syncRunner; // thread to do a sync.
247 QThread syncThread; // Thread which talks to evernote
248 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
249 QThread thumbnailThread; // Thread that generates pretty pictures
250 QTimer saveTimer; // Timer to save note contents
252 QTimer authTimer; // Refresh authentication
253 QTimer externalFileSaveTimer; // Save files altered externally
254 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
255 List<String> externalFiles; // External files to save later
256 List<String> importFilesKeep; // Auto-import files to save later
257 List<String> importFilesDelete; // Auto-import files to save later
259 int indexTime; // how often to try and index
260 boolean indexRunning; // Is indexing running?
261 boolean indexDisabled; // Is indexing disabled?
263 int syncThreadsReady; // number of sync threads that are free
264 int syncTime; // Sync interval
265 boolean syncRunning; // Is sync running?
266 boolean automaticSync; // do sync automatically?
267 QTreeWidgetItem attributeTreeSelected;
269 QAction prevButton; // Go to the previous item viewed
270 QAction nextButton; // Go to the next item in the history
271 QAction downButton; // Go to the next item in the list
272 QAction upButton; // Go to the prev. item in the list;
273 QAction synchronizeButton; // Synchronize with Evernote
274 QAction allNotesButton; // Reset & view all notes
275 QTimer synchronizeAnimationTimer; // Timer to change animation button
276 int synchronizeIconAngle; // Used to rotate sync icon
277 QAction printButton; // Print Button
278 QAction tagButton; // Tag edit button
279 QAction attributeButton; // Attribute information button
280 QAction emailButton; // Email button
281 QAction deleteButton; // Delete button
282 QAction newButton; // new Note Button;
283 QSpinBox zoomSpinner; // Zoom zoom
284 QAction searchClearButton; // Clear the search field
286 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
288 QSplitter mainLeftRightSplitter; // main splitter for left/right side
289 QSplitter leftSplitter1; // first left hand splitter
290 QSplitter browserIndexSplitter; // splitter between note index & note text
292 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
293 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
294 List<String> importedFiles; // History of imported files (so we don't import twice)
296 OnlineNoteHistory historyWindow; // online history window
297 List<NoteVersionId> versions; // history versions
299 QTimer threadMonitorTimer; // Timer to watch threads.
300 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
301 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
302 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
303 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
304 int tagDeadCount=0; // number of consecutive dead times for the tag thread
305 int trashDeadCount=0; // number of consecutive dead times for the trash thread
306 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
307 boolean disableTagThreadCheck=false;
308 boolean disableNotebookThreadCheck=false;
309 boolean disableTrashThreadCheck=false;
310 boolean disableSaveThreadCheck=false;
311 boolean disableSyncThreadCheck=false;
312 boolean disableIndexThreadCheck=false;
314 HashMap<String, String> noteCache; // Cash of note content
315 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
316 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
317 List<String> historyGuids; // GUIDs of previously viewed items
318 int historyPosition; // Position within the viewed items
319 boolean fromHistory; // Is this from the history queue?
320 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
321 List<Thumbnailer> thumbGenerators; // generate preview image
322 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
323 boolean encryptOnShutdown; // should I encrypt when I close?
324 boolean decryptOnShutdown; // should I decrypt on shutdown;
325 String encryptCipher; // What cipher should I use?
326 Signal0 minimizeToTray;
327 boolean windowMaximized = false; // Keep track of the window state for restores
328 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
329 List<QPixmap> syncIcons; // Array of icons used in sync animation
330 private boolean closeAction = false; // Used to say when to close or when to minimize
331 private static Logger log = Logger.getLogger(NeverNote.class);
332 private String saveLastPath; // last path we used
333 private final QTimer messageTimer; // Timer to clear the status message.
334 private long blockTime; // When the app. is blocked, this is the time to unblock it.
337 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
340 //***************************************************************
341 //***************************************************************
342 //** Constructor & main entry point
343 //***************************************************************
344 //***************************************************************
345 // Application Constructor
346 @SuppressWarnings("static-access")
347 public NeverNote(DatabaseConnection dbConn) {
349 if (conn.getConnection() == null) {
350 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
351 "is accessing the database or NeverNote is already running.\n\n" +
352 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
354 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
357 setObjectName("mainWindow");
358 // thread().setPriority(Thread.MAX_PRIORITY);
360 logger = new ApplicationLogger("nevernote.log");
361 logger.log(logger.HIGH, "Starting Application");
363 decryptOnShutdown = false;
364 encryptOnShutdown = false;
365 conn.checkDatabaseVersion();
369 // Start building the invalid XML tables
370 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
371 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
373 for (int i=0; i<elements.size(); i++) {
374 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
377 logger.log(logger.EXTREME, "Starting GUI build");
379 QTranslator nevernoteTranslator = new QTranslator();
380 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
381 QApplication.instance().installTranslator(nevernoteTranslator);
383 Global.originalPalette = QApplication.palette();
384 QApplication.setStyle(Global.getStyle());
385 if (Global.useStandardPalette())
386 QApplication.setPalette(QApplication.style().standardPalette());
387 setWindowTitle("NeverNote");
389 mainLeftRightSplitter = new QSplitter();
390 setCentralWidget(mainLeftRightSplitter);
391 leftSplitter1 = new QSplitter();
392 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
394 browserIndexSplitter = new QSplitter();
395 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
397 //* Setup threads & thread timers
398 int indexRunnerCount = Global.getIndexThreads();
399 indexRunnerCount = 1;
400 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
402 logger.log(logger.EXTREME, "Building list manager");
403 listManager = new ListManager(conn, logger);
405 logger.log(logger.EXTREME, "Building index runners & timers");
406 indexRunner = new IndexRunner("indexRunner.log",
407 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
408 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
409 indexThread = new QThread(indexRunner, "Index Thread");
410 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
413 synchronizeAnimationTimer = new QTimer();
414 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
416 indexTimer = new QTimer();
417 indexTime = 1000*Global.getIndexThreadSleepInterval();
418 indexTimer.start(indexTime); // Start indexing timer
419 indexTimer.timeout.connect(this, "indexTimer()");
420 indexDisabled = false;
421 indexRunning = false;
423 logger.log(logger.EXTREME, "Setting sync thread & timers");
425 syncRunner = new SyncRunner("syncRunner.log",
426 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
427 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
428 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
429 syncTimer = new QTimer();
430 syncTimer.timeout.connect(this, "syncTimer()");
431 syncRunner.status.message.connect(this, "setMessage(String)");
432 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
433 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
436 automaticSync = true;
437 syncTimer.start(syncTime*60*1000);
439 automaticSync = false;
442 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
443 syncThread = new QThread(syncRunner, "Synchronization Thread");
447 logger.log(logger.EXTREME, "Starting thumnail thread");
448 pdfReadyQueue = new ArrayList<String>();
449 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
450 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
451 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
452 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
453 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
454 thumbnailThread.start();
455 thumbGenerators = new ArrayList<Thumbnailer>();
456 thumbnailTimer = new QTimer();
457 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
459 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
460 thumbnailTimer.start();
462 logger.log(logger.EXTREME, "Starting authentication timer");
463 authTimer = new QTimer();
464 authTimer.timeout.connect(this, "authTimer()");
465 authTimer.start(1000*60*15);
466 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
468 logger.log(logger.EXTREME, "Setting save note timer");
469 saveTimer = new QTimer();
470 saveTimer.timeout.connect(this, "saveNote()");
471 if (Global.getAutoSaveInterval() > 0) {
472 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
475 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
477 logger.log(logger.EXTREME, "Starting external file monitor timer");
478 externalFileSaveTimer = new QTimer();
479 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
480 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
481 externalFiles = new ArrayList<String>();
482 importFilesDelete = new ArrayList<String>();
483 importFilesKeep = new ArrayList<String>();
484 externalFileSaveTimer.start();
486 notebookTree = new NotebookTreeWidget(conn);
487 attributeTree = new AttributeTreeWidget();
488 tagTree = new TagTreeWidget(conn);
489 savedSearchTree = new SavedSearchTreeWidget();
490 trashTree = new TrashTreeWidget();
491 noteTableView = new TableView(logger, listManager);
494 searchField = new QComboBox();
495 searchField.setObjectName("searchField");
496 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
497 searchField.setEditable(true);
498 searchField.activatedIndex.connect(this, "searchFieldChanged()");
499 searchField.setDuplicatesEnabled(false);
500 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
501 searchShortcut = new QShortcut(this);
502 setupShortcut(searchShortcut, "Focus_Search");
503 searchShortcut.activated.connect(this, "focusSearch()");
505 quotaBar = new QuotaProgressBar();
507 zoomSpinner = new QSpinBox();
508 zoomSpinner.setMinimum(10);
509 zoomSpinner.setMaximum(1000);
510 zoomSpinner.setAccelerated(true);
511 zoomSpinner.setSingleStep(10);
512 zoomSpinner.setValue(100);
513 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
515 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
518 QGridLayout leftGrid = new QGridLayout();
519 leftSplitter1.setContentsMargins(5, 0, 0, 7);
520 leftSplitter1.setLayout(leftGrid);
521 leftGrid.addWidget(searchLayout,1,1);
522 leftGrid.addWidget(tagTree,2,1);
523 leftGrid.addWidget(attributeTree,3,1);
524 leftGrid.addWidget(savedSearchTree,4,1);
525 leftGrid.addWidget(trashTree,5, 1);
527 // Setup the browser window
528 noteCache = new HashMap<String,String>();
529 readOnlyCache = new HashMap<String, Boolean>();
530 inkNoteCache = new HashMap<String, Boolean>();
531 browserWindow = new BrowserWindow(conn);
533 mainLeftRightSplitter.addWidget(leftSplitter1);
534 mainLeftRightSplitter.addWidget(browserIndexSplitter);
536 if (Global.getListView() == Global.View_List_Wide) {
537 browserIndexSplitter.addWidget(noteTableView);
538 browserIndexSplitter.addWidget(browserWindow);
540 mainLeftRightSplitter.addWidget(noteTableView);
541 mainLeftRightSplitter.addWidget(browserWindow);
544 // Setup the thumbnail viewer
545 thumbnailViewer = new ThumbnailViewer();
546 thumbnailViewer.upArrow.connect(this, "upAction()");
547 thumbnailViewer.downArrow.connect(this, "downAction()");
548 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
549 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
551 //Setup external browser manager
552 externalWindows = new HashMap<String, ExternalBrowse>();
554 listManager.loadNotesIndex();
555 initializeNotebookTree();
557 initializeSavedSearchTree();
558 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
559 attributeTreeSelected = null;
560 initializeNoteTable();
562 selectedNoteGUIDs = new ArrayList<String>();
563 statusBar = new QStatusBar();
564 setStatusBar(statusBar);
565 menuBar = new MainMenuBar(this);
566 emitLog = new ArrayList<String>();
568 tagTree.setDeleteAction(menuBar.tagDeleteAction);
569 tagTree.setEditAction(menuBar.tagEditAction);
570 tagTree.setAddAction(menuBar.tagAddAction);
571 tagTree.setIconAction(menuBar.tagIconAction);
572 tagTree.setVisible(Global.isWindowVisible("tagTree"));
573 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
574 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
575 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
576 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
578 if (!Global.isWindowVisible("zoom")) {
579 searchLayout.hideZoom();
580 menuBar.hideZoom.setChecked(false);
583 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
584 notebookTree.setEditAction(menuBar.notebookEditAction);
585 notebookTree.setAddAction(menuBar.notebookAddAction);
586 notebookTree.setIconAction(menuBar.notebookIconAction);
587 notebookTree.setStackAction(menuBar.notebookStackAction);
588 notebookTree.setPublishAction(menuBar.notebookPublishAction);
589 notebookTree.setShareAction(menuBar.notebookShareAction);
590 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
591 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
592 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
593 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
594 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
596 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
597 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
598 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
599 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
600 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
601 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
602 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
604 noteTableView.setAddAction(menuBar.noteAdd);
605 noteTableView.setDeleteAction(menuBar.noteDelete);
606 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
607 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
608 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
609 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
610 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
611 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
612 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
614 quotaBar.setMouseClickAction(menuBar.accountAction);
617 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
618 trashTree.setEmptyAction(menuBar.emptyTrashAction);
619 trashTree.setVisible(Global.isWindowVisible("trashTree"));
620 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
621 trashTree.updateCounts(listManager.getTrashCount());
622 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
623 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
625 noteTableView.setVisible(Global.isWindowVisible("noteList"));
626 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
628 if (!Global.isWindowVisible("editorButtonBar"))
629 toggleEditorButtonBar();
630 if (!Global.isWindowVisible("leftPanel"))
631 menuBar.hideLeftSide.setChecked(true);
632 if (Global.isWindowVisible("noteInformation"))
633 toggleNoteInformation();
634 quotaBar.setVisible(Global.isWindowVisible("quota"));
635 if (!quotaBar.isVisible())
636 menuBar.hideQuota.setChecked(false);
637 searchField.setVisible(Global.isWindowVisible("searchField"));
638 if (!searchField.isVisible())
639 menuBar.hideSearch.setChecked(false);
641 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
646 find = new FindDialog();
647 find.getOkButton().clicked.connect(this, "doFindText()");
649 // Setup the tray icon menu bar
650 trayShowAction = new QAction("Show/Hide", this);
651 trayExitAction = new QAction("Exit", this);
652 trayAddNoteAction = new QAction("Add Note", this);
654 trayExitAction.triggered.connect(this, "closeNeverNote()");
655 trayAddNoteAction.triggered.connect(this, "addNote()");
656 trayShowAction.triggered.connect(this, "trayToggleVisible()");
658 trayMenu = new QMenu(this);
659 trayMenu.addAction(trayAddNoteAction);
660 trayMenu.addAction(trayShowAction);
661 trayMenu.addAction(trayExitAction);
664 trayIcon = new QSystemTrayIcon(this);
665 trayIcon.setToolTip("NeverNote");
666 trayIcon.setContextMenu(trayMenu);
667 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
670 currentNoteGuid = Global.getLastViewedNoteGuid();
671 historyGuids = new ArrayList<String>();
675 if (!currentNoteGuid.trim().equals("")) {
676 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
679 noteIndexUpdated(true);
681 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
682 if (menuBar.showEditorBar.isChecked())
683 showEditorButtons(browserWindow);
684 tagIndexUpdated(true);
685 savedSearchIndexUpdated();
686 notebookIndexUpdated();
688 setupSyncSignalListeners();
689 setupBrowserSignalListeners();
690 setupIndexListeners();
693 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
694 tagTree.showAllTags(true);
696 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
697 setWindowIcon(appIcon);
698 trayIcon.setIcon(appIcon);
699 if (Global.showTrayIcon())
704 scrollToGuid(currentNoteGuid);
705 if (Global.automaticLogin()) {
707 if (Global.isConnected)
710 setupFolderImports();
713 restoreWindowState(true);
715 if (Global.mimicEvernoteInterface) {
716 notebookTree.selectGuid("");
719 threadMonitorTimer = new QTimer();
720 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
721 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
723 historyGuids.add(currentNoteGuid);
726 menuBar.blockSignals(true);
727 menuBar.narrowListView.blockSignals(true);
728 menuBar.wideListView.blockSignals(true);
729 if (Global.getListView() == Global.View_List_Narrow) {
730 menuBar.narrowListView.setChecked(true);
733 menuBar.wideListView.setChecked(true);
735 menuBar.blockSignals(false);
736 menuBar.narrowListView.blockSignals(false);
737 menuBar.wideListView.blockSignals(false);
739 if (Global.getListView() == Global.View_List_Wide) {
740 browserIndexSplitter.addWidget(noteTableView);
741 browserIndexSplitter.addWidget(browserWindow);
743 mainLeftRightSplitter.addWidget(noteTableView);
744 mainLeftRightSplitter.addWidget(browserWindow);
747 messageTimer = new QTimer();
748 messageTimer.timeout.connect(this, "clearMessage()");
749 messageTimer.setInterval(1000*15);
752 int sortCol = Global.getSortColumn();
753 int sortOrder = Global.getSortOrder();
754 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
755 if (Global.checkVersionUpgrade())
760 public static void main(String[] args) {
761 log.setLevel(Level.FATAL);
762 QApplication.initialize(args);
763 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
764 QSplashScreen splash = new QSplashScreen(pixmap);
767 DatabaseConnection dbConn;
770 initializeGlobalSettings(args);
772 showSplash = Global.isWindowVisible("SplashScreen");
776 dbConn = setupDatabaseConnection();
778 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
779 Global.getFileManager().purgeResDirectory(true);
781 } catch (InitializationException e) {
784 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
788 NeverNote application = new NeverNote(dbConn);
790 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
791 if (Global.startMinimized())
792 application.showMinimized();
794 if (Global.wasWindowMaximized())
795 application.showMaximized();
801 splash.finish(application);
803 System.out.println("Goodbye.");
808 * Open the internal database, or create if not present
810 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
812 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
813 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
815 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
816 boolean dbExists = f.exists();
818 Global.setDatabaseUrl("");
820 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
821 boolean goodCheck = false;
823 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
825 if (!dialog.okPressed())
827 Global.cipherPassword = dialog.getPassword();
828 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
829 Global.getDatabaseUserPassword(), Global.cipherPassword);
832 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
833 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
834 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
838 // Encrypt the database upon shutdown
839 private void encryptOnShutdown() {
840 String dbPath= Global.getFileManager().getDbDirPath("");
841 String dbName = "NeverNote";
843 Statement st = conn.getConnection().createStatement();
844 st.execute("shutdown");
845 if (QMessageBox.question(this, tr("Are you sure"),
846 tr("Are you sure you wish to encrypt the database?"),
847 QMessageBox.StandardButton.Yes,
848 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
849 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
850 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
851 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
853 } catch (SQLException e) {
858 // Decrypt the database upon shutdown
859 private void decryptOnShutdown() {
860 String dbPath= Global.getFileManager().getDbDirPath("");
861 String dbName = "NeverNote";
863 Statement st = conn.getConnection().createStatement();
864 st.execute("shutdown");
865 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
866 encryptCipher = "AES";
868 encryptCipher = "XTEA";
869 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
870 "Are you sure you wish to decrypt the database?"),
871 QMessageBox.StandardButton.Yes,
872 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
874 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
875 Global.setDatabaseUrl("");
876 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
878 } catch (SQLException e) {
883 * Encrypt/Decrypt the local database
885 public void doDatabaseEncrypt() {
886 // The database is not currently encrypted
887 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
888 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
889 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
890 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
891 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
892 "Do you wish to proceed?"),
893 QMessageBox.StandardButton.Yes,
894 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
897 DBEncryptDialog dialog = new DBEncryptDialog();
899 if (dialog.okPressed()) {
900 Global.cipherPassword = dialog.getPassword();
901 encryptOnShutdown = true;
902 encryptCipher = dialog.getEncryptionMethod();
905 DBEncryptDialog dialog = new DBEncryptDialog();
906 dialog.setWindowTitle("Database Decryption");
907 dialog.hideEncryption();
909 if (dialog.okPressed()) {
910 if (!dialog.getPassword().equals(Global.cipherPassword)) {
911 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
914 decryptOnShutdown = true;
921 private static void initializeGlobalSettings(String[] args) throws InitializationException {
922 StartupConfig startupConfig = new StartupConfig();
924 for (String arg : args) {
925 String lower = arg.toLowerCase();
926 if (lower.startsWith("--name="))
927 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
928 if (lower.startsWith("--home="))
929 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
930 if (lower.startsWith("--disable-viewing"))
931 startupConfig.setDisableViewing(true);
933 Global.setup(startupConfig);
938 public void closeEvent(QCloseEvent event) {
939 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
944 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
947 if (currentNote!= null & browserWindow!=null) {
948 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
949 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
952 setMessage(tr("Beginning shutdown."));
954 // Close down external windows
955 Collection<ExternalBrowse> windows = externalWindows.values();
956 Iterator<ExternalBrowse> iterator = windows.iterator();
957 while (iterator.hasNext()) {
958 ExternalBrowse browser = iterator.next();
959 browser.windowClosing.disconnect();
964 externalFileEditedSaver();
965 if (Global.isConnected && Global.synchronizeOnClose()) {
966 setMessage(tr("Performing synchronization before closing."));
967 syncRunner.syncNeeded = true;
968 syncRunner.addWork("SYNC");
970 syncRunner.keepRunning = false;
972 syncRunner.addWork("STOP");
973 setMessage("Closing Program.");
974 threadMonitorTimer.stop();
976 thumbnailRunner.addWork("STOP");
977 indexRunner.addWork("STOP");
982 if (tempFiles != null)
985 browserWindow.noteSignal.tagsChanged.disconnect();
986 browserWindow.noteSignal.titleChanged.disconnect();
987 browserWindow.noteSignal.noteChanged.disconnect();
988 browserWindow.noteSignal.notebookChanged.disconnect();
989 browserWindow.noteSignal.createdDateChanged.disconnect();
990 browserWindow.noteSignal.alteredDateChanged.disconnect();
991 syncRunner.searchSignal.listChanged.disconnect();
992 syncRunner.tagSignal.listChanged.disconnect();
993 syncRunner.notebookSignal.listChanged.disconnect();
994 syncRunner.noteIndexSignal.listChanged.disconnect();
997 Global.saveWindowVisible("toolBar", toolBar.isVisible());
998 saveNoteColumnPositions();
999 saveNoteIndexWidth();
1001 int width = notebookTree.columnWidth(0);
1002 Global.setColumnWidth("notebookTreeName", width);
1003 width = tagTree.columnWidth(0);
1004 Global.setColumnWidth("tagTreeName", width);
1006 Global.saveWindowMaximized(isMaximized());
1007 Global.saveCurrentNoteGuid(currentNoteGuid);
1009 int sortCol = noteTableView.proxyModel.sortColumn();
1010 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1011 Global.setSortColumn(sortCol);
1012 Global.setSortOrder(sortOrder);
1016 Global.keepRunning = false;
1018 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1019 if (indexRunner.thread().isAlive())
1020 indexRunner.thread().join(50);
1021 if (!indexRunner.thread().isAlive())
1022 logger.log(logger.MEDIUM, "Index thread has stopped");
1024 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1025 indexRunner.thread().interrupt();
1027 } catch (InterruptedException e1) {
1028 e1.printStackTrace();
1031 if (!syncRunner.thread().isAlive()) {
1032 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1033 if (syncRunner.thread().isAlive()) {
1034 System.out.println(tr("Synchronizing. Please be patient."));
1035 for(;syncRunner.thread().isAlive();) {
1038 } catch (InterruptedException e) {
1039 e.printStackTrace();
1043 logger.log(logger.MEDIUM, "Sync thread has stopped");
1046 if (encryptOnShutdown) {
1047 encryptOnShutdown();
1049 if (decryptOnShutdown) {
1050 decryptOnShutdown();
1053 Global.getFileManager().purgeResDirectory(false);
1054 } catch (InitializationException e) {
1055 System.out.println(tr("Empty res directory purge failed"));
1056 e.printStackTrace();
1058 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1061 @SuppressWarnings("unused")
1062 private void closeNeverNote() {
1066 public void setMessage(String s) {
1067 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1070 logger.log(logger.HIGH, "Message: " +s);
1071 statusBar.showMessage(s);
1075 messageTimer.stop();
1076 messageTimer.setSingleShot(true);
1077 messageTimer.start();
1080 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1083 private void clearMessage() {
1084 statusBar.clearMessage();
1088 private void waitCursor(boolean wait) {
1090 if (QApplication.overrideCursor() == null)
1091 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1094 while (QApplication.overrideCursor() != null)
1095 QApplication.restoreOverrideCursor();
1097 listManager.refreshCounters();
1100 private void setupIndexListeners() {
1101 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1102 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1103 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1104 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1106 private void setupSyncSignalListeners() {
1107 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1108 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1109 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1110 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1111 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1113 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1114 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1115 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1117 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1118 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1119 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1120 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1121 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1123 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1126 private void setupBrowserSignalListeners() {
1127 setupBrowserWindowListeners(browserWindow, true);
1130 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1131 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1132 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1133 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1134 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1135 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1136 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1137 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1138 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1139 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1140 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1141 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1142 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1143 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1144 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1145 if (master) browser.focusLost.connect(this, "saveNote()");
1146 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1149 //**************************************************
1151 //**************************************************
1152 private void setupShortcut(QShortcut action, String text) {
1153 if (!Global.shortcutKeys.containsAction(text))
1155 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1158 //***************************************************************
1159 //***************************************************************
1160 //* Settings and look & feel
1161 //***************************************************************
1162 //***************************************************************
1163 @SuppressWarnings("unused")
1164 private void settings() {
1165 logger.log(logger.HIGH, "Entering NeverNote.settings");
1166 saveNoteColumnPositions();
1167 saveNoteIndexWidth();
1169 ConfigDialog settings = new ConfigDialog(this);
1170 String dateFormat = Global.getDateFormat();
1171 String timeFormat = Global.getTimeFormat();
1173 indexTime = 1000*Global.getIndexThreadSleepInterval();
1174 indexTimer.start(indexTime); // reset indexing timer
1177 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1178 if (Global.showTrayIcon())
1183 if (menuBar.showEditorBar.isChecked())
1184 showEditorButtons(browserWindow);
1186 // Reset the save timer
1187 if (Global.getAutoSaveInterval() > 0)
1188 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1192 // This is a hack to force a reload of the index in case the date or time changed.
1193 // if (!dateFormat.equals(Global.getDateFormat()) ||
1194 // !timeFormat.equals(Global.getTimeFormat())) {
1196 readOnlyCache.clear();
1197 inkNoteCache.clear();
1198 noteIndexUpdated(true);
1201 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1203 // Restore things to the way they were
1204 private void restoreWindowState(boolean mainWindow) {
1205 // We need to name things or this doesn't work.
1206 setObjectName("NeverNote");
1207 restoreState(Global.restoreState(objectName()));
1208 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1209 browserIndexSplitter.setObjectName("browserIndexSplitter");
1210 leftSplitter1.setObjectName("leftSplitter1");
1212 // Restore the actual positions.
1214 restoreGeometry(Global.restoreGeometry(objectName()));
1215 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1216 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1217 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1220 // Save window positions for the next start
1221 private void saveWindowState() {
1222 Global.saveGeometry(objectName(), saveGeometry());
1223 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1224 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1225 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1226 Global.saveState(objectName(), saveState());
1228 // Load the style sheet
1229 private void loadStyleSheet() {
1230 String styleSheetName = "default.qss";
1231 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1232 styleSheetName = "default-cleanlooks.qss";
1233 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1234 QFile file = new QFile(fileName);
1236 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1237 if (!file.exists()) {
1238 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1239 file = new QFile(fileName);
1241 file.open(OpenModeFlag.ReadOnly);
1242 String styleSheet = file.readAll().toString();
1244 setStyleSheet(styleSheet);
1246 // Save column positions for the next time
1247 private void saveNoteColumnPositions() {
1248 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1249 Global.setColumnPosition("noteTableCreationPosition", position);
1250 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1251 Global.setColumnPosition("noteTableTagPosition", position);
1252 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1253 Global.setColumnPosition("noteTableNotebookPosition", position);
1254 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1255 Global.setColumnPosition("noteTableChangedPosition", position);
1256 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1257 Global.setColumnPosition("noteTableAuthorPosition", position);
1258 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1259 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1260 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1261 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1262 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1263 Global.setColumnPosition("noteTableTitlePosition", position);
1264 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1265 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1266 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1267 Global.setColumnPosition("noteTableGuidPosition", position);
1268 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1269 Global.setColumnPosition("noteTableThumbnailPosition", position);
1272 // Save column widths for the next time
1273 private void saveNoteIndexWidth() {
1275 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1276 Global.setColumnWidth("noteTableCreationPosition", width);
1277 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1278 Global.setColumnWidth("noteTableChangedPosition", width);
1279 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1280 Global.setColumnWidth("noteTableGuidPosition", width);
1281 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1282 Global.setColumnWidth("noteTableNotebookPosition", width);
1283 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1284 Global.setColumnWidth("noteTableTagPosition", width);
1285 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1286 Global.setColumnWidth("noteTableTitlePosition", width);
1287 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1288 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1289 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1290 Global.setColumnWidth("noteTableAuthorPosition", width);
1291 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1292 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1293 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1294 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1295 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1296 Global.setColumnWidth("noteTableThumbnailPosition", width);
1297 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1298 Global.setColumnWidth("noteTableGuidPosition", width);
1301 @SuppressWarnings("unused")
1302 private void toggleSearchWindow() {
1303 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1304 searchLayout.toggleSearchField();
1305 menuBar.hideSearch.setChecked(searchField.isVisible());
1306 Global.saveWindowVisible("searchField", searchField.isVisible());
1307 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1309 @SuppressWarnings("unused")
1310 private void toggleQuotaWindow() {
1311 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1312 searchLayout.toggleQuotaBar();
1313 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1314 Global.saveWindowVisible("quota", quotaBar.isVisible());
1315 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1317 @SuppressWarnings("unused")
1318 private void toggleZoomWindow() {
1319 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1320 searchLayout.toggleZoom();
1321 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1322 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1323 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1328 //***************************************************************
1329 //***************************************************************
1330 //** These functions deal with Notebook menu items
1331 //***************************************************************
1332 //***************************************************************
1333 // Setup the tree containing the user's notebooks.
1334 private void initializeNotebookTree() {
1335 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1336 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1337 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1338 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1339 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1341 // Listener when a notebook is selected
1342 private void notebookTreeSelection() {
1343 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1346 clearAttributeFilter();
1347 clearSavedSearchFilter();
1348 if (Global.mimicEvernoteInterface) {
1350 searchField.clear();
1352 menuBar.noteRestoreAction.setVisible(false);
1353 menuBar.notebookEditAction.setEnabled(true);
1354 menuBar.notebookDeleteAction.setEnabled(true);
1355 menuBar.notebookPublishAction.setEnabled(true);
1356 menuBar.notebookShareAction.setEnabled(true);
1357 menuBar.notebookIconAction.setEnabled(true);
1358 menuBar.notebookStackAction.setEnabled(true);
1359 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1360 selectedNotebookGUIDs.clear();
1362 String stackName = "";
1363 if (selections.size() > 0) {
1364 guid = (selections.get(0).text(2));
1365 stackName = selections.get(0).text(0);
1367 if (!Global.mimicEvernoteInterface) {
1368 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1369 if (selections.size()==0) {
1370 selectedNotebookGUIDs.clear();
1371 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1372 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1374 menuBar.notebookEditAction.setEnabled(false);
1375 menuBar.notebookDeleteAction.setEnabled(false);
1376 menuBar.notebookStackAction.setEnabled(false);
1377 menuBar.notebookIconAction.setEnabled(false);
1380 if (!guid.equals("") && !guid.equals("STACK")) {
1381 selectedNotebookGUIDs.add(guid);
1382 menuBar.notebookIconAction.setEnabled(true);
1384 menuBar.notebookIconAction.setEnabled(true);
1385 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1386 Notebook book = listManager.getNotebookIndex().get(j);
1387 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1388 selectedNotebookGUIDs.add(book.getGuid());
1391 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1392 listManager.loadNotesIndex();
1393 noteIndexUpdated(false);
1394 refreshEvernoteNote(true);
1395 listManager.refreshCounters = true;
1396 listManager.refreshCounters();
1397 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1400 private void clearNotebookFilter() {
1401 notebookTree.blockSignals(true);
1402 notebookTree.clearSelection();
1403 menuBar.noteRestoreAction.setVisible(false);
1404 menuBar.notebookEditAction.setEnabled(false);
1405 menuBar.notebookDeleteAction.setEnabled(false);
1406 selectedNotebookGUIDs.clear();
1407 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1408 notebookTree.blockSignals(false);
1410 // Triggered when the notebook DB has been updated
1411 private void notebookIndexUpdated() {
1412 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1414 // Get the possible icons
1415 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1416 notebookTree.setIcons(icons);
1418 if (selectedNotebookGUIDs == null)
1419 selectedNotebookGUIDs = new ArrayList<String>();
1420 List<Notebook> books = conn.getNotebookTable().getAll();
1421 for (int i=books.size()-1; i>=0; i--) {
1422 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1423 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1425 j=listManager.getArchiveNotebookIndex().size();
1431 listManager.countNotebookResults(listManager.getNoteIndex());
1432 notebookTree.blockSignals(true);
1433 notebookTree.load(books, listManager.getLocalNotebooks());
1434 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1435 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1437 selectedNotebookGUIDs.remove(i);
1439 listManager.refreshCounters = true;
1440 listManager.refreshCounters();
1441 notebookTree.blockSignals(false);
1443 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1445 // Show/Hide note information
1446 @SuppressWarnings("unused")
1447 private void toggleNotebookWindow() {
1448 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1449 searchLayout.toggleNotebook();
1450 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1451 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1452 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1454 // Add a new notebook
1455 @SuppressWarnings("unused")
1456 private void addNotebook() {
1457 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1458 NotebookEdit edit = new NotebookEdit();
1459 edit.setNotebooks(listManager.getNotebookIndex());
1462 if (!edit.okPressed())
1465 Calendar currentTime = new GregorianCalendar();
1466 Long l = new Long(currentTime.getTimeInMillis());
1467 String randint = new String(Long.toString(l));
1469 Notebook newBook = new Notebook();
1470 newBook.setUpdateSequenceNum(0);
1471 newBook.setGuid(randint);
1472 newBook.setName(edit.getNotebook());
1473 newBook.setServiceCreated(new Date().getTime());
1474 newBook.setServiceUpdated(new Date().getTime());
1475 newBook.setDefaultNotebook(false);
1476 newBook.setPublished(false);
1478 listManager.getNotebookIndex().add(newBook);
1480 listManager.getLocalNotebooks().add(newBook.getGuid());
1481 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1482 notebookIndexUpdated();
1483 listManager.countNotebookResults(listManager.getNoteIndex());
1484 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1485 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1487 // Edit an existing notebook
1488 @SuppressWarnings("unused")
1489 private void stackNotebook() {
1490 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1491 StackNotebook edit = new StackNotebook();
1493 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1494 QTreeWidgetItem currentSelection;
1495 for (int i=0; i<selections.size(); i++) {
1496 currentSelection = selections.get(0);
1497 String guid = currentSelection.text(2);
1498 if (guid.equalsIgnoreCase("")) {
1499 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1502 if (guid.equalsIgnoreCase("STACK")) {
1503 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1508 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1513 if (!edit.okPressed())
1516 String stack = edit.getStackName();
1518 for (int i=0; i<selections.size(); i++) {
1519 currentSelection = selections.get(i);
1520 String guid = currentSelection.text(2);
1521 listManager.updateNotebookStack(guid, stack);
1523 notebookIndexUpdated();
1524 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1526 // Edit an existing notebook
1527 @SuppressWarnings("unused")
1528 private void editNotebook() {
1529 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1530 NotebookEdit edit = new NotebookEdit();
1532 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1533 QTreeWidgetItem currentSelection;
1534 currentSelection = selections.get(0);
1535 edit.setNotebook(currentSelection.text(0));
1537 String guid = currentSelection.text(2);
1538 if (!guid.equalsIgnoreCase("STACK")) {
1539 edit.setTitle(tr("Edit Notebook"));
1540 edit.setNotebooks(listManager.getNotebookIndex());
1541 edit.setLocalCheckboxEnabled(false);
1542 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1543 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1544 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1545 i=listManager.getNotebookIndex().size();
1549 edit.setTitle(tr("Edit Stack"));
1550 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1551 edit.hideLocalCheckbox();
1552 edit.hideDefaultCheckbox();
1557 if (!edit.okPressed())
1561 if (guid.equalsIgnoreCase("STACK")) {
1562 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1563 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1564 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1565 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1566 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1568 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1569 currentSelection.setText(0, edit.getNotebook());
1573 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1574 currentSelection.setText(0, edit.getNotebook());
1576 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1577 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1578 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1579 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1580 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1581 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1582 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1583 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1585 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1586 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1587 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1588 linkedNotebook.setShareName(edit.getNotebook());
1589 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1591 i=listManager.getNotebookIndex().size();
1595 // Build a list of non-closed notebooks
1596 List<Notebook> nbooks = new ArrayList<Notebook>();
1597 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1598 boolean found=false;
1599 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1600 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1604 nbooks.add(listManager.getNotebookIndex().get(i));
1608 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1609 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1610 browserWindow.setNotebookList(filteredBooks);
1611 Iterator<String> set = externalWindows.keySet().iterator();
1612 while(set.hasNext())
1613 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1614 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1616 // Publish a notebook
1617 @SuppressWarnings("unused")
1618 private void publishNotebook() {
1619 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1620 QTreeWidgetItem currentSelection;
1621 currentSelection = selections.get(0);
1622 String guid = currentSelection.text(2);
1624 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1629 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1630 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1631 n = listManager.getNotebookIndex().get(i);
1633 i = listManager.getNotebookIndex().size();
1639 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1642 if (!publish.okClicked())
1645 Publishing p = publish.getPublishing();
1646 boolean isPublished = !publish.isStopPressed();
1647 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1648 n.setPublished(isPublished);
1650 listManager.getNotebookIndex().set(position, n);
1651 notebookIndexUpdated();
1653 // Publish a notebook
1654 @SuppressWarnings("unused")
1655 private void shareNotebook() {
1656 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1657 QTreeWidgetItem currentSelection;
1658 currentSelection = selections.get(0);
1659 String guid = currentSelection.text(2);
1661 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1665 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1666 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1667 n = listManager.getNotebookIndex().get(i);
1668 i = listManager.getNotebookIndex().size();
1672 String authToken = null;
1673 if (syncRunner.isConnected)
1674 authToken = syncRunner.authToken;
1675 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1680 // Delete an existing notebook
1681 @SuppressWarnings("unused")
1682 private void deleteNotebook() {
1683 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1684 boolean stacksFound = false;
1685 boolean notebooksFound = false;
1686 boolean assigned = false;
1687 // Check if any notes have this notebook
1688 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1689 for (int i=0; i<selections.size(); i++) {
1690 QTreeWidgetItem currentSelection;
1691 currentSelection = selections.get(i);
1692 String guid = currentSelection.text(2);
1693 if (!guid.equalsIgnoreCase("STACK")) {
1694 notebooksFound = true;
1695 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1696 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1697 if (noteGuid.equals(guid)) {
1699 j=listManager.getNoteIndex().size();
1700 i=selections.size();
1708 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1709 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1713 if (conn.getNotebookTable().getAll().size() == 1) {
1714 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1718 // If all notebooks are clear, verify the delete
1719 String msg1 = new String(tr("Delete selected notebooks?"));
1720 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1721 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1722 " not deleted unless selected?"));
1724 if (stacksFound && notebooksFound)
1726 if (!stacksFound && notebooksFound)
1728 if (stacksFound && !notebooksFound)
1730 if (QMessageBox.question(this, tr("Confirmation"), msg,
1731 QMessageBox.StandardButton.Yes,
1732 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1736 // If confirmed, delete the notebook
1737 for (int i=selections.size()-1; i>=0; i--) {
1738 QTreeWidgetItem currentSelection;
1739 currentSelection = selections.get(i);
1740 String guid = currentSelection.text(2);
1741 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1742 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1743 listManager.renameStack(currentSelection.text(0), "");
1745 conn.getNotebookTable().expungeNotebook(guid, true);
1746 listManager.deleteNotebook(guid);
1750 notebookIndexUpdated();
1751 // notebookTreeSelection();
1752 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1753 // listManager.countNotebookResults(listManager.getNoteIndex());
1754 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1756 // A note's notebook has been updated
1757 @SuppressWarnings("unused")
1758 private void updateNoteNotebook(String guid, String notebookGuid) {
1760 // Update the list manager
1761 listManager.updateNoteNotebook(guid, notebookGuid);
1762 listManager.countNotebookResults(listManager.getNoteIndex());
1763 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1765 // Find the name of the notebook
1766 String notebookName = null;
1767 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1768 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1769 notebookName = listManager.getNotebookIndex().get(i).getName();
1774 // If we found the name, update the browser window
1775 if (notebookName != null) {
1776 updateListNoteNotebook(guid, notebookName);
1777 if (guid.equals(currentNoteGuid)) {
1778 int pos = browserWindow.notebookBox.findText(notebookName);
1780 browserWindow.notebookBox.setCurrentIndex(pos);
1784 // If we're dealing with the current note, then we need to be sure and update the notebook there
1785 if (guid.equals(currentNoteGuid)) {
1786 if (currentNote != null) {
1787 currentNote.setNotebookGuid(notebookGuid);
1791 // Open/close notebooks
1792 @SuppressWarnings("unused")
1793 private void closeNotebooks() {
1794 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1796 if (!na.okClicked())
1800 listManager.getArchiveNotebookIndex().clear();
1802 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1803 String text = na.getClosedBookList().takeItem(i).text();
1804 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1805 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1806 Notebook n = listManager.getNotebookIndex().get(j);
1807 conn.getNotebookTable().setArchived(n.getGuid(),true);
1808 listManager.getArchiveNotebookIndex().add(n);
1809 j=listManager.getNotebookIndex().size();
1814 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1815 String text = na.getOpenBookList().takeItem(i).text();
1816 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1817 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1818 Notebook n = listManager.getNotebookIndex().get(j);
1819 conn.getNotebookTable().setArchived(n.getGuid(),false);
1820 j=listManager.getNotebookIndex().size();
1824 notebookTreeSelection();
1825 listManager.loadNotesIndex();
1826 notebookIndexUpdated();
1827 noteIndexUpdated(false);
1828 reloadTagTree(true);
1829 // noteIndexUpdated(false);
1831 // Build a list of non-closed notebooks
1832 List<Notebook> nbooks = new ArrayList<Notebook>();
1833 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1834 boolean found=false;
1835 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1836 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1840 nbooks.add(listManager.getNotebookIndex().get(i));
1843 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1844 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1845 browserWindow.setNotebookList(filteredBooks);
1847 // Update any external windows
1848 Iterator<String> set = externalWindows.keySet().iterator();
1849 while(set.hasNext())
1850 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1854 // Change the notebook's icon
1855 @SuppressWarnings("unused")
1856 private void setNotebookIcon() {
1857 boolean stackSelected = false;
1858 boolean allNotebookSelected = false;
1860 QTreeWidgetItem currentSelection;
1861 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1862 if (selections.size() == 0)
1865 currentSelection = selections.get(0);
1866 String guid = currentSelection.text(2);
1867 if (guid.equalsIgnoreCase(""))
1868 allNotebookSelected = true;
1869 if (guid.equalsIgnoreCase("STACK"))
1870 stackSelected = true;
1872 QIcon currentIcon = currentSelection.icon(0);
1876 if (!stackSelected && !allNotebookSelected) {
1877 icon = conn.getNotebookTable().getIcon(guid);
1879 dialog = new SetIcon(currentIcon, saveLastPath);
1880 dialog.setUseDefaultIcon(true);
1882 dialog = new SetIcon(icon, saveLastPath);
1883 dialog.setUseDefaultIcon(false);
1886 if (stackSelected) {
1887 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1889 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1892 dialog = new SetIcon(currentIcon, saveLastPath);
1893 dialog.setUseDefaultIcon(true);
1895 dialog = new SetIcon(icon, saveLastPath);
1896 dialog.setUseDefaultIcon(false);
1900 if (dialog.okPressed()) {
1901 saveLastPath = dialog.getPath();
1903 QIcon newIcon = dialog.getIcon();
1904 if (stackSelected) {
1905 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1906 if (newIcon == null) {
1907 newIcon = new QIcon(iconPath+"books2.png");
1909 currentSelection.setIcon(0,newIcon);
1912 if (allNotebookSelected) {
1913 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1914 if (newIcon == null) {
1915 newIcon = new QIcon(iconPath+"notebook-green.png");
1917 currentSelection.setIcon(0,newIcon);
1920 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1921 if (newIcon == null) {
1922 boolean isPublished = false;;
1923 boolean found = false;
1924 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1925 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1926 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1930 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1932 currentSelection.setIcon(0, newIcon);
1938 //***************************************************************
1939 //***************************************************************
1940 //** These functions deal with Tag menu items
1941 //***************************************************************
1942 //***************************************************************
1943 // Add a new notebook
1944 @SuppressWarnings("unused")
1945 private void addTag() {
1946 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1947 TagEdit edit = new TagEdit();
1948 edit.setTagList(listManager.getTagIndex());
1950 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1951 QTreeWidgetItem currentSelection = null;
1952 if (selections.size() > 0) {
1953 currentSelection = selections.get(0);
1954 edit.setParentTag(currentSelection.text(0));
1959 if (!edit.okPressed())
1962 Calendar currentTime = new GregorianCalendar();
1963 Long l = new Long(currentTime.getTimeInMillis());
1964 String randint = new String(Long.toString(l));
1966 Tag newTag = new Tag();
1967 newTag.setUpdateSequenceNum(0);
1968 newTag.setGuid(randint);
1969 newTag.setName(edit.getTag());
1970 if (edit.getParentTag().isChecked()) {
1971 newTag.setParentGuid(currentSelection.text(2));
1972 newTag.setParentGuidIsSet(true);
1973 currentSelection.setExpanded(true);
1975 conn.getTagTable().addTag(newTag, true);
1976 listManager.getTagIndex().add(newTag);
1977 reloadTagTree(true);
1979 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1981 @SuppressWarnings("unused")
1982 private void reloadTagTree() {
1983 reloadTagTree(false);
1985 private void reloadTagTree(boolean reload) {
1986 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1987 tagIndexUpdated(reload);
1988 boolean filter = false;
1990 listManager.countTagResults(listManager.getNoteIndex());
1991 if (notebookTree.selectedItems().size() > 0
1992 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1994 if (tagTree.selectedItems().size() > 0)
1996 tagTree.showAllTags(!filter);
1997 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1999 // Edit an existing tag
2000 @SuppressWarnings("unused")
2001 private void editTag() {
2002 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2003 TagEdit edit = new TagEdit();
2004 edit.setTitle("Edit Tag");
2005 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2006 QTreeWidgetItem currentSelection;
2007 currentSelection = selections.get(0);
2008 edit.setTag(currentSelection.text(0));
2009 edit.setTagList(listManager.getTagIndex());
2012 if (!edit.okPressed())
2015 String guid = currentSelection.text(2);
2016 currentSelection.setText(0,edit.getTag());
2018 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2019 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2020 listManager.getTagIndex().get(i).setName(edit.getTag());
2021 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2022 updateListTagName(guid);
2023 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2024 browserWindow.setTag(getTagNamesForNote(currentNote));
2025 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2029 browserWindow.setTag(getTagNamesForNote(currentNote));
2030 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2032 // Delete an existing tag
2033 @SuppressWarnings("unused")
2034 private void deleteTag() {
2035 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2037 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2038 QMessageBox.StandardButton.Yes,
2039 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2043 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2044 for (int i=selections.size()-1; i>=0; i--) {
2045 QTreeWidgetItem currentSelection;
2046 currentSelection = selections.get(i);
2047 removeTagItem(currentSelection.text(2));
2049 tagIndexUpdated(true);
2051 listManager.countTagResults(listManager.getNoteIndex());
2052 // tagTree.updateCounts(listManager.getTagCounter());
2053 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2055 // Remove a tag tree item. Go recursively down & remove the children too
2056 private void removeTagItem(String guid) {
2057 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2058 String parent = listManager.getTagIndex().get(j).getParentGuid();
2059 if (parent != null && parent.equals(guid)) {
2060 //Remove this tag's children
2061 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2064 //Now, remove this tag
2065 removeListTagName(guid);
2066 conn.getTagTable().expungeTag(guid, true);
2067 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2068 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2069 listManager.getTagIndex().remove(a);
2074 // Setup the tree containing the user's tags
2075 private void initializeTagTree() {
2076 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2077 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2078 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2079 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2080 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2081 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2083 // Listener when a tag is selected
2084 private void tagTreeSelection() {
2085 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2088 clearAttributeFilter();
2089 clearSavedSearchFilter();
2091 menuBar.noteRestoreAction.setVisible(false);
2093 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2094 QTreeWidgetItem currentSelection;
2095 selectedTagGUIDs.clear();
2096 for (int i=0; i<selections.size(); i++) {
2097 currentSelection = selections.get(i);
2098 selectedTagGUIDs.add(currentSelection.text(2));
2100 if (selections.size() > 0) {
2101 menuBar.tagEditAction.setEnabled(true);
2102 menuBar.tagDeleteAction.setEnabled(true);
2103 menuBar.tagIconAction.setEnabled(true);
2106 menuBar.tagEditAction.setEnabled(false);
2107 menuBar.tagDeleteAction.setEnabled(false);
2108 menuBar.tagIconAction.setEnabled(true);
2110 listManager.setSelectedTags(selectedTagGUIDs);
2111 listManager.loadNotesIndex();
2112 noteIndexUpdated(false);
2113 refreshEvernoteNote(true);
2114 listManager.refreshCounters = true;
2115 listManager.refreshCounters();
2116 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2118 // trigger the tag index to be refreshed
2119 @SuppressWarnings("unused")
2120 private void tagIndexUpdated() {
2121 tagIndexUpdated(true);
2123 private void tagIndexUpdated(boolean reload) {
2124 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2125 if (selectedTagGUIDs == null)
2126 selectedTagGUIDs = new ArrayList<String>();
2128 listManager.reloadTagIndex();
2130 tagTree.blockSignals(true);
2132 tagTree.setIcons(conn.getTagTable().getAllIcons());
2133 tagTree.load(listManager.getTagIndex());
2136 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2137 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2139 selectedTagGUIDs.remove(i);
2141 tagTree.blockSignals(false);
2143 browserWindow.setTag(getTagNamesForNote(currentNote));
2144 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2146 // Show/Hide note information
2147 @SuppressWarnings("unused")
2148 private void toggleTagWindow() {
2149 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2150 if (tagTree.isVisible())
2154 menuBar.hideTags.setChecked(tagTree.isVisible());
2155 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2156 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2158 // A note's tags have been updated
2159 @SuppressWarnings("unused")
2160 private void updateNoteTags(String guid, List<String> tags) {
2161 // Save any new tags. We'll need them later.
2162 List<String> newTags = new ArrayList<String>();
2163 for (int i=0; i<tags.size(); i++) {
2164 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2165 newTags.add(tags.get(i));
2168 listManager.saveNoteTags(guid, tags);
2169 listManager.countTagResults(listManager.getNoteIndex());
2170 StringBuffer names = new StringBuffer("");
2171 for (int i=0; i<tags.size(); i++) {
2172 names = names.append(tags.get(i));
2173 if (i<tags.size()-1) {
2174 names.append(Global.tagDelimeter + " ");
2177 browserWindow.setTag(names.toString());
2180 // Now, we need to add any new tags to the tag tree
2181 for (int i=0; i<newTags.size(); i++)
2182 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2184 // Get a string containing all tag names for a note
2185 private String getTagNamesForNote(Note n) {
2186 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2187 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2189 StringBuffer buffer = new StringBuffer(100);
2190 Vector<String> v = new Vector<String>();
2191 List<String> guids = n.getTagGuids();
2196 for (int i=0; i<guids.size(); i++) {
2197 v.add(listManager.getTagNameByGuid(guids.get(i)));
2199 Comparator<String> comparator = Collections.reverseOrder();
2200 Collections.sort(v,comparator);
2201 Collections.reverse(v);
2203 for (int i = 0; i<v.size(); i++) {
2205 buffer.append(", ");
2206 buffer.append(v.get(i));
2209 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2210 return buffer.toString();
2212 // Tags were added via dropping notes from the note list
2213 @SuppressWarnings("unused")
2214 private void tagsAdded(String noteGuid, String tagGuid) {
2215 String tagName = null;
2216 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2217 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2218 tagName = listManager.getTagIndex().get(i).getName();
2219 i=listManager.getTagIndex().size();
2222 if (tagName == null)
2225 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2226 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2227 List<String> tagNames = new ArrayList<String>();
2228 tagNames.add(new String(tagName));
2229 Note n = listManager.getMasterNoteIndex().get(i);
2230 for (int j=0; j<n.getTagNames().size(); j++) {
2231 tagNames.add(new String(n.getTagNames().get(j)));
2233 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2234 if (n.getGuid().equals(currentNoteGuid)) {
2235 Collections.sort(tagNames);
2236 String display = "";
2237 for (int j=0; j<tagNames.size(); j++) {
2238 display = display+tagNames.get(j);
2239 if (j+2<tagNames.size())
2240 display = display+Global.tagDelimeter+" ";
2242 browserWindow.setTag(display);
2244 i=listManager.getMasterNoteIndex().size();
2249 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2251 private void clearTagFilter() {
2252 tagTree.blockSignals(true);
2253 tagTree.clearSelection();
2254 menuBar.noteRestoreAction.setVisible(false);
2255 menuBar.tagEditAction.setEnabled(false);
2256 menuBar.tagDeleteAction.setEnabled(false);
2257 menuBar.tagIconAction.setEnabled(false);
2258 selectedTagGUIDs.clear();
2259 listManager.setSelectedTags(selectedTagGUIDs);
2260 tagTree.blockSignals(false);
2262 // Change the icon for a tag
2263 @SuppressWarnings("unused")
2264 private void setTagIcon() {
2265 QTreeWidgetItem currentSelection;
2266 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2267 if (selections.size() == 0)
2270 currentSelection = selections.get(0);
2271 String guid = currentSelection.text(2);
2273 QIcon currentIcon = currentSelection.icon(0);
2274 QIcon icon = conn.getTagTable().getIcon(guid);
2277 dialog = new SetIcon(currentIcon, saveLastPath);
2278 dialog.setUseDefaultIcon(true);
2280 dialog = new SetIcon(icon, saveLastPath);
2281 dialog.setUseDefaultIcon(false);
2284 if (dialog.okPressed()) {
2285 saveLastPath = dialog.getPath();
2286 QIcon newIcon = dialog.getIcon();
2287 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2288 if (newIcon == null)
2289 newIcon = new QIcon(iconPath+"tag.png");
2290 currentSelection.setIcon(0, newIcon);
2296 //***************************************************************
2297 //***************************************************************
2298 //** These functions deal with Saved Search menu items
2299 //***************************************************************
2300 //***************************************************************
2301 // Add a new notebook
2302 @SuppressWarnings("unused")
2303 private void addSavedSearch() {
2304 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2305 SavedSearchEdit edit = new SavedSearchEdit();
2306 edit.setSearchList(listManager.getSavedSearchIndex());
2309 if (!edit.okPressed())
2312 Calendar currentTime = new GregorianCalendar();
2313 Long l = new Long(currentTime.getTimeInMillis());
2314 String randint = new String(Long.toString(l));
2316 SavedSearch search = new SavedSearch();
2317 search.setUpdateSequenceNum(0);
2318 search.setGuid(randint);
2319 search.setName(edit.getName());
2320 search.setQuery(edit.getQuery());
2321 search.setFormat(QueryFormat.USER);
2322 listManager.getSavedSearchIndex().add(search);
2323 conn.getSavedSearchTable().addSavedSearch(search, true);
2324 savedSearchIndexUpdated();
2325 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2327 // Edit an existing tag
2328 @SuppressWarnings("unused")
2329 private void editSavedSearch() {
2330 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2331 SavedSearchEdit edit = new SavedSearchEdit();
2332 edit.setTitle(tr("Edit Search"));
2333 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2334 QTreeWidgetItem currentSelection;
2335 currentSelection = selections.get(0);
2336 String guid = currentSelection.text(1);
2337 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2338 edit.setName(currentSelection.text(0));
2339 edit.setQuery(s.getQuery());
2340 edit.setSearchList(listManager.getSavedSearchIndex());
2343 if (!edit.okPressed())
2346 List<SavedSearch> list = listManager.getSavedSearchIndex();
2347 SavedSearch search = null;
2348 boolean found = false;
2349 for (int i=0; i<list.size(); i++) {
2350 search = list.get(i);
2351 if (search.getGuid().equals(guid)) {
2358 search.setName(edit.getName());
2359 search.setQuery(edit.getQuery());
2360 conn.getSavedSearchTable().updateSavedSearch(search, true);
2361 savedSearchIndexUpdated();
2362 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2364 // Delete an existing tag
2365 @SuppressWarnings("unused")
2366 private void deleteSavedSearch() {
2367 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2369 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2370 QMessageBox.StandardButton.Yes,
2371 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2375 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2376 for (int i=selections.size()-1; i>=0; i--) {
2377 QTreeWidgetItem currentSelection;
2378 currentSelection = selections.get(i);
2379 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2380 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2381 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2382 listManager.getSavedSearchIndex().remove(j);
2383 j=listManager.getSavedSearchIndex().size()+1;
2386 selections.remove(i);
2388 savedSearchIndexUpdated();
2389 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2391 // Setup the tree containing the user's tags
2392 private void initializeSavedSearchTree() {
2393 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2394 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2395 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2397 // Listener when a tag is selected
2398 @SuppressWarnings("unused")
2399 private void savedSearchTreeSelection() {
2400 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2402 clearNotebookFilter();
2405 clearAttributeFilter();
2407 String currentGuid = selectedSavedSearchGUID;
2408 menuBar.savedSearchEditAction.setEnabled(true);
2409 menuBar.savedSearchDeleteAction.setEnabled(true);
2410 menuBar.savedSearchIconAction.setEnabled(true);
2411 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2412 QTreeWidgetItem currentSelection;
2413 selectedSavedSearchGUID = "";
2414 for (int i=0; i<selections.size(); i++) {
2415 currentSelection = selections.get(i);
2416 if (currentSelection.text(1).equals(currentGuid)) {
2417 currentSelection.setSelected(false);
2419 selectedSavedSearchGUID = currentSelection.text(1);
2421 // i = selections.size() +1;
2424 // There is the potential for no notebooks to be selected if this
2425 // happens then we make it look like all notebooks were selecetd.
2426 // If that happens, just select the "all notebooks"
2427 if (selections.size()==0) {
2428 clearSavedSearchFilter();
2430 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2432 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2434 private void clearSavedSearchFilter() {
2435 menuBar.savedSearchEditAction.setEnabled(false);
2436 menuBar.savedSearchDeleteAction.setEnabled(false);
2437 menuBar.savedSearchIconAction.setEnabled(false);
2438 savedSearchTree.blockSignals(true);
2439 savedSearchTree.clearSelection();
2440 savedSearchTree.blockSignals(false);
2441 selectedSavedSearchGUID = "";
2442 searchField.setEditText("");
2443 searchPerformed = false;
2444 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2446 // trigger the tag index to be refreshed
2447 private void savedSearchIndexUpdated() {
2448 if (selectedSavedSearchGUID == null)
2449 selectedSavedSearchGUID = new String();
2450 savedSearchTree.blockSignals(true);
2451 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2452 savedSearchTree.load(listManager.getSavedSearchIndex());
2453 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2454 savedSearchTree.blockSignals(false);
2456 // trigger when the saved search selection changes
2457 @SuppressWarnings("unused")
2458 private void updateSavedSearchSelection() {
2459 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2461 menuBar.savedSearchEditAction.setEnabled(true);
2462 menuBar.savedSearchDeleteAction.setEnabled(true);
2463 menuBar.savedSearchIconAction.setEnabled(true);
2464 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2466 if (selections.size() > 0) {
2467 menuBar.savedSearchEditAction.setEnabled(true);
2468 menuBar.savedSearchDeleteAction.setEnabled(true);
2469 menuBar.savedSearchIconAction.setEnabled(true);
2470 selectedSavedSearchGUID = selections.get(0).text(1);
2471 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2472 searchField.setEditText(s.getQuery());
2474 menuBar.savedSearchEditAction.setEnabled(false);
2475 menuBar.savedSearchDeleteAction.setEnabled(false);
2476 menuBar.savedSearchIconAction.setEnabled(false);
2477 selectedSavedSearchGUID = "";
2478 searchField.setEditText("");
2480 searchFieldChanged();
2482 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2486 // Show/Hide note information
2487 @SuppressWarnings("unused")
2488 private void toggleSavedSearchWindow() {
2489 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2490 if (savedSearchTree.isVisible())
2491 savedSearchTree.hide();
2493 savedSearchTree.show();
2494 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2496 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2497 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2499 // Change the icon for a saved search
2500 @SuppressWarnings("unused")
2501 private void setSavedSearchIcon() {
2502 QTreeWidgetItem currentSelection;
2503 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2504 if (selections.size() == 0)
2507 currentSelection = selections.get(0);
2508 String guid = currentSelection.text(1);
2510 QIcon currentIcon = currentSelection.icon(0);
2511 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2514 dialog = new SetIcon(currentIcon, saveLastPath);
2515 dialog.setUseDefaultIcon(true);
2517 dialog = new SetIcon(icon, saveLastPath);
2518 dialog.setUseDefaultIcon(false);
2521 if (dialog.okPressed()) {
2522 saveLastPath = dialog.getPath();
2523 QIcon newIcon = dialog.getIcon();
2524 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2525 if (newIcon == null)
2526 newIcon = new QIcon(iconPath+"search.png");
2527 currentSelection.setIcon(0, newIcon);
2535 //***************************************************************
2536 //***************************************************************
2537 //** These functions deal with Help menu & tool menu items
2538 //***************************************************************
2539 //***************************************************************
2540 // Show database status
2541 @SuppressWarnings("unused")
2542 private void databaseStatus() {
2544 indexRunner.interrupt = true;
2545 int dirty = conn.getNoteTable().getDirtyCount();
2546 int unindexed = conn.getNoteTable().getUnindexedCount();
2547 DatabaseStatus status = new DatabaseStatus();
2548 status.setUnsynchronized(dirty);
2549 status.setUnindexed(unindexed);
2550 status.setNoteCount(conn.getNoteTable().getNoteCount());
2551 status.setNotebookCount(listManager.getNotebookIndex().size());
2552 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2553 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2554 status.setTagCount(listManager.getTagIndex().size());
2555 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2556 status.setWordCount(conn.getWordsTable().getWordCount());
2560 // Compact the database
2561 @SuppressWarnings("unused")
2562 private void compactDatabase() {
2563 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2564 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2565 "but please be aware that depending upon the size of your database this can be time consuming " +
2566 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2567 QMessageBox.StandardButton.Yes,
2568 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2571 setMessage("Compacting database.");
2573 listManager.compactDatabase();
2575 setMessage("Database compact is complete.");
2576 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2578 @SuppressWarnings("unused")
2579 private void accountInformation() {
2580 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2581 AccountDialog dialog = new AccountDialog();
2583 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2585 @SuppressWarnings("unused")
2586 private void releaseNotes() {
2587 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2588 QDialog dialog = new QDialog(this);
2589 QHBoxLayout layout = new QHBoxLayout();
2590 QTextEdit textBox = new QTextEdit();
2591 layout.addWidget(textBox);
2592 textBox.setReadOnly(true);
2593 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2594 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2595 QIODevice.OpenModeFlag.Text)))
2597 textBox.setText(file.readAll().toString());
2599 dialog.setWindowTitle(tr("Release Notes"));
2600 dialog.setLayout(layout);
2602 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2604 // Called when user picks Log from the help menu
2605 @SuppressWarnings("unused")
2606 private void logger() {
2607 logger.log(logger.HIGH, "Entering NeverNote.logger");
2608 LogFileDialog dialog = new LogFileDialog(emitLog);
2610 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2612 // Menu option "help/about" was selected
2613 @SuppressWarnings("unused")
2614 private void about() {
2615 logger.log(logger.HIGH, "Entering NeverNote.about");
2616 QMessageBox.about(this,
2617 tr("About NeverNote"),
2618 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2620 +tr("<hr></center>Evernote"
2621 +"An Open Source Evernote Client.<br><br>"
2622 +"Licensed under GPL v2. <br><hr><br>"
2623 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2624 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2625 +"PDFRenderer is licened under the LGPL<br>"
2626 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2627 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2628 +"Jazzy is licened under the LGPL<br>"
2629 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2630 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2631 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2632 logger.log(logger.HIGH, "Leaving NeverNote.about");
2634 // Hide the entire left hand side
2635 @SuppressWarnings("unused")
2636 private void toggleLeftSide() {
2639 hidden = !menuBar.hideLeftSide.isChecked();
2640 menuBar.hideLeftSide.setChecked(!hidden);
2643 leftSplitter1.setHidden(true);
2645 leftSplitter1.setHidden(false);
2647 Global.saveWindowVisible("leftPanel", hidden);
2650 public void checkForUpdates() {
2651 // Send off thread to check for a new version
2652 versionChecker = new QNetworkAccessManager(this);
2653 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2654 QNetworkRequest request = new QNetworkRequest();
2655 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2656 versionChecker.get(request);
2658 @SuppressWarnings("unused")
2659 private void upgradeFileRead(QNetworkReply reply) {
2660 if (!reply.isReadable())
2663 String winVersion = Global.version;
2664 String osxVersion = Global.version;
2665 String linuxVersion = Global.version;
2666 String linux64Version = Global.version;
2667 String version = Global.version;
2669 // Determine the versions available
2670 QByteArray data = reply.readLine();
2671 while (data != null && !reply.atEnd()) {
2672 String line = data.toString();
2674 if (line.contains(":"))
2675 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2678 if (line.toLowerCase().contains("windows"))
2679 winVersion = lineVersion;
2680 else if (line.toLowerCase().contains("os-x"))
2681 osxVersion = lineVersion;
2682 else if (line.toLowerCase().contains("linux amd64"))
2683 linux64Version = lineVersion;
2684 else if (line.toLowerCase().contains("linux i386"))
2685 linuxVersion = lineVersion;
2686 else if (line.toLowerCase().contains("default"))
2687 version = lineVersion;
2689 // Read the next line
2690 data = reply.readLine();
2693 // Now we need to determine what system we are on.
2694 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2695 version = winVersion;
2696 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2697 version = osxVersion;
2698 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2699 if (System.getProperty("os.arch").contains("amd64") ||
2700 System.getProperty("os.arch").contains("x86_64"))
2701 version = linux64Version;
2703 version = linuxVersion;
2707 for (String validVersion : Global.validVersions) {
2708 if (version.equals(validVersion))
2712 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2714 if (dialog.remindMe())
2715 Global.setCheckVersionUpgrade(true);
2717 Global.setCheckVersionUpgrade(false);
2721 //***************************************************************
2722 //***************************************************************
2723 //** These functions deal with the Toolbar
2724 //***************************************************************
2725 //***************************************************************
2726 @SuppressWarnings("unused")
2727 private void focusSearch() {
2728 searchField.setFocus();
2731 // Text in the search bar has been cleared
2732 private void searchFieldCleared() {
2735 // This is done because we want to force a reload of
2736 // images. Some images we may want to highlight the text.
2737 readOnlyCache.clear();
2738 inkNoteCache.clear();
2740 QWebSettings.setMaximumPagesInCache(0);
2741 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2743 searchField.setEditText("");
2744 saveNoteColumnPositions();
2745 saveNoteIndexWidth();
2746 noteIndexUpdated(true);
2747 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2748 currentNote = listManager.getNoteIndex().get(0);
2749 currentNoteGuid = currentNote.getGuid();
2751 if (currentNote != null)
2752 loadNoteBrowserInformation(browserWindow);
2754 // text in the search bar changed. We only use this to tell if it was cleared,
2755 // otherwise we trigger off searchFieldChanged.
2756 @SuppressWarnings("unused")
2757 private void searchFieldTextChanged(String text) {
2758 QWebSettings.setMaximumPagesInCache(0);
2759 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2761 if (text.trim().equals("")) {
2762 searchFieldCleared();
2763 if (searchPerformed) {
2765 // This is done because we want to force a reload of
2766 // images. Some images we may want to highlight the text.
2768 readOnlyCache.clear();
2769 inkNoteCache.clear();
2771 listManager.setEnSearch("");
2772 listManager.loadNotesIndex();
2773 refreshEvernoteNote(true);
2774 noteIndexUpdated(false);
2776 searchPerformed = false;
2779 // Text in the toolbar has changed
2780 private void searchFieldChanged() {
2781 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2783 readOnlyCache.clear();
2784 inkNoteCache.clear();
2785 saveNoteColumnPositions();
2786 saveNoteIndexWidth();
2787 String text = searchField.currentText();
2788 listManager.setEnSearch(text.trim());
2789 listManager.loadNotesIndex();
2790 noteIndexUpdated(false);
2791 refreshEvernoteNote(true);
2792 searchPerformed = true;
2793 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2796 // Build the window tool bar
2797 private void setupToolBar() {
2798 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2799 toolBar = addToolBar(tr("Tool Bar"));
2800 toolBar.setObjectName("toolBar");
2801 menuBar.setupToolBarVisible();
2802 if (!Global.isWindowVisible("toolBar"))
2803 toolBar.setVisible(false);
2805 toolBar.setVisible(true);
2807 // toolBar.addWidget(menuBar);
2808 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2809 // toolBar.addSeparator();
2810 prevButton = toolBar.addAction("Previous");
2811 QIcon prevIcon = new QIcon(iconPath+"back.png");
2812 prevButton.setIcon(prevIcon);
2813 prevButton.triggered.connect(this, "previousViewedAction()");
2814 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2816 nextButton = toolBar.addAction("Next");
2817 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2818 nextButton.setIcon(nextIcon);
2819 nextButton.triggered.connect(this, "nextViewedAction()");
2820 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2822 upButton = toolBar.addAction("Up");
2823 QIcon upIcon = new QIcon(iconPath+"up.png");
2824 upButton.setIcon(upIcon);
2825 upButton.triggered.connect(this, "upAction()");
2826 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2829 downButton = toolBar.addAction("Down");
2830 QIcon downIcon = new QIcon(iconPath+"down.png");
2831 downButton.setIcon(downIcon);
2832 downButton.triggered.connect(this, "downAction()");
2833 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2835 synchronizeButton = toolBar.addAction("Synchronize");
2836 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2837 synchronizeIconAngle = 0;
2838 synchronizeButton.triggered.connect(this, "evernoteSync()");
2839 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2841 printButton = toolBar.addAction("Print");
2842 QIcon printIcon = new QIcon(iconPath+"print.png");
2843 printButton.setIcon(printIcon);
2844 printButton.triggered.connect(this, "printNote()");
2845 togglePrintButton(Global.isToolbarButtonVisible("print"));
2847 tagButton = toolBar.addAction("Tag");
2848 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2849 tagButton.setIcon(tagIcon);
2850 tagButton.triggered.connect(browserWindow, "modifyTags()");
2851 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2853 attributeButton = toolBar.addAction("Attributes");
2854 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2855 attributeButton.setIcon(attributeIcon);
2856 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2857 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2859 emailButton = toolBar.addAction("Email");
2860 QIcon emailIcon = new QIcon(iconPath+"email.png");
2861 emailButton.setIcon(emailIcon);
2862 emailButton.triggered.connect(this, "emailNote()");
2863 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2865 deleteButton = toolBar.addAction("Delete");
2866 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2867 deleteButton.setIcon(deleteIcon);
2868 deleteButton.triggered.connect(this, "deleteNote()");
2869 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2871 newButton = toolBar.addAction("New");
2872 QIcon newIcon = new QIcon(iconPath+"new.png");
2873 newButton.triggered.connect(this, "addNote()");
2874 newButton.setIcon(newIcon);
2875 toggleNewButton(Global.isToolbarButtonVisible("new"));
2877 allNotesButton = toolBar.addAction("All Notes");
2878 QIcon allIcon = new QIcon(iconPath+"books.png");
2879 allNotesButton.triggered.connect(this, "allNotes()");
2880 allNotesButton.setIcon(allIcon);
2881 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2883 //toolBar.addSeparator();
2884 //toolBar.addWidget(new QLabel(tr("Quota:")));
2885 //toolBar.addWidget(quotaBar);
2886 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2888 //toolBar.addSeparator();
2890 //toolBar.addWidget(new QLabel(tr("Zoom")));
2891 //toolBar.addWidget(zoomSpinner);
2893 //toolBar.addWidget(new QLabel(" "));
2894 //toolBar.addSeparator();
2895 //toolBar.addWidget(new QLabel(tr(" Search:")));
2896 //toolBar.addWidget(searchField);
2897 QSizePolicy sizePolicy = new QSizePolicy();
2898 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2899 QLabel spacer = new QLabel("");
2900 spacer.setSizePolicy(sizePolicy);
2901 toolBar.addWidget(spacer);
2902 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2904 //searchClearButton = toolBar.addAction("Search Clear");
2905 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2906 //searchClearButton.setIcon(searchClearIcon);
2907 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2908 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2910 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2912 // Update the sychronize button picture
2914 public QMenu createPopupMenu() {
2915 QMenu contextMenu = super.createPopupMenu();
2917 contextMenu.addSeparator();
2918 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2919 contextMenu.addAction(prevAction);
2920 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2922 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2923 contextMenu.addAction(nextAction);
2924 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2926 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2927 contextMenu.addAction(upAction);
2928 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2930 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2931 contextMenu.addAction(downAction);
2932 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2934 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2935 contextMenu.addAction(synchronizeAction);
2936 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2938 QAction printAction = addContextAction("print", tr("Print"));
2939 contextMenu.addAction(printAction);
2940 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2942 QAction tagAction = addContextAction("tag", tr("Tag"));
2943 contextMenu.addAction(tagAction);
2944 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2946 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2947 contextMenu.addAction(attributeAction);
2948 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2950 QAction emailAction = addContextAction("email", tr("Email"));
2951 contextMenu.addAction(emailAction);
2952 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2954 QAction deleteAction = addContextAction("delete", tr("Delete"));
2955 contextMenu.addAction(deleteAction);
2956 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2958 QAction newAction = addContextAction("new", tr("Add"));
2959 contextMenu.addAction(newAction);
2960 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2962 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2963 contextMenu.addAction(allNotesAction);
2964 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2966 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2967 contextMenu.addAction(searchClearAction);
2968 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2973 private QAction addContextAction(String config, String name) {
2974 QAction newAction = new QAction(this);
2975 newAction.setText(name);
2976 newAction.setCheckable(true);
2977 newAction.setChecked(Global.isToolbarButtonVisible(config));
2980 private void togglePrevArrowButton(Boolean toggle) {
2981 prevButton.setVisible(toggle);
2982 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2984 private void toggleNextArrowButton(Boolean toggle) {
2985 nextButton.setVisible(toggle);
2986 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2988 private void toggleUpArrowButton(Boolean toggle) {
2989 upButton.setVisible(toggle);
2990 Global.saveToolbarButtonsVisible("upArrow", toggle);
2992 private void toggleDownArrowButton(Boolean toggle) {
2993 downButton.setVisible(toggle);
2994 Global.saveToolbarButtonsVisible("downArrow", toggle);
2996 private void toggleSynchronizeButton(Boolean toggle) {
2997 synchronizeButton.setVisible(toggle);
2998 Global.saveToolbarButtonsVisible("synchronize", toggle);
3000 private void togglePrintButton(Boolean toggle) {
3001 printButton.setVisible(toggle);
3002 Global.saveToolbarButtonsVisible("print", toggle);
3004 private void toggleTagButton(Boolean toggle) {
3005 tagButton.setVisible(toggle);
3006 Global.saveToolbarButtonsVisible("tag", toggle);
3008 private void toggleAttributeButton(Boolean toggle) {
3009 attributeButton.setVisible(toggle);
3010 Global.saveToolbarButtonsVisible("attribute", toggle);
3012 private void toggleEmailButton(Boolean toggle) {
3013 emailButton.setVisible(toggle);
3014 Global.saveToolbarButtonsVisible("email", toggle);
3016 private void toggleDeleteButton(Boolean toggle) {
3017 deleteButton.setVisible(toggle);
3018 Global.saveToolbarButtonsVisible("delete", toggle);
3020 private void toggleNewButton(Boolean toggle) {
3021 newButton.setVisible(toggle);
3022 Global.saveToolbarButtonsVisible("new", toggle);
3024 private void toggleAllNotesButton(Boolean toggle) {
3025 allNotesButton.setVisible(toggle);
3026 Global.saveToolbarButtonsVisible("allNotes", toggle);
3028 @SuppressWarnings("unused")
3029 private void toggleSearchClearButton(Boolean toggle) {
3030 searchClearButton.setVisible(toggle);
3031 Global.saveToolbarButtonsVisible("searchClear", toggle);
3038 @SuppressWarnings("unused")
3039 private void updateSyncButton() {
3041 if (syncIcons == null) {
3042 syncIcons = new ArrayList<QPixmap>();
3044 synchronizeIconAngle = 0;
3045 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3047 for (int i=0; i<=360; i++) {
3048 QPixmap rotatedPix = new QPixmap(pix.size());
3049 QPainter p = new QPainter(rotatedPix);
3050 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3051 QSize size = pix.size();
3052 p.translate(size.width()/2, size.height()/2);
3055 p.setBackgroundMode(BGMode.OpaqueMode);
3056 p.translate(-size.width()/2, -size.height()/2);
3057 p.drawPixmap(0,0, pix);
3059 syncIcons.add(rotatedPix);
3063 synchronizeIconAngle++;
3064 if (synchronizeIconAngle > 359)
3065 synchronizeIconAngle=0;
3066 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3069 // Synchronize with Evernote
3070 @SuppressWarnings("unused")
3071 private void evernoteSync() {
3072 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3073 if (!Global.isConnected)
3075 if (Global.isConnected)
3076 synchronizeAnimationTimer.start(5);
3077 // synchronizeAnimationTimer.start(200);
3079 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3081 private void updateQuotaBar() {
3082 long limit = Global.getUploadLimit();
3083 long amount = Global.getUploadAmount();
3084 if (amount>0 && limit>0) {
3085 int percent =(int)(amount*100/limit);
3086 quotaBar.setValue(percent);
3088 quotaBar.setValue(0);
3091 @SuppressWarnings("unused")
3092 private void zoomChanged() {
3093 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3096 //****************************************************************
3097 //****************************************************************
3098 //* System Tray functions
3099 //****************************************************************
3100 //****************************************************************
3101 private void trayToggleVisible() {
3106 if (windowMaximized)
3113 @SuppressWarnings("unused")
3114 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3115 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3116 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3117 trayToggleVisible();
3122 //***************************************************************
3123 //***************************************************************
3124 //** These functions deal with the trash tree
3125 //***************************************************************
3126 //***************************************************************
3127 // Setup the tree containing the trash.
3128 @SuppressWarnings("unused")
3129 private void trashTreeSelection() {
3130 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3132 clearNotebookFilter();
3134 clearAttributeFilter();
3135 clearSavedSearchFilter();
3137 String tempGuid = currentNoteGuid;
3139 // currentNoteGuid = "";
3140 currentNote = new Note();
3141 selectedNoteGUIDs.clear();
3142 listManager.getSelectedNotebooks().clear();
3143 listManager.getSelectedTags().clear();
3144 listManager.setSelectedSavedSearch("");
3145 browserWindow.clear();
3147 // toggle the add buttons
3148 newButton.setEnabled(!newButton.isEnabled());
3149 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3150 menuBar.noteAdd.setVisible(true);
3152 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3153 if (selections.size() == 0) {
3154 currentNoteGuid = trashNoteGuid;
3155 trashNoteGuid = tempGuid;
3156 Global.showDeleted = false;
3157 menuBar.noteRestoreAction.setEnabled(false);
3158 menuBar.noteRestoreAction.setVisible(false);
3161 currentNoteGuid = trashNoteGuid;
3162 trashNoteGuid = tempGuid;
3163 menuBar.noteRestoreAction.setEnabled(true);
3164 menuBar.noteRestoreAction.setVisible(true);
3165 Global.showDeleted = true;
3167 listManager.loadNotesIndex();
3168 noteIndexUpdated(false);
3169 //// browserWindow.setEnabled(newButton.isEnabled());
3170 browserWindow.setReadOnly(!newButton.isEnabled());
3171 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3173 // Empty the trash file
3174 @SuppressWarnings("unused")
3175 private void emptyTrash() {
3176 // browserWindow.clear();
3177 listManager.emptyTrash();
3178 if (trashTree.selectedItems().size() > 0) {
3179 listManager.getSelectedNotebooks().clear();
3180 listManager.getSelectedTags().clear();
3181 listManager.setSelectedSavedSearch("");
3182 newButton.setEnabled(!newButton.isEnabled());
3183 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3184 menuBar.noteAdd.setVisible(true);
3185 browserWindow.clear();
3188 clearNotebookFilter();
3189 clearSavedSearchFilter();
3190 clearAttributeFilter();
3192 Global.showDeleted = false;
3193 menuBar.noteRestoreAction.setEnabled(false);
3194 menuBar.noteRestoreAction.setVisible(false);
3196 listManager.loadNotesIndex();
3197 noteIndexUpdated(false);
3200 // Show/Hide trash window
3201 @SuppressWarnings("unused")
3202 private void toggleTrashWindow() {
3203 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3204 if (trashTree.isVisible())
3208 menuBar.hideTrash.setChecked(trashTree.isVisible());
3210 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3211 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3213 private void clearTrashFilter() {
3214 Global.showDeleted = false;
3215 newButton.setEnabled(true);
3216 menuBar.noteAdd.setEnabled(true);
3217 menuBar.noteAdd.setVisible(true);
3218 trashTree.blockSignals(true);
3219 trashTree.clearSelection();
3220 trashTree.blockSignals(false);
3225 //***************************************************************
3226 //***************************************************************
3227 //** These functions deal with connection settings
3228 //***************************************************************
3229 //***************************************************************
3230 // SyncRunner had a problem and things are disconnected
3231 @SuppressWarnings("unused")
3232 private void remoteErrorDisconnect() {
3233 menuBar.connectAction.setText(tr("Connect"));
3234 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3235 menuBar.synchronizeAction.setEnabled(false);
3236 Global.isConnected = false;
3237 synchronizeAnimationTimer.stop();
3240 // Do a manual connect/disconnect
3241 private void remoteConnect() {
3242 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3244 if (Global.isConnected) {
3245 Global.isConnected = false;
3246 syncRunner.enDisconnect();
3247 setupConnectMenuOptions();
3252 AESEncrypter aes = new AESEncrypter();
3254 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3255 } catch (FileNotFoundException e) {
3256 // File not found, so we'll just get empty strings anyway.
3259 if (Global.getProxyValue("url").equals("")) {
3260 System.setProperty("http.proxyHost","") ;
3261 System.setProperty("http.proxyPort", "") ;
3262 System.setProperty("https.proxyHost","") ;
3263 System.setProperty("https.proxyPort", "") ;
3266 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3267 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3268 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3269 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3271 if (Global.getProxyValue("userid").equals("")) {
3272 Authenticator.setDefault(new Authenticator() {
3274 protected PasswordAuthentication getPasswordAuthentication() {
3276 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3282 syncRunner.userStoreUrl = Global.userStoreUrl;
3283 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3284 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3286 String userid = aes.getUserid();
3287 String password = aes.getPassword();
3288 if (!userid.equals("") && !password.equals("")) {
3289 Global.username = userid;
3290 Global.password = password;
3291 syncRunner.username = Global.username;
3292 syncRunner.password = Global.password;
3293 syncRunner.enConnect();
3296 Global.isConnected = syncRunner.isConnected;
3298 if (!Global.isConnected) {
3299 // Show the login dialog box
3300 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3301 LoginDialog login = new LoginDialog();
3304 if (!login.okPressed()) {
3308 Global.username = login.getUserid();
3309 Global.password = login.getPassword();
3311 syncRunner.username = Global.username;
3312 syncRunner.password = Global.password;
3313 syncRunner.enConnect();
3314 Global.isConnected = syncRunner.isConnected;
3317 if (!Global.isConnected)
3320 setupConnectMenuOptions();
3321 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3323 private void setupConnectMenuOptions() {
3324 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3325 if (!Global.isConnected) {
3326 menuBar.connectAction.setText(tr("Connect"));
3327 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3328 menuBar.synchronizeAction.setEnabled(false);
3330 menuBar.connectAction.setText(tr("Disconnect"));
3331 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3332 menuBar.synchronizeAction.setEnabled(true);
3334 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3339 //***************************************************************
3340 //***************************************************************
3341 //** These functions deal with the GUI Attribute tree
3342 //***************************************************************
3343 //***************************************************************
3344 @SuppressWarnings("unused")
3345 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3347 // clearTagFilter();
3348 // clearNotebookFilter();
3350 // clearSavedSearchFilter();
3352 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3353 if (item.childCount() > 0) {
3354 item.setSelected(false);
3356 Global.createdBeforeFilter.reset();
3357 Global.createdSinceFilter.reset();
3358 Global.changedBeforeFilter.reset();
3359 Global.changedSinceFilter.reset();
3360 Global.containsFilter.reset();
3361 attributeTreeSelected = item;
3362 DateAttributeFilterTable f = null;
3363 f = findDateAttributeFilterTable(item.parent());
3365 f.select(item.parent().indexOfChild(item));
3367 Global.containsFilter.select(item.parent().indexOfChild(item));
3370 listManager.loadNotesIndex();
3371 noteIndexUpdated(false);
3374 attributeTreeSelected = null;
3375 item.setSelected(false);
3376 Global.createdBeforeFilter.reset();
3377 Global.createdSinceFilter.reset();
3378 Global.changedBeforeFilter.reset();
3379 Global.changedSinceFilter.reset();
3380 Global.containsFilter.reset();
3381 listManager.loadNotesIndex();
3382 noteIndexUpdated(false);
3384 // This determines what attribute filter we need, depending upon the selection
3385 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3386 if (w.parent() != null && w.childCount() > 0) {
3387 QTreeWidgetItem parent = w.parent();
3388 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3389 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3390 return Global.createdSinceFilter;
3391 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3392 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3393 return Global.createdBeforeFilter;
3394 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3395 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3396 return Global.changedSinceFilter;
3397 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3398 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3399 return Global.changedBeforeFilter;
3404 // Show/Hide attribute search window
3405 @SuppressWarnings("unused")
3406 private void toggleAttributesWindow() {
3407 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3408 if (attributeTree.isVisible())
3409 attributeTree.hide();
3411 attributeTree.show();
3412 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3414 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3415 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3417 private void clearAttributeFilter() {
3418 Global.createdBeforeFilter.reset();
3419 Global.createdSinceFilter.reset();
3420 Global.changedBeforeFilter.reset();
3421 Global.changedSinceFilter.reset();
3422 Global.containsFilter.reset();
3423 attributeTreeSelected = null;
3424 attributeTree.blockSignals(true);
3425 attributeTree.clearSelection();
3426 attributeTree.blockSignals(false);
3430 //***************************************************************
3431 //***************************************************************
3432 //** These functions deal with the GUI Note index table
3433 //***************************************************************
3434 //***************************************************************
3435 // Initialize the note list table
3436 private void initializeNoteTable() {
3437 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3438 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3439 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3440 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3442 // Show/Hide trash window
3443 @SuppressWarnings("unused")
3444 private void toggleNoteListWindow() {
3445 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3446 if (noteTableView.isVisible())
3447 noteTableView.hide();
3449 noteTableView.show();
3450 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3452 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3453 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3455 // Handle the event that a user selects a note from the table
3456 @SuppressWarnings("unused")
3457 private void noteTableSelection() {
3458 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3460 if (historyGuids.size() == 0) {
3461 historyGuids.add(currentNoteGuid);
3462 historyPosition = 1;
3464 noteTableView.showColumn(Global.noteTableGuidPosition);
3466 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3467 if (!Global.isColumnVisible("guid"))
3468 noteTableView.hideColumn(Global.noteTableGuidPosition);
3470 if (selections.size() > 0) {
3472 menuBar.noteDuplicateAction.setEnabled(true);
3473 menuBar.noteOnlineHistoryAction.setEnabled(true);
3474 menuBar.noteMergeAction.setEnabled(true);
3475 selectedNoteGUIDs.clear();
3476 if (selections.size() != 1 || Global.showDeleted) {
3477 menuBar.noteDuplicateAction.setEnabled(false);
3479 if (selections.size() != 1 || !Global.isConnected) {
3480 menuBar.noteOnlineHistoryAction.setEnabled(false);
3482 if (selections.size() == 1) {
3483 menuBar.noteMergeAction.setEnabled(false);
3485 for (int i=0; i<selections.size(); i++) {
3486 int row = selections.get(i).row();
3488 upButton.setEnabled(false);
3490 upButton.setEnabled(true);
3491 if (row < listManager.getNoteTableModel().rowCount()-1)
3492 downButton.setEnabled(true);
3494 downButton.setEnabled(false);
3495 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3496 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3497 currentNoteGuid = (String)ix.values().toArray()[0];
3498 selectedNoteGUIDs.add(currentNoteGuid);
3502 nextButton.setEnabled(true);
3503 prevButton.setEnabled(true);
3505 int endPosition = historyGuids.size()-1;
3506 for (int j=historyPosition; j<=endPosition; j++) {
3507 historyGuids.remove(historyGuids.size()-1);
3509 historyGuids.add(currentNoteGuid);
3510 historyPosition = historyGuids.size();
3512 if (historyPosition <= 1)
3513 prevButton.setEnabled(false);
3514 if (historyPosition == historyGuids.size())
3515 nextButton.setEnabled(false);
3517 fromHistory = false;
3518 scrollToGuid(currentNoteGuid);
3519 refreshEvernoteNote(true);
3520 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3522 // Trigger a refresh when the note db has been updated
3523 private void noteIndexUpdated(boolean reload) {
3524 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3526 refreshEvernoteNoteList();
3527 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3528 noteTableView.load(reload);
3529 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3531 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3532 pos = noteTableView.proxyModel.rowCount();
3535 if (noteTableView.proxyModel.rowCount() == 0)
3538 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3540 currentNoteGuid = (String)i.data();
3544 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3546 scrollToGuid(currentNoteGuid);
3547 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3549 // Called when the list of notes is updated
3550 private void refreshEvernoteNoteList() {
3551 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3552 browserWindow.setDisabled(false);
3553 if (selectedNoteGUIDs == null)
3554 selectedNoteGUIDs = new ArrayList<String>();
3555 selectedNoteGUIDs.clear(); // clear out old entries
3557 String saveCurrentNoteGuid = new String();
3558 String tempNoteGuid = new String();
3560 historyGuids.clear();
3561 historyPosition = 0;
3562 prevButton.setEnabled(false);
3563 nextButton.setEnabled(false);
3565 if (currentNoteGuid == null)
3566 currentNoteGuid = new String();
3568 //determine current note guid
3569 for (Note note : listManager.getNoteIndex()) {
3570 tempNoteGuid = note.getGuid();
3571 if (currentNoteGuid.equals(tempNoteGuid)) {
3572 saveCurrentNoteGuid = tempNoteGuid;
3576 if (listManager.getNoteIndex().size() == 0) {
3577 currentNoteGuid = "";
3579 browserWindow.clear();
3580 browserWindow.setDisabled(true);
3583 if (!saveCurrentNoteGuid.equals("")) {
3584 refreshEvernoteNote(false);
3586 currentNoteGuid = "";
3588 reloadTagTree(false);
3590 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3592 // Called when the previous arrow button is clicked
3593 @SuppressWarnings("unused")
3594 private void previousViewedAction() {
3595 if (!prevButton.isEnabled())
3597 if (historyPosition == 0)
3600 if (historyPosition <= 0)
3602 String historyGuid = historyGuids.get(historyPosition-1);
3604 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3605 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3606 if (modelIndex != null) {
3607 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3608 String tableGuid = (String)ix.values().toArray()[0];
3609 if (tableGuid.equals(historyGuid)) {
3610 noteTableView.selectRow(i);
3616 @SuppressWarnings("unused")
3617 private void nextViewedAction() {
3618 if (!nextButton.isEnabled())
3620 String historyGuid = historyGuids.get(historyPosition);
3623 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3624 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3625 if (modelIndex != null) {
3626 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3627 String tableGuid = (String)ix.values().toArray()[0];
3628 if (tableGuid.equals(historyGuid)) {
3629 noteTableView.selectRow(i);
3635 // Called when the up arrow is clicked
3636 @SuppressWarnings("unused")
3637 private void upAction() {
3638 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3639 int row = selections.get(0).row();
3641 noteTableView.selectRow(row-1);
3644 // Called when the down arrow is clicked
3645 @SuppressWarnings("unused")
3646 private void downAction() {
3647 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3648 int row = selections.get(0).row();
3649 int max = listManager.getNoteTableModel().rowCount();
3651 noteTableView.selectRow(row+1);
3654 // Update a tag string for a specific note in the list
3655 @SuppressWarnings("unused")
3656 private void updateListTags(String guid, List<String> tags) {
3657 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3658 StringBuffer tagBuffer = new StringBuffer();
3659 for (int i=0; i<tags.size(); i++) {
3660 tagBuffer.append(tags.get(i));
3661 if (i<tags.size()-1)
3662 tagBuffer.append(", ");
3665 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3666 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3667 if (modelIndex != null) {
3668 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3669 String tableGuid = (String)ix.values().toArray()[0];
3670 if (tableGuid.equals(guid)) {
3671 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3672 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3673 noteTableView.proxyModel.invalidate();
3678 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3680 // Update a title for a specific note in the list
3681 @SuppressWarnings("unused")
3682 private void updateListAuthor(String guid, String author) {
3683 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3685 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3686 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3687 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3688 if (modelIndex != null) {
3689 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3690 String tableGuid = (String)ix.values().toArray()[0];
3691 if (tableGuid.equals(guid)) {
3692 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3693 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3694 noteTableView.proxyModel.invalidate();
3700 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3702 private void updateListNoteNotebook(String guid, String notebook) {
3703 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3704 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3705 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3707 // Update a title for a specific note in the list
3708 @SuppressWarnings("unused")
3709 private void updateListSourceUrl(String guid, String url) {
3710 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3712 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3713 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3714 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3715 if (modelIndex != null) {
3716 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3717 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3718 String tableGuid = (String)ix.values().toArray()[0];
3719 if (tableGuid.equals(guid)) {
3720 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3721 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3722 noteTableView.proxyModel.invalidate();
3727 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3729 @SuppressWarnings("unused")
3730 private void updateListGuid(String oldGuid, String newGuid) {
3731 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3733 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3734 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3735 if (modelIndex != null) {
3736 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3737 String tableGuid = (String)ix.values().toArray()[0];
3738 if (tableGuid.equals(oldGuid)) {
3739 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3740 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3745 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3747 private void updateListTagName(String guid) {
3748 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3750 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3751 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3752 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3754 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3755 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3756 if (modelIndex != null) {
3757 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3758 String noteGuid = (String)ix.values().toArray()[0];
3759 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3760 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3761 i=listManager.getNoteTableModel().rowCount();
3767 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3769 private void removeListTagName(String guid) {
3770 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3772 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3773 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3774 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3775 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3776 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3779 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3780 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3781 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3782 if (modelIndex != null) {
3783 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3784 String noteGuid = (String)ix.values().toArray()[0];
3785 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3786 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3787 i=listManager.getNoteTableModel().rowCount();
3793 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3795 private void updateListNotebookName(String oldName, String newName) {
3796 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3798 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3799 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3800 if (modelIndex != null) {
3801 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3802 String tableName = (String)ix.values().toArray()[0];
3803 if (tableName.equalsIgnoreCase(oldName)) {
3804 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3808 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3810 @SuppressWarnings("unused")
3811 private void updateListDateCreated(String guid, QDateTime date) {
3812 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3814 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3815 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3816 if (modelIndex != null) {
3817 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3818 String tableGuid = (String)ix.values().toArray()[0];
3819 if (tableGuid.equals(guid)) {
3820 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3821 noteTableView.proxyModel.invalidate();
3826 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3828 @SuppressWarnings("unused")
3829 private void updateListDateSubject(String guid, QDateTime date) {
3830 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3832 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3833 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3834 if (modelIndex != null) {
3835 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3836 String tableGuid = (String)ix.values().toArray()[0];
3837 if (tableGuid.equals(guid)) {
3838 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3839 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3840 noteTableView.proxyModel.invalidate();
3845 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3847 private void updateListDateChanged(String guid, QDateTime date) {
3848 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3850 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3851 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3852 if (modelIndex != null) {
3853 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3854 String tableGuid = (String)ix.values().toArray()[0];
3855 if (tableGuid.equals(guid)) {
3856 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3857 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3862 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3864 private void updateListDateChanged() {
3865 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3866 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3867 updateListDateChanged(currentNoteGuid, date);
3868 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3871 private void scrollToCurrentGuid() {
3872 //scrollToGuid(currentNoteGuid);
3873 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3874 if (selections.size() == 0)
3876 QModelIndex index = selections.get(0);
3877 int row = selections.get(0).row();
3878 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3881 // Scroll to the current GUID in tthe list.
3882 // Scroll to a particular index item
3883 private void scrollToGuid(String guid) {
3884 if (currentNote == null || guid == null)
3886 if (currentNote.isActive() && Global.showDeleted) {
3887 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3888 if (!listManager.getNoteIndex().get(i).isActive()) {
3889 currentNote = listManager.getNoteIndex().get(i);
3890 currentNoteGuid = currentNote.getGuid();
3891 i = listManager.getNoteIndex().size();
3895 if (!currentNote.isActive() && !Global.showDeleted) {
3896 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3897 if (listManager.getNoteIndex().get(i).isActive()) {
3898 currentNote = listManager.getNoteIndex().get(i);
3899 currentNoteGuid = currentNote.getGuid();
3900 i = listManager.getNoteIndex().size();
3905 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3906 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3907 if (currentNoteGuid.equals(index.data())) {
3908 // noteTableView.selectionModel().blockSignals(true);
3909 noteTableView.selectRow(i);
3910 // noteTableView.selectionModel().blockSignals(false);
3911 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3912 i=listManager.getNoteTableModel().rowCount();
3915 noteTableView.repaint();
3917 // Show/Hide columns
3918 private void showColumns() {
3919 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3920 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3921 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3922 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3923 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3924 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3925 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3926 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3927 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3928 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3929 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3931 // Title color has changed
3932 @SuppressWarnings("unused")
3933 private void titleColorChanged(Integer color) {
3934 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3936 QColor backgroundColor = new QColor();
3937 QColor foregroundColor = new QColor(QColor.black);
3938 backgroundColor.setRgb(color);
3940 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3941 foregroundColor.setRgb(QColor.white.rgb());
3943 if (selectedNoteGUIDs.size() == 0)
3944 selectedNoteGUIDs.add(currentNoteGuid);
3946 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3947 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3948 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3949 if (modelIndex != null) {
3950 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3951 String tableGuid = (String)ix.values().toArray()[0];
3952 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3953 for (int k=0; k<Global.noteTableColumnCount; k++) {
3954 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3955 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3956 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3958 i=listManager.getNoteTableModel().rowCount();
3963 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3965 // Wide list was chosen
3966 public void narrowListView() {
3967 saveNoteColumnPositions();
3968 saveNoteIndexWidth();
3970 int sortCol = noteTableView.proxyModel.sortColumn();
3971 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3972 Global.setSortColumn(sortCol);
3973 Global.setSortOrder(sortOrder);
3975 Global.setListView(Global.View_List_Narrow);
3977 menuBar.wideListView.blockSignals(true);
3978 menuBar.narrowListView.blockSignals(true);
3980 menuBar.wideListView.setChecked(false);
3981 menuBar.narrowListView.setChecked(true);
3983 menuBar.wideListView.blockSignals(false);
3984 menuBar.narrowListView.blockSignals(false);
3986 mainLeftRightSplitter.addWidget(noteTableView);
3987 mainLeftRightSplitter.addWidget(browserWindow);
3988 restoreWindowState(false);
3989 noteTableView.repositionColumns();
3990 noteTableView.resizeColumnWidths();
3991 noteTableView.resizeRowHeights();
3993 sortCol = Global.getSortColumn();
3994 sortOrder = Global.getSortOrder();
3995 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3998 noteTableView.load(false);
3999 scrollToCurrentGuid();
4001 public void wideListView() {
4002 int sortCol = noteTableView.proxyModel.sortColumn();
4003 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4004 Global.setSortColumn(sortCol);
4005 Global.setSortOrder(sortOrder);
4008 saveNoteColumnPositions();
4009 saveNoteIndexWidth();
4010 Global.setListView(Global.View_List_Wide);
4012 menuBar.wideListView.blockSignals(true);
4013 menuBar.narrowListView.blockSignals(true);
4015 menuBar.wideListView.setChecked(true);
4016 menuBar.narrowListView.setChecked(false);
4018 menuBar.wideListView.blockSignals(false);
4019 menuBar.narrowListView.blockSignals(false);
4020 browserIndexSplitter.setVisible(true);
4021 browserIndexSplitter.addWidget(noteTableView);
4022 browserIndexSplitter.addWidget(browserWindow);
4023 restoreWindowState(false);
4024 noteTableView.repositionColumns();
4025 noteTableView.resizeColumnWidths();
4026 noteTableView.resizeRowHeights();
4028 sortCol = Global.getSortColumn();
4029 sortOrder = Global.getSortOrder();
4030 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4033 noteTableView.load(false);
4034 scrollToCurrentGuid();
4038 //***************************************************************
4039 //***************************************************************
4040 //** External editor window functions
4041 //***************************************************************
4042 //***************************************************************
4043 private void listDoubleClick() {
4045 if (externalWindows.containsKey(currentNoteGuid)) {
4046 externalWindows.get(currentNoteGuid).raise();
4049 // We have a new external editor to create
4050 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4051 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4052 newBrowser.setWindowIcon(appIcon);
4053 externalWindows.put(currentNoteGuid, newBrowser);
4054 showEditorButtons(newBrowser.getBrowserWindow());
4055 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
4056 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4057 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4058 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4059 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4060 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4062 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4063 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4064 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4065 browserWindow.blockApplication.connect(this, "blockApplication(Long)");
4066 browserWindow.unblockApplication.connect(this, "unblockApplication()");
4070 @SuppressWarnings("unused")
4071 private void externalWindowTitleEdited(String guid, String text) {
4072 if (guid.equals(currentNoteGuid)) {
4073 browserWindow.setTitle(text);
4076 @SuppressWarnings({ "rawtypes", "unused" })
4077 private void externalWindowTagsEdited(String guid, List values) {
4078 StringBuffer line = new StringBuffer(100);
4079 for (int i=0; i<values.size(); i++) {
4081 line.append(Global.tagDelimeter+" ");
4082 line.append(values.get(i));
4084 if (guid.equals(currentNoteGuid)) {
4085 browserWindow.setTag(line.toString());
4088 @SuppressWarnings("unused")
4089 private void externalWindowClosing(String guid) {
4090 externalWindows.remove(guid);
4095 //***************************************************************
4096 //***************************************************************
4097 //** These functions deal with Note specific things
4098 //***************************************************************
4099 //***************************************************************
4100 @SuppressWarnings("unused")
4101 private void setNoteDirty() {
4102 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4104 // Find if the note is being edited externally. If it is, update it.
4105 if (externalWindows.containsKey(currentNoteGuid)) {
4106 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4107 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4108 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4109 window.getBrowserWindow().getBrowser().setContent(unicode);
4112 // If the note is dirty, then it is unsynchronized by default.
4116 // Set the note as dirty and check if its status is synchronized in the display table
4118 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4119 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4123 // If this wasn't already marked as unsynchronized, then we need to update the table
4124 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4125 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4126 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4127 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4128 if (modelIndex != null) {
4129 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4130 String tableGuid = (String)ix.values().toArray()[0];
4131 if (tableGuid.equals(currentNoteGuid)) {
4132 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4138 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4140 @SuppressWarnings("unused")
4141 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4142 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4143 QByteArray unicode = codec.fromUnicode(content);
4144 noteCache.remove(guid);
4145 noteCache.put(guid, unicode.toString());
4146 if (guid.equals(currentNoteGuid)) {
4148 browserWindow.getBrowser().setContent(unicode);
4151 thumbnailRunner.addWork("GENERATE "+ guid);
4152 saveNote(guid, browser);
4156 private void saveNote() {
4158 saveNote(currentNoteGuid, browserWindow);
4159 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4163 private void saveNote(String guid, BrowserWindow window) {
4164 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4165 logger.log(logger.EXTREME, "Note is dirty.");
4168 logger.log(logger.EXTREME, "Saving to cache");
4169 QTextCodec codec = QTextCodec.codecForLocale();
4170 // QTextDecoder decoder = codec.makeDecoder();
4171 codec = QTextCodec.codecForName("UTF-8");
4172 QByteArray unicode = codec.fromUnicode(window.getContent());
4173 noteCache.put(guid, unicode.toString());
4175 logger.log(logger.EXTREME, "updating list manager");
4176 listManager.updateNoteContent(guid, window.getContent());
4177 logger.log(logger.EXTREME, "Updating title");
4178 listManager.updateNoteTitle(guid, window.getTitle());
4179 updateListDateChanged();
4181 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4182 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4183 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4184 currentNote = listManager.getNoteIndex().get(i);
4185 i = listManager.getNoteIndex().size();
4190 // Get a note from Evernote (and put it in the browser)
4191 private void refreshEvernoteNote(boolean reload) {
4192 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4194 if (Global.disableViewing) {
4195 browserWindow.setEnabled(false);
4200 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4202 Global.cryptCounter =0;
4204 browserWindow.setReadOnly(true);
4212 browserWindow.loadingData(true);
4214 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4215 if (currentNote == null)
4217 loadNoteBrowserInformation(browserWindow);
4220 private void loadNoteBrowserInformation(BrowserWindow browser) {
4221 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4222 formatter.setNote(currentNote, Global.pdfPreview());
4223 formatter.setHighlight(listManager.getEnSearch());
4225 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4226 js = new QByteArray();
4227 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4228 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4229 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>");
4230 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4231 js.append("<style> img { max-width:100%; }</style>");
4232 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4233 js.append("</head>");
4234 formatter.setNote(currentNote, Global.pdfPreview());
4235 js.append(formatter.rebuildNoteHTML());
4236 js.append("</HTML>");
4237 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4238 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4239 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4240 browser.getBrowser().setContent(js);
4241 noteCache.put(currentNoteGuid, js.toString());
4243 if (formatter.resourceError)
4244 resourceErrorMessage();
4245 readOnly = formatter.readOnly;
4246 inkNote = formatter.inkNote;
4248 readOnlyCache.put(currentNoteGuid, true);
4250 inkNoteCache.put(currentNoteGuid, true);
4252 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4253 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4254 js = new QByteArray(cachedContent);
4255 browser.getBrowser().setContent(js);
4256 if (readOnlyCache.containsKey(currentNoteGuid))
4258 if (inkNoteCache.containsKey(currentNoteGuid))
4261 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4262 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4264 if (readOnly || inkNote)
4265 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4267 browser.getBrowser().page().setContentEditable(true);
4268 browser.setReadOnly(readOnly);
4269 deleteButton.setEnabled(!readOnly);
4270 tagButton.setEnabled(!readOnly);
4271 menuBar.noteDelete.setEnabled(!readOnly);
4272 menuBar.noteTags.setEnabled(!readOnly);
4273 browser.setNote(currentNote);
4275 if (currentNote != null && currentNote.getNotebookGuid() != null &&
4276 conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4277 deleteButton.setEnabled(false);
4278 menuBar.notebookDeleteAction.setEnabled(false);
4280 deleteButton.setEnabled(true);
4281 menuBar.notebookDeleteAction.setEnabled(true);
4284 // Build a list of non-closed notebooks
4285 List<Notebook> nbooks = new ArrayList<Notebook>();
4286 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4287 boolean found=false;
4288 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4289 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4293 nbooks.add(listManager.getNotebookIndex().get(i));
4296 browser.setTitle(currentNote.getTitle());
4297 browser.setTag(getTagNamesForNote(currentNote));
4298 browser.setAuthor(currentNote.getAttributes().getAuthor());
4300 browser.setAltered(currentNote.getUpdated());
4301 browser.setCreation(currentNote.getCreated());
4302 if (currentNote.getAttributes().getSubjectDate() > 0)
4303 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4305 browser.setSubjectDate(currentNote.getCreated());
4306 browser.setUrl(currentNote.getAttributes().getSourceURL());
4308 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4309 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4310 browser.setAllTags(tagList);
4312 browser.setCurrentTags(currentNote.getTagNames());
4314 scrollToGuid(currentNoteGuid);
4316 browser.loadingData(false);
4317 if (thumbnailViewer.isActiveWindow())
4320 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4321 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4324 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4326 // Save a generated thumbnail
4327 private void toggleNoteInformation() {
4328 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4329 browserWindow.toggleInformation();
4330 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4331 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4332 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4334 // Listener triggered when a print button is pressed
4335 @SuppressWarnings("unused")
4336 private void printNote() {
4337 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4339 QPrintDialog dialog = new QPrintDialog();
4340 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4341 QPrinter printer = dialog.printer();
4342 browserWindow.getBrowser().print(printer);
4344 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4347 // Listener triggered when the email button is pressed
4348 @SuppressWarnings("unused")
4349 private void emailNote() {
4350 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4352 if (Desktop.isDesktopSupported()) {
4353 Desktop desktop = Desktop.getDesktop();
4355 String text2 = browserWindow.getContentsToEmail();
4356 QUrl url = new QUrl("mailto:");
4357 url.addQueryItem("subject", currentNote.getTitle());
4358 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4359 url.addQueryItem("body", text2);
4360 QDesktopServices.openUrl(url);
4364 if (desktop.isSupported(Desktop.Action.MAIL)) {
4365 URI uriMailTo = null;
4367 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4368 String text = browserWindow.getContentsToEmail();
4369 //text = "<b>" +text +"</b>";
4370 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4371 +"&BODY=" +text, null);
4372 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4373 +"&ATTACHMENT=d:/test.pdf", null);
4374 desktop.mail(uriMailTo);
4375 } catch (URISyntaxException e) {
4376 e.printStackTrace();
4377 } catch (IOException e) {
4378 e.printStackTrace();
4385 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4387 // Reindex all notes
4388 @SuppressWarnings("unused")
4389 private void fullReindex() {
4390 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4391 indexRunner.addWork("REINDEXALL");
4392 setMessage(tr("Database will be reindexed."));
4393 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4395 // Listener when a user wants to reindex a specific note
4396 @SuppressWarnings("unused")
4397 private void reindexNote() {
4398 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4399 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4400 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4402 if (selectedNotebookGUIDs.size() > 1)
4403 setMessage(tr("Notes will be reindexed."));
4405 setMessage(tr("Note will be reindexed."));
4406 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4409 @SuppressWarnings("unused")
4410 private void deleteNote() {
4411 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4412 if (currentNote == null)
4414 if (currentNoteGuid.equals(""))
4416 String title = null;
4417 if (selectedNoteGUIDs.size() == 1)
4418 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4420 // If we are deleting non-trash notes
4421 if (currentNote.isActive()) {
4422 if (Global.verifyDelete()) {
4424 if (selectedNoteGUIDs.size() > 1) {
4425 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4428 msg = new String(tr("Delete note \"") +title +"\"?");
4430 msg = new String(tr("Delete note selected note?"));
4432 if (QMessageBox.question(this, tr("Confirmation"), msg,
4433 QMessageBox.StandardButton.Yes,
4434 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4438 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4439 selectedNoteGUIDs.add(currentNoteGuid);
4440 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4441 listManager.deleteNote(selectedNoteGUIDs.get(i));
4444 // If we are deleting from the trash.
4445 if (Global.verifyDelete()) {
4447 if (selectedNoteGUIDs.size() > 1) {
4448 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4451 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4453 msg = new String(tr("Permanently delete note selected note?"));
4455 if (QMessageBox.question(this, "Confirmation", msg,
4456 QMessageBox.StandardButton.Yes,
4457 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4461 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4462 selectedNoteGUIDs.add(currentNoteGuid);
4463 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4464 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4465 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4466 if (modelIndex != null) {
4467 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4468 String tableGuid = (String)ix.values().toArray()[0];
4469 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4470 listManager.getNoteTableModel().removeRow(j);
4475 listManager.expungeNote(selectedNoteGUIDs.get(i));
4478 currentNoteGuid = "";
4479 listManager.loadNotesIndex();
4480 noteIndexUpdated(false);
4481 refreshEvernoteNote(true);
4482 scrollToGuid(currentNoteGuid);
4483 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4486 @SuppressWarnings("unused")
4487 private void addNote() {
4488 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4489 // browserWindow.setEnabled(true);
4490 browserWindow.setReadOnly(false);
4492 Calendar currentTime = new GregorianCalendar();
4493 StringBuffer noteString = new StringBuffer(100);
4494 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4495 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4498 if (Global.overrideDefaultFont()) {
4499 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4500 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4501 noteString.append("<br clear=\"none\" />\n");
4502 noteString.append("</span>\n</font>\n");
4504 noteString.append("<br clear=\"none\" />\n");
4505 noteString.append("</en-note>");
4507 Long l = new Long(currentTime.getTimeInMillis());
4508 String randint = new String(Long.toString(l));
4510 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4512 // for the first non-archived notebook. Finally, if nothing else we
4513 // pick the first notebook in the list.
4514 String notebook = null;
4515 listManager.getNotebookIndex().get(0).getGuid();
4516 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4517 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4518 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4519 notebook = currentSelectedNotebook.text(2);
4521 boolean found = false;
4522 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4523 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4524 boolean match = false;
4525 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4526 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4528 j = listManager.getArchiveNotebookIndex().size();
4532 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4533 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4535 // Now we have a list of good notebooks, so we can look for the default
4537 for (int i=0; i<goodNotebooks.size(); i++) {
4538 if (goodNotebooks.get(i).isDefaultNotebook()) {
4539 notebook = goodNotebooks.get(i).getGuid();
4541 i = goodNotebooks.size();
4545 if (goodNotebooks.size() > 0 && !found)
4546 notebook = goodNotebooks.get(0).getGuid();
4549 notebook = listManager.getNotebookIndex().get(0).getGuid();
4552 Note newNote = new Note();
4553 newNote.setUpdateSequenceNum(0);
4554 newNote.setGuid(randint);
4555 newNote.setNotebookGuid(notebook);
4556 newNote.setTitle("");
4557 newNote.setContent(noteString.toString());
4558 newNote.setDeleted(0);
4559 newNote.setCreated(System.currentTimeMillis());
4560 newNote.setUpdated(System.currentTimeMillis());
4561 newNote.setActive(true);
4562 NoteAttributes na = new NoteAttributes();
4563 na.setLatitude(0.0);
4564 na.setLongitude(0.0);
4565 na.setAltitude(0.0);
4566 newNote.setAttributes(new NoteAttributes());
4567 newNote.setTagGuids(new ArrayList<String>());
4568 newNote.setTagNames(new ArrayList<String>());
4570 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4571 if (Global.newNoteWithSelectedTags()) {
4572 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4573 QTreeWidgetItem currentSelection;
4574 for (int i=0; i<selections.size(); i++) {
4575 currentSelection = selections.get(i);
4576 newNote.getTagGuids().add(currentSelection.text(2));
4577 newNote.getTagNames().add(currentSelection.text(0));
4581 conn.getNoteTable().addNote(newNote, true);
4582 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4583 listManager.addNote(newNote);
4584 // noteTableView.insertRow(newNote, true, -1);
4586 currentNote = newNote;
4587 currentNoteGuid = currentNote.getGuid();
4588 noteTableView.clearSelection();
4589 refreshEvernoteNote(true);
4590 listManager.countNotebookResults(listManager.getNoteIndex());
4591 browserWindow.titleLabel.setFocus();
4592 browserWindow.titleLabel.selectAll();
4593 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4595 // If the window is hidden, then we want to popup this in an external window &
4598 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4600 // Restore a note from the trash;
4601 @SuppressWarnings("unused")
4602 private void restoreNote() {
4604 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4605 selectedNoteGUIDs.add(currentNoteGuid);
4606 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4607 listManager.restoreNote(selectedNoteGUIDs.get(i));
4609 currentNoteGuid = "";
4610 listManager.loadNotesIndex();
4611 noteIndexUpdated(false);
4614 // Search a note for specific txt
4615 @SuppressWarnings("unused")
4616 private void findText() {
4618 find.setFocusOnTextField();
4620 @SuppressWarnings("unused")
4621 private void doFindText() {
4622 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4625 @SuppressWarnings("unused")
4626 private void updateNoteTitle(String guid, String title) {
4627 listManager.setNoteSynchronized(guid, false);
4629 // Signal received that note content has changed. Normally we just need the guid to remove
4630 // it from the cache.
4631 @SuppressWarnings("unused")
4632 private void invalidateNoteCache(String guid, String content) {
4633 String v = noteCache.remove(guid);
4634 // if (guid.equals(currentNoteGuid) && !noteDirty)
4635 refreshEvernoteNote(true);
4637 // Signal received that a note guid has changed
4638 @SuppressWarnings("unused")
4639 private void noteGuidChanged(String oldGuid, String newGuid) {
4640 if (noteCache.containsKey(oldGuid)) {
4641 if (!oldGuid.equals(currentNoteGuid)) {
4642 String cache = noteCache.get(oldGuid);
4643 noteCache.put(newGuid, cache);
4644 noteCache.remove(oldGuid);
4646 noteCache.remove(oldGuid);
4647 noteCache.put(newGuid, browserWindow.getContent());
4651 listManager.updateNoteGuid(oldGuid, newGuid, false);
4652 if (currentNoteGuid.equals(oldGuid)) {
4653 if (currentNote != null)
4654 currentNote.setGuid(newGuid);
4655 currentNoteGuid = newGuid;
4658 if (externalWindows.containsKey(oldGuid)) {
4659 ExternalBrowse b = externalWindows.get(oldGuid);
4660 externalWindows.remove(oldGuid);
4661 b.getBrowserWindow().getNote().setGuid(newGuid);
4662 externalWindows.put(newGuid, b);
4665 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4666 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4667 noteTableView.proxyModel.addGuid(newGuid);
4668 i=listManager.getNoteIndex().size();
4672 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4673 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4674 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4675 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4679 // Toggle the note editor button bar
4680 private void toggleEditorButtonBar() {
4681 if (browserWindow.buttonsVisible) {
4682 browserWindow.hideButtons();
4683 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4684 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4686 browserWindow.buttonsVisible = true;
4687 showEditorButtons(browserWindow);
4689 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4691 // Show editor buttons
4692 private void showEditorButtons(BrowserWindow browser) {
4693 browser.buttonLayout.setVisible(true);
4694 browser.undoAction.setVisible(false);
4696 browser.undoButton.setVisible(false);
4698 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4699 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4700 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4701 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4702 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4703 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4704 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4705 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4706 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4707 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4708 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4709 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4710 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4711 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4712 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4713 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4714 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4715 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4716 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4717 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4718 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4719 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4720 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4722 private void duplicateNote(String guid) {
4724 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4725 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4726 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4727 oldNote.setResources(resList);
4728 duplicateNote(oldNote);
4730 private void duplicateNote(Note oldNote) {
4732 // Now that we have a good notebook guid, we need to move the conflicting note
4733 // to the local notebook
4734 Calendar currentTime = new GregorianCalendar();
4735 Long l = new Long(currentTime.getTimeInMillis());
4736 String newGuid = new String(Long.toString(l));
4738 // Note newNote = oldNote.deepCopy();
4739 Note newNote = (Note)Global.deepCopy(oldNote);
4740 newNote.setUpdateSequenceNum(0);
4741 newNote.setGuid(newGuid);
4742 newNote.setDeleted(0);
4743 newNote.setActive(true);
4746 List<String> tagNames = new ArrayList<String>();
4747 List<String> tagGuids = new ArrayList<String>();;
4748 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4749 tagNames.add(oldNote.getTagNames().get(i));
4750 tagGuids.add(oldNote.getTagGuids().get(i));
4753 // Sort note Tags to make them look nice
4754 for (int i=0; i<tagNames.size()-1; i++) {
4755 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4756 String n1 = tagNames.get(i);
4757 String n2 = tagNames.get(i+1);
4758 tagNames.set(i, n2);
4759 tagNames.set(i+1, n1);
4762 newNote.setTagGuids(tagGuids);
4763 newNote.setTagNames(tagNames);
4765 // Add tag guids to note
4768 // Duplicate resources
4769 List<Resource> resList = oldNote.getResources();
4770 if (resList == null)
4771 resList = new ArrayList<Resource>();
4773 for (int i=0; i<resList.size(); i++) {
4775 while (l == prevGuid) {
4776 currentTime = new GregorianCalendar();
4777 l = new Long(currentTime.getTimeInMillis());
4780 String newResGuid = new String(Long.toString(l));
4781 resList.get(i).setNoteGuid(newGuid);
4782 resList.get(i).setGuid(newResGuid);
4783 resList.get(i).setUpdateSequenceNum(0);
4784 resList.get(i).setActive(true);
4785 conn.getNoteTable().noteResourceTable.saveNoteResource(
4786 (Resource)Global.deepCopy(resList.get(i)), true);
4788 newNote.setResources(resList);
4790 // Add note to the database
4791 listManager.addNote(newNote);
4792 conn.getNoteTable().addNote(newNote, true);
4793 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4794 noteTableView.insertRow(newNote, true, -1);
4795 currentNoteGuid = newNote.getGuid();
4796 currentNote = newNote;
4797 refreshEvernoteNote(true);
4798 listManager.countNotebookResults(listManager.getNoteIndex());
4802 @SuppressWarnings("unused")
4803 private void allNotes() {
4804 clearAttributeFilter();
4805 clearNotebookFilter();
4806 clearSavedSearchFilter();
4809 searchField.clear();
4810 if (Global.mimicEvernoteInterface) {
4811 notebookTree.selectGuid("");
4813 notebookTreeSelection();
4816 @SuppressWarnings("unused")
4817 private void mergeNotes() {
4818 logger.log(logger.HIGH, "Merging notes");
4821 String masterGuid = null;
4822 List<String> sources = new ArrayList<String>();
4824 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4825 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4826 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4827 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4829 masterGuid = (String)ix.values().toArray()[0];
4831 sources.add((String)ix.values().toArray()[0]);
4834 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4835 logger.log(logger.EXTREME, "Children count: "+sources.size());
4836 mergeNoteContents(masterGuid, sources);
4837 currentNoteGuid = masterGuid;
4838 noteIndexUpdated(false);
4839 refreshEvernoteNote(true);
4842 private void mergeNoteContents(String targetGuid, List<String> sources) {
4843 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4844 String newContent = target.getContent();
4845 newContent = newContent.replace("</en-note>", "<br></br>");
4847 for (int i=0; i<sources.size(); i++) {
4848 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4849 if (source.isSetTitle()) {
4850 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4852 String sourceContent = source.getContent();
4853 logger.log(logger.EXTREME, "Merging contents into note");
4854 logger.log(logger.EXTREME, sourceContent);
4855 logger.log(logger.EXTREME, "End of content");
4856 int startOfNote = sourceContent.indexOf("<en-note>");
4857 sourceContent = sourceContent.substring(startOfNote+9);
4858 int endOfNote = sourceContent.indexOf("</en-note>");
4859 sourceContent = sourceContent.substring(0,endOfNote);
4860 newContent = newContent + sourceContent;
4861 logger.log(logger.EXTREME, "New note content");
4862 logger.log(logger.EXTREME, newContent);
4863 logger.log(logger.EXTREME, "End of content");
4864 for (int j=0; j<source.getResourcesSize(); j++) {
4865 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4866 Resource r = source.getResources().get(j);
4867 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4869 Calendar currentTime = new GregorianCalendar();
4870 Long l = new Long(currentTime.getTimeInMillis());
4874 while (l == prevGuid) {
4875 currentTime = new GregorianCalendar();
4876 l = new Long(currentTime.getTimeInMillis());
4878 String newResGuid = new String(Long.toString(l));
4879 newRes.setNoteGuid(targetGuid);
4880 newRes.setGuid(newResGuid);
4881 newRes.setUpdateSequenceNum(0);
4882 newRes.setActive(true);
4883 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4886 logger.log(logger.EXTREME, "Updating note");
4887 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4888 for (int i=0; i<sources.size(); i++) {
4889 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4890 listManager.deleteNote(sources.get(i));
4892 logger.log(logger.EXTREME, "Exiting merge note");
4894 // A resource within a note has had a guid change
4895 @SuppressWarnings("unused")
4896 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4897 if (!oldGuid.equals(newGuid))
4898 Global.resourceMap.put(oldGuid, newGuid);
4900 // View a thumbnail of the note
4901 public void thumbnailView() {
4903 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4904 QFile thumbnail = new QFile(thumbnailName);
4905 if (!thumbnail.exists()) {
4907 QImage img = new QImage();
4908 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4909 thumbnailViewer.setThumbnail(img);
4911 thumbnailViewer.setThumbnail(thumbnailName);
4912 if (!thumbnailViewer.isVisible())
4913 thumbnailViewer.showFullScreen();
4915 // An error happened while saving a note. Inform the user
4916 @SuppressWarnings("unused")
4917 private void saveRunnerError(String guid, String msg) {
4919 String title = "*Unknown*";
4920 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4921 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4922 title = listManager.getMasterNoteIndex().get(i).getTitle();
4923 i=listManager.getMasterNoteIndex().size();
4926 msg = "An error has happened while saving the note \"" +title+
4927 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4928 "As a result, changes to the note may not be saved properly in the database."+
4929 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4930 "\nbe lost. Please review the note to recover any critical data before restarting.";
4932 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4935 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4936 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4937 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4938 // Find an idle preview object
4939 for (int i=0; i<thumbGenerators.size(); i++) {
4940 if (thumbGenerators.get(i).mutex.tryLock()) {
4941 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4942 thumbGenerators.get(i).loadContent(guid, html, zoom);
4946 if (thumbGenerators.size() >= 1) {
4947 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4951 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4952 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4953 thumbGenerators.add(preview);
4955 if (preview.mutex.tryLock()) {
4956 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4957 preview.loadContent(guid, html, zoom);
4959 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4964 //**********************************************************
4965 //**********************************************************
4966 //* Online user actions
4967 //**********************************************************
4968 //**********************************************************
4969 private void setupOnlineMenu() {
4970 if (!Global.isConnected) {
4971 menuBar.noteOnlineHistoryAction.setEnabled(false);
4972 menuBar.selectiveSyncAction.setEnabled(false);
4975 menuBar.noteOnlineHistoryAction.setEnabled(true);
4976 menuBar.selectiveSyncAction.setEnabled(true);
4979 @SuppressWarnings("unused")
4980 private void viewNoteHistory() {
4981 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4983 if (currentNote.getUpdateSequenceNum() == 0) {
4984 setMessage(tr("Note has never been synchronized."));
4985 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4989 setMessage(tr("Getting Note History"));
4991 Note currentOnlineNote = null;
4994 if (Global.isPremium())
4995 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4997 versions = new ArrayList<NoteVersionId>();
4998 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4999 } catch (EDAMUserException e) {
5000 setMessage("EDAMUserException: " +e.getMessage());
5002 } catch (EDAMSystemException e) {
5003 setMessage("EDAMSystemException: " +e.getMessage());
5005 } catch (EDAMNotFoundException e) {
5006 setMessage(tr("Note not found on server."));
5007 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
5009 } catch (TException e) {
5010 setMessage("EDAMTransactionException: " +e.getMessage());
5014 // If we've gotten this far, we have a good note.
5015 if (historyWindow == null) {
5016 historyWindow = new OnlineNoteHistory(logger, conn);
5017 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5018 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5019 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5021 historyWindow.historyCombo.clear();
5023 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5024 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5026 historyWindow.setCurrent(isDirty);
5028 loadHistoryWindowContent(currentOnlineNote);
5029 historyWindow.load(versions);
5030 setMessage(tr("History retrieved"));
5032 historyWindow.exec();
5034 private Note reloadHistoryWindow(String selection) {
5036 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5037 String dateTimeFormat = new String(fmt);
5038 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5042 for (int i=0; i<versions.size(); i++) {
5043 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5044 if (versionDate.toString().equals(selection))
5048 if (index > -1 || selection.indexOf("Current") > -1) {
5049 Note historyNote = null;
5052 usn = versions.get(index).getUpdateSequenceNum();
5053 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5055 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5056 } catch (EDAMUserException e) {
5057 setMessage("EDAMUserException: " +e.getMessage());
5060 } catch (EDAMSystemException e) {
5061 setMessage("EDAMSystemException: " +e.getMessage());
5064 } catch (EDAMNotFoundException e) {
5065 setMessage("EDAMNotFoundException: " +e.getMessage());
5068 } catch (TException e) {
5069 setMessage("EDAMTransactionException: " +e.getMessage());
5075 if (historyNote != null)
5076 historyWindow.setContent(historyNote);
5082 private void loadHistoryWindowContent(Note note) {
5083 note.setUpdateSequenceNum(0);
5084 historyWindow.setContent(note);
5086 @SuppressWarnings("unused")
5087 private void restoreHistoryNoteAsNew() {
5088 setMessage(tr("Restoring as new note."));
5089 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5090 setMessage(tr("Note has been restored as a new note."));
5092 @SuppressWarnings("unused")
5093 private void restoreHistoryNote() {
5094 setMessage(tr("Restoring note."));
5095 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5096 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5099 for (int i=0; i<n.getResourcesSize(); i++) {
5100 n.getResources().get(i).setActive(true);
5101 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5103 listManager.addNote(n);
5104 conn.getNoteTable().addNote(n, true);
5105 refreshEvernoteNote(true);
5106 setMessage(tr("Note has been restored."));
5108 @SuppressWarnings("unused")
5109 private void setupSelectiveSync() {
5111 // Get a list of valid notebooks
5112 List<Notebook> notebooks = null;
5113 List<Tag> tags = null;
5114 List<LinkedNotebook> linkedNotebooks = null;
5116 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5117 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5118 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5119 } catch (EDAMUserException e) {
5120 setMessage("EDAMUserException: " +e.getMessage());
5122 } catch (EDAMSystemException e) {
5123 setMessage("EDAMSystemException: " +e.getMessage());
5125 } catch (TException e) {
5126 setMessage("EDAMTransactionException: " +e.getMessage());
5128 } catch (EDAMNotFoundException e) {
5129 setMessage("EDAMNotFoundException: " +e.getMessage());
5133 // Split up notebooks into synchronized & non-synchronized
5134 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5135 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5137 for (int i=notebooks.size()-1; i>=0; i--) {
5138 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5139 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5140 ignoredBooks.add(notebooks.get(i));
5141 j=dbIgnoredNotebooks.size();
5146 // split up tags into synchronized & non-synchronized
5147 List<Tag> ignoredTags = new ArrayList<Tag>();
5148 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5150 for (int i=tags.size()-1; i>=0; i--) {
5151 for (int j=0; j<dbIgnoredTags.size(); j++) {
5152 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5153 ignoredTags.add(tags.get(i));
5154 j=dbIgnoredTags.size();
5159 // split up linked notebooks into synchronized & non-synchronized
5160 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5161 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5162 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5163 String notebookGuid = linkedNotebooks.get(i).getGuid();
5164 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5165 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5166 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5167 j=dbIgnoredLinkedNotebooks.size();
5172 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5174 if (!ignore.okClicked())
5179 // Clear out old notebooks & add the new ones
5180 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5181 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5182 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5185 List<String> newNotebooks = new ArrayList<String>();
5186 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5187 String text = ignore.getIgnoredBookList().takeItem(i).text();
5188 for (int j=0; j<notebooks.size(); j++) {
5189 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5190 Notebook n = notebooks.get(j);
5191 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5193 newNotebooks.add(n.getGuid());
5198 // Clear out old tags & add new ones
5199 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5200 for (int i=0; i<oldIgnoreTags.size(); i++) {
5201 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5204 List<String> newTags = new ArrayList<String>();
5205 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5206 String text = ignore.getIgnoredTagList().takeItem(i).text();
5207 for (int j=0; j<tags.size(); j++) {
5208 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5209 Tag t = tags.get(j);
5210 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5211 newTags.add(t.getGuid());
5217 // Clear out old tags & add new ones
5218 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5219 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5220 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5223 List<String> newLinked = new ArrayList<String>();
5224 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5225 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5226 for (int j=0; j<linkedNotebooks.size(); j++) {
5227 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5228 LinkedNotebook t = linkedNotebooks.get(j);
5229 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5230 newLinked.add(t.getGuid());
5231 j=linkedNotebooks.size();
5236 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5242 //**********************************************************
5243 //**********************************************************
5244 //* XML Modifying methods
5245 //**********************************************************
5246 //**********************************************************
5247 // An error has happended fetching a resource. let the user know
5248 private void resourceErrorMessage() {
5251 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5252 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5253 "In a perfect world this wouldn't happen, but it has.\n" +
5254 "It is embarasing when a program like me, designed to save all your\n"+
5255 "precious data, has a problem finding data.\n\n" +
5256 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5257 "In the mean time, I'm not going to let you make changes to this note.\n" +
5258 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5259 "this note on the Evernote servers. Sorry."+
5260 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5262 browserWindow.setReadOnly(true);
5268 //**********************************************************
5269 //**********************************************************
5271 //**********************************************************
5272 //**********************************************************
5273 // We should now do a sync with Evernote
5274 private void syncTimer() {
5275 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5276 syncRunner.syncNeeded = true;
5277 syncRunner.disableUploads = Global.disableUploads;
5279 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5281 private void syncStart() {
5282 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5284 if (!syncRunning && Global.isConnected) {
5285 syncRunner.setConnected(true);
5286 syncRunner.setKeepRunning(Global.keepRunning);
5287 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5289 if (syncThreadsReady > 0) {
5290 thumbnailRunner.interrupt = true;
5291 saveNoteIndexWidth();
5292 saveNoteColumnPositions();
5293 if (syncRunner.addWork("SYNC")) {
5295 syncRunner.syncNeeded = true;
5300 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5302 @SuppressWarnings("unused")
5303 private void syncThreadComplete(Boolean refreshNeeded) {
5304 setMessage(tr("Finalizing Synchronization"));
5306 syncRunning = false;
5307 syncRunner.syncNeeded = false;
5308 synchronizeAnimationTimer.stop();
5309 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5311 if (currentNote == null) {
5312 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5314 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5315 noteIndexUpdated(false);
5316 noteTableView.selectionModel().blockSignals(true);
5317 scrollToGuid(currentNoteGuid);
5318 noteTableView.selectionModel().blockSignals(false);
5319 refreshEvernoteNote(false);
5320 scrollToGuid(currentNoteGuid);
5322 if (!syncRunner.error)
5323 setMessage(tr("Synchronization Complete"));
5325 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5326 logger.log(logger.MEDIUM, "Sync complete.");
5328 public void saveUploadAmount(long t) {
5329 Global.saveUploadAmount(t);
5331 public void saveUserInformation(User user) {
5332 Global.saveUserInformation(user);
5334 public void saveEvernoteUpdateCount(int i) {
5335 Global.saveEvernoteUpdateCount(i);
5337 public void refreshLists() {
5338 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5339 System.out.println("<><><><><><><><><><><><><><><><><><><><>");
5341 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5342 tagIndexUpdated(true);
5343 notebookIndexUpdated();
5344 savedSearchIndexUpdated();
5345 listManager.loadNotesIndex();
5347 noteTableView.selectionModel().blockSignals(true);
5348 noteIndexUpdated(true);
5349 noteTableView.selectionModel().blockSignals(false);
5350 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5354 @SuppressWarnings("unused")
5355 private void authTimer() {
5356 Calendar cal = Calendar.getInstance();
5358 // If we are not connected let's get out of here
5359 if (!Global.isConnected)
5362 // If this is the first time through, then we need to set this
5363 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5364 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5366 // long now = new Date().getTime();
5367 // if (now > Global.authRefreshTime && Global.isConnected) {
5368 syncRunner.authRefreshNeeded = true;
5372 @SuppressWarnings("unused")
5373 private void authRefreshComplete(boolean goodSync) {
5374 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5375 Global.isConnected = syncRunner.isConnected;
5377 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5378 authTimer.start(1000*60*15);
5379 logger.log(logger.LOW, "Authentication token has been renewed");
5380 // setMessage("Authentication token has been renewed.");
5382 authTimer.start(1000*60*5);
5383 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5384 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5386 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5390 @SuppressWarnings("unused")
5391 private synchronized void indexTimer() {
5392 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5395 if (!indexDisabled && indexRunner.idle) {
5396 thumbnailRunner.interrupt = true;
5397 indexRunner.addWork("SCAN");
5399 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5402 @SuppressWarnings("unused")
5403 private void indexStarted() {
5404 setMessage(tr("Indexing notes"));
5406 @SuppressWarnings("unused")
5407 private void indexComplete() {
5408 setMessage(tr("Index complete"));
5410 @SuppressWarnings("unused")
5411 private synchronized void toggleNoteIndexing() {
5412 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5413 indexDisabled = !indexDisabled;
5415 setMessage(tr("Indexing is now enabled."));
5417 setMessage(tr("Indexing is now disabled."));
5418 menuBar.disableIndexing.setChecked(indexDisabled);
5419 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5422 @SuppressWarnings("unused")
5423 private void threadMonitorCheck() {
5428 alive = listManager.threadCheck(Global.tagCounterThreadId);
5431 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5432 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5433 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5434 disableTagThreadCheck = true;
5439 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5441 notebookThreadDeadCount++;
5442 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5443 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5444 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5445 disableNotebookThreadCheck=true;
5448 notebookThreadDeadCount=0;
5450 alive = listManager.threadCheck(Global.trashCounterThreadId);
5453 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5454 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5455 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5456 disableTrashThreadCheck = true;
5461 alive = listManager.threadCheck(Global.saveThreadId);
5463 saveThreadDeadCount++;
5464 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5465 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5466 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5467 disableSaveThreadCheck = true;
5470 saveThreadDeadCount=0;
5472 if (!syncThread.isAlive()) {
5473 syncThreadDeadCount++;
5474 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5475 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5476 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5477 disableSyncThreadCheck = true;
5480 syncThreadDeadCount=0;
5482 if (!indexThread.isAlive()) {
5483 indexThreadDeadCount++;
5484 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5485 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5486 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5487 disableIndexThreadCheck = true;
5490 indexThreadDeadCount=0;
5495 private void thumbnailTimer() {
5496 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5497 thumbnailRunner.addWork("SCAN");
5501 //**************************************************
5502 //* Backup & Restore
5503 //**************************************************
5504 @SuppressWarnings("unused")
5505 private void databaseBackup() {
5506 QFileDialog fd = new QFileDialog(this);
5507 fd.setFileMode(FileMode.AnyFile);
5508 fd.setConfirmOverwrite(true);
5509 fd.setWindowTitle(tr("Backup Database"));
5510 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5511 fd.setAcceptMode(AcceptMode.AcceptSave);
5512 if (saveLastPath == null || saveLastPath.equals(""))
5513 fd.setDirectory(System.getProperty("user.home"));
5515 fd.setDirectory(saveLastPath);
5516 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5522 saveLastPath = fd.selectedFiles().get(0);
5523 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5524 setMessage(tr("Backing up database"));
5526 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5528 ExportData noteWriter = new ExportData(conn, true);
5529 String fileName = fd.selectedFiles().get(0);
5531 if (!fileName.endsWith(".nnex"))
5532 fileName = fileName +".nnex";
5533 noteWriter.exportData(fileName);
5534 setMessage(tr("Database backup completed."));
5539 @SuppressWarnings("unused")
5540 private void databaseRestore() {
5541 if (QMessageBox.question(this, tr("Confirmation"),
5542 tr("This is used to restore a database from backups.\n" +
5543 "It is HIGHLY recommened that this only be used to populate\n" +
5544 "an empty database. Restoring into a database that\n already has data" +
5545 " can cause problems.\n\nAre you sure you want to continue?"),
5546 QMessageBox.StandardButton.Yes,
5547 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5552 QFileDialog fd = new QFileDialog(this);
5553 fd.setFileMode(FileMode.ExistingFile);
5554 fd.setConfirmOverwrite(true);
5555 fd.setWindowTitle(tr("Restore Database"));
5556 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5557 fd.setAcceptMode(AcceptMode.AcceptOpen);
5558 if (saveLastPath == null || saveLastPath.equals(""))
5559 fd.setDirectory(System.getProperty("user.home"));
5561 fd.setDirectory(saveLastPath);
5562 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5568 saveLastPath = fd.selectedFiles().get(0);
5569 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5571 setMessage(tr("Restoring database"));
5572 ImportData noteReader = new ImportData(conn, true);
5573 noteReader.importData(fd.selectedFiles().get(0));
5575 if (noteReader.lastError != 0) {
5576 setMessage(noteReader.getErrorMessage());
5577 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5582 listManager.loadNoteTitleColors();
5584 refreshEvernoteNote(true);
5585 setMessage(tr("Database has been restored."));
5588 @SuppressWarnings("unused")
5589 private void exportNotes() {
5590 QFileDialog fd = new QFileDialog(this);
5591 fd.setFileMode(FileMode.AnyFile);
5592 fd.setConfirmOverwrite(true);
5593 fd.setWindowTitle(tr("Backup Database"));
5594 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5595 fd.setAcceptMode(AcceptMode.AcceptSave);
5596 fd.setDirectory(System.getProperty("user.home"));
5597 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5603 setMessage(tr("Exporting Notes"));
5606 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5607 selectedNoteGUIDs.add(currentNoteGuid);
5609 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5610 String fileName = fd.selectedFiles().get(0);
5612 if (!fileName.endsWith(".nnex"))
5613 fileName = fileName +".nnex";
5614 noteWriter.exportData(fileName);
5615 setMessage(tr("Export completed."));
5621 @SuppressWarnings("unused")
5622 private void importNotes() {
5623 QFileDialog fd = new QFileDialog(this);
5624 fd.setFileMode(FileMode.ExistingFile);
5625 fd.setConfirmOverwrite(true);
5626 fd.setWindowTitle(tr("Import Notes"));
5627 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5628 fd.setAcceptMode(AcceptMode.AcceptOpen);
5629 if (saveLastPath == null || saveLastPath.equals(""))
5630 fd.setDirectory(System.getProperty("user.home"));
5632 fd.setDirectory(saveLastPath);
5633 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5639 setMessage("Importing Notes");
5642 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5643 selectedNoteGUIDs.add(currentNoteGuid);
5645 ImportData noteReader = new ImportData(conn, false);
5646 String fileName = fd.selectedFiles().get(0);
5647 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5649 if (!fileName.endsWith(".nnex"))
5650 fileName = fileName +".nnex";
5651 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5652 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5654 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5656 noteReader.importData(fileName);
5658 if (noteReader.lastError != 0) {
5659 setMessage(noteReader.getErrorMessage());
5660 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5665 listManager.loadNoteTitleColors();
5667 refreshEvernoteNote(false);
5668 setMessage(tr("Notes have been imported."));
5671 setMessage("Import completed.");
5678 //**************************************************
5679 //* Duplicate a note
5680 //**************************************************
5681 @SuppressWarnings("unused")
5682 private void duplicateNote() {
5684 duplicateNote(currentNoteGuid);
5689 //**************************************************
5691 //**************************************************
5692 public void setupFolderImports() {
5693 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5695 if (importKeepWatcher == null)
5696 importKeepWatcher = new QFileSystemWatcher();
5697 if (importDeleteWatcher == null) {
5698 importDeleteWatcher = new QFileSystemWatcher();
5699 for (int i=0; i<records.size(); i++) {
5700 if (!records.get(i).keep)
5701 folderImportDelete(records.get(i).folder);
5707 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5708 for (int i=0; i<records.size(); i++) {
5709 if (records.get(i).keep)
5710 importKeepWatcher.addPath(records.get(i).folder);
5712 importDeleteWatcher.addPath(records.get(i).folder);
5715 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5716 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5718 // Look at the files already there so we don't import them again if a new file is created
5719 if (importedFiles == null) {
5720 importedFiles = new ArrayList<String>();
5721 for (int j=0; j<records.size(); j++) {
5722 QDir dir = new QDir(records.get(j).folder);
5723 List<QFileInfo> list = dir.entryInfoList();
5724 for (int k=0; k<list.size(); k++) {
5725 if (list.get(k).isFile())
5726 importedFiles.add(list.get(k).absoluteFilePath());
5731 public void folderImport() {
5732 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5733 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5735 if (!dialog.okClicked())
5738 // We have some sort of update.
5739 if (importKeepWatcher.directories().size() > 0)
5740 importKeepWatcher.removePaths(importKeepWatcher.directories());
5741 if (importDeleteWatcher.directories().size() > 0)
5742 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5744 conn.getWatchFolderTable().expungeAll();
5745 // Start building from the table
5746 for (int i=0; i<dialog.table.rowCount(); i++) {
5747 QTableWidgetItem item = dialog.table.item(i, 0);
5748 String dir = item.text();
5749 item = dialog.table.item(i, 1);
5750 String notebook = item.text();
5751 item = dialog.table.item(i, 2);
5753 if (item.text().equalsIgnoreCase("Keep"))
5758 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5759 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5761 setupFolderImports();
5764 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5766 String whichOS = System.getProperty("os.name");
5767 if (whichOS.contains("Windows"))
5768 dirName = dirName.replace('/','\\');
5770 FileImporter importer = new FileImporter(logger, conn);
5772 QDir dir = new QDir(dirName);
5773 List<QFileInfo> list = dir.entryInfoList();
5774 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5776 for (int i=0; i<list.size(); i++){
5778 boolean redundant = false;
5779 // Check if we've already imported this one or if it existed before
5780 for (int j=0; j<importedFiles.size(); j++) {
5781 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5786 importer.setFileInfo(list.get(i));
5787 importer.setFileName(list.get(i).absoluteFilePath());
5790 if (list.get(i).isFile() && importer.isValidType()) {
5792 if (!importer.importFile()) {
5793 // If we can't get to the file, it is probably locked. We'll try again later.
5794 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5795 importFilesKeep.add(list.get(i).absoluteFilePath());
5799 Note newNote = importer.getNote();
5800 newNote.setNotebookGuid(notebook);
5801 newNote.setTitle(dir.at(i));
5802 listManager.addNote(newNote);
5803 conn.getNoteTable().addNote(newNote, true);
5804 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5805 noteTableView.insertRow(newNote, true, -1);
5806 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5807 listManager.countNotebookResults(listManager.getNoteIndex());
5808 importedFiles.add(list.get(i).absoluteFilePath());
5816 public void folderImportDelete(String dirName) {
5818 String whichOS = System.getProperty("os.name");
5819 if (whichOS.contains("Windows"))
5820 dirName = dirName.replace('/','\\');
5822 FileImporter importer = new FileImporter(logger, conn);
5823 QDir dir = new QDir(dirName);
5824 List<QFileInfo> list = dir.entryInfoList();
5825 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5827 for (int i=0; i<list.size(); i++){
5828 importer.setFileInfo(list.get(i));
5829 importer.setFileName(list.get(i).absoluteFilePath());
5831 if (list.get(i).isFile() && importer.isValidType()) {
5833 if (!importer.importFile()) {
5834 // If we can't get to the file, it is probably locked. We'll try again later.
5835 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5836 importFilesKeep.add(list.get(i).absoluteFilePath());
5840 Note newNote = importer.getNote();
5841 newNote.setNotebookGuid(notebook);
5842 newNote.setTitle(dir.at(i));
5843 listManager.addNote(newNote);
5844 conn.getNoteTable().addNote(newNote, true);
5845 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5846 noteTableView.insertRow(newNote, true, -1);
5847 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5848 listManager.countNotebookResults(listManager.getNoteIndex());
5849 dir.remove(dir.at(i));
5855 //**************************************************
5857 //**************************************************
5858 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5859 logger.log(logger.HIGH, "Entering exernalFileEdited");
5861 // Strip URL prefix and base dir path
5862 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5863 String name = fileName.replace(dPath, "");
5864 int pos = name.lastIndexOf('.');
5867 guid = guid.substring(0,pos);
5869 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5871 guid = name.substring(0, pos);
5874 QFile file = new QFile(fileName);
5875 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5876 // If we can't get to the file, it is probably locked. We'll try again later.
5877 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5878 externalFiles.add(fileName);
5881 QByteArray binData = file.readAll();
5883 if (binData.size() == 0) {
5884 // If we can't get to the file, it is probably locked. We'll try again later.
5885 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5886 externalFiles.add(fileName);
5890 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5892 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5893 if (r == null || r.getData() == null || r.getData().getBody() == null)
5895 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5896 MessageDigest md = MessageDigest.getInstance("MD5");
5897 md.update(binData.toByteArray());
5898 byte[] hash = md.digest();
5899 String newHash = Global.byteArrayToHexString(hash);
5900 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5901 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5903 if (externalWindows.containsKey(r.getNoteGuid())) {
5904 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5905 r.getGuid(), oldHash, newHash);
5907 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5908 Data data = r.getData();
5909 data.setBody(binData.toByteArray());
5910 data.setBodyHash(hash);
5911 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5913 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5915 if (r.getNoteGuid().equals(currentNoteGuid)) {
5916 QWebSettings.setMaximumPagesInCache(0);
5917 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5918 refreshEvernoteNote(true);
5919 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5922 if (externalWindows.containsKey(r.getNoteGuid())) {
5923 QWebSettings.setMaximumPagesInCache(0);
5924 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5925 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5929 logger.log(logger.HIGH, "Exiting externalFielEdited");
5931 // This is a timer event that tries to save any external files that were edited. This
5932 // is only needed if we couldn't save a file earlier.
5933 public void externalFileEditedSaver() {
5934 for (int i=externalFiles.size()-1; i>=0; i--) {
5936 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5937 externalFileEdited(externalFiles.get(i));
5938 externalFiles.remove(i);
5939 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5941 for (int i=0; i<importFilesKeep.size(); i++) {
5943 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5944 folderImportKeep(importFilesKeep.get(i));
5945 importFilesKeep.remove(i);
5946 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5948 for (int i=0; i<importFilesDelete.size(); i++) {
5949 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5950 folderImportDelete(importFilesDelete.get(i));
5951 importFilesDelete.remove(i);
5958 // If an attachment on the current note was edited, we need to update the current notes's hash
5959 // Update a note content's hash. This happens if a resource is edited outside of NN
5960 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5961 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5963 for (;position>-1;) {
5964 endPos = browser.getContent().indexOf(">", position+1);
5965 String oldSegment = browser.getContent().substring(position,endPos);
5966 int hashPos = oldSegment.indexOf("hash=\"");
5967 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5968 String hash = oldSegment.substring(hashPos+6, hashEnd);
5969 if (hash.equalsIgnoreCase(oldHash)) {
5970 String newSegment = oldSegment.replace(oldHash, newHash);
5971 String content = browser.getContent().substring(0,position) +
5973 browser.getContent().substring(endPos);
5974 browser.getBrowser().setContent(new QByteArray(content));;
5977 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5982 //*************************************************
5983 //* Minimize to tray
5984 //*************************************************
5986 public void changeEvent(QEvent e) {
5987 if (e.type() == QEvent.Type.WindowStateChange) {
5988 if (isMinimized() && Global.showTrayIcon()) {
5990 QTimer.singleShot(10, this, "hide()");
5994 windowMaximized = true;
5996 windowMaximized = false;
6000 //*************************************************
6001 //* Check database userid & passwords
6002 //*************************************************
6003 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6004 Connection connection;
6007 Class.forName("org.h2.Driver");
6008 } catch (ClassNotFoundException e1) {
6009 e1.printStackTrace();
6014 String passwordString = null;
6015 if (cypherPassword==null || cypherPassword.trim().equals(""))
6016 passwordString = userPassword;
6018 passwordString = cypherPassword+" "+userPassword;
6019 connection = DriverManager.getConnection(url,userid,passwordString);
6020 } catch (SQLException e) {
6025 } catch (SQLException e) {
6026 e.printStackTrace();
6032 //*************************************************
6033 // Block the program. This is used for things
6034 // like async web calls.
6035 //*************************************************
6036 @SuppressWarnings("unused")
6037 private void blockApplication(Long time) {
6038 Calendar currentTime = new GregorianCalendar();
6040 blockTime = new Long(currentTime.getTimeInMillis())+time;
6042 for (;currentTime.getTimeInMillis()>blockTime;) {
6045 } catch (InterruptedException e) {
6046 e.printStackTrace();
6052 @SuppressWarnings("unused")
6053 private void unblockApplication() {