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.TagMerge;
158 import cx.fbn.nevernote.dialog.ThumbnailViewer;
159 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
160 import cx.fbn.nevernote.dialog.WatchFolder;
161 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
162 import cx.fbn.nevernote.filters.FilterEditorTags;
163 import cx.fbn.nevernote.gui.AttributeTreeWidget;
164 import cx.fbn.nevernote.gui.BrowserWindow;
165 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
166 import cx.fbn.nevernote.gui.ExternalBrowse;
167 import cx.fbn.nevernote.gui.MainMenuBar;
168 import cx.fbn.nevernote.gui.NotebookTreeWidget;
169 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
170 import cx.fbn.nevernote.gui.SearchPanel;
171 import cx.fbn.nevernote.gui.TableView;
172 import cx.fbn.nevernote.gui.TagTreeWidget;
173 import cx.fbn.nevernote.gui.Thumbnailer;
174 import cx.fbn.nevernote.gui.TrashTreeWidget;
175 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
176 import cx.fbn.nevernote.sql.DatabaseConnection;
177 import cx.fbn.nevernote.sql.WatchFolderRecord;
178 import cx.fbn.nevernote.threads.IndexRunner;
179 import cx.fbn.nevernote.threads.SyncRunner;
180 import cx.fbn.nevernote.threads.ThumbnailRunner;
181 import cx.fbn.nevernote.utilities.AESEncrypter;
182 import cx.fbn.nevernote.utilities.ApplicationLogger;
183 import cx.fbn.nevernote.utilities.FileImporter;
184 import cx.fbn.nevernote.utilities.FileUtils;
185 import cx.fbn.nevernote.utilities.ListManager;
186 import cx.fbn.nevernote.utilities.SyncTimes;
187 import cx.fbn.nevernote.xml.ExportData;
188 import cx.fbn.nevernote.xml.ImportData;
189 import cx.fbn.nevernote.xml.NoteFormatter;
192 public class NeverNote extends QMainWindow{
194 QStatusBar statusBar; // Application status bar
196 DatabaseConnection conn;
198 MainMenuBar menuBar; // Main menu bar
199 FindDialog find; // Text search in note dialog
200 List<String> emitLog; // Messages displayed in the status bar;
201 QSystemTrayIcon trayIcon; // little tray icon
202 QMenu trayMenu; // System tray menu
203 QAction trayExitAction; // Exit the application
204 QAction trayShowAction; // toggle the show/hide action
205 QAction trayAddNoteAction; // Add a note from the system tray
206 QNetworkAccessManager versionChecker; // Used when checking for new versions
208 NotebookTreeWidget notebookTree; // List of notebooks
209 AttributeTreeWidget attributeTree; // List of note attributes
210 TagTreeWidget tagTree; // list of user created tags
211 SavedSearchTreeWidget savedSearchTree; // list of saved searches
212 TrashTreeWidget trashTree; // Trashcan
213 TableView noteTableView; // List of notes (the widget).
215 public BrowserWindow browserWindow; // Window containing browser & labels
216 public QToolBar toolBar; // The tool bar under the menu
217 QComboBox searchField; // search filter bar on the toolbar;
218 QShortcut searchShortcut; // Shortcut to search bar
219 boolean searchPerformed = false; // Search was done?
220 QuotaProgressBar quotaBar; // The current quota usage
222 ApplicationLogger logger;
223 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
224 List<String> selectedTagGUIDs; // List of selected tag GUIDs
225 List<String> selectedNoteGUIDs; // List of selected notes
226 String selectedSavedSearchGUID; // Currently selected saved searches
227 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
229 NoteFilter filter; // Note filter
230 String currentNoteGuid; // GUID of the current note
231 Note currentNote; // The currently viewed note
232 boolean noteDirty; // Has the note been changed?
233 boolean inkNote; // if this is an ink note, it is read only
234 boolean readOnly; // Is this note read-only?
237 ListManager listManager; // DB runnable task
239 List<QTemporaryFile> tempFiles; // Array of temporary files;
241 QTimer indexTimer; // timer to start the index thread
242 IndexRunner indexRunner; // thread to index notes
245 QTimer syncTimer; // Sync on an interval
246 QTimer syncDelayTimer; // Sync delay to free up database
247 SyncRunner syncRunner; // thread to do a sync.
248 QThread syncThread; // Thread which talks to evernote
249 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
250 QThread thumbnailThread; // Thread that generates pretty pictures
251 QTimer saveTimer; // Timer to save note contents
253 QTimer authTimer; // Refresh authentication
254 QTimer externalFileSaveTimer; // Save files altered externally
255 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
256 List<String> externalFiles; // External files to save later
257 List<String> importFilesKeep; // Auto-import files to save later
258 List<String> importFilesDelete; // Auto-import files to save later
260 int indexTime; // how often to try and index
261 boolean indexRunning; // Is indexing running?
262 boolean indexDisabled; // Is indexing disabled?
264 int syncThreadsReady; // number of sync threads that are free
265 int syncTime; // Sync interval
266 boolean syncRunning; // Is sync running?
267 boolean automaticSync; // do sync automatically?
268 QTreeWidgetItem attributeTreeSelected;
270 QAction prevButton; // Go to the previous item viewed
271 QAction nextButton; // Go to the next item in the history
272 QAction downButton; // Go to the next item in the list
273 QAction upButton; // Go to the prev. item in the list;
274 QAction synchronizeButton; // Synchronize with Evernote
275 QAction allNotesButton; // Reset & view all notes
276 QTimer synchronizeAnimationTimer; // Timer to change animation button
277 int synchronizeIconAngle; // Used to rotate sync icon
278 QAction printButton; // Print Button
279 QAction tagButton; // Tag edit button
280 QAction attributeButton; // Attribute information button
281 QAction emailButton; // Email button
282 QAction deleteButton; // Delete button
283 QAction newButton; // new Note Button;
284 QSpinBox zoomSpinner; // Zoom zoom
285 QAction searchClearButton; // Clear the search field
287 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
289 QSplitter mainLeftRightSplitter; // main splitter for left/right side
290 QSplitter leftSplitter1; // first left hand splitter
291 QSplitter browserIndexSplitter; // splitter between note index & note text
293 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
294 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
295 List<String> importedFiles; // History of imported files (so we don't import twice)
297 OnlineNoteHistory historyWindow; // online history window
298 List<NoteVersionId> versions; // history versions
300 QTimer threadMonitorTimer; // Timer to watch threads.
301 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
302 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
303 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
304 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
305 int tagDeadCount=0; // number of consecutive dead times for the tag thread
306 int trashDeadCount=0; // number of consecutive dead times for the trash thread
307 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
308 boolean disableTagThreadCheck=false;
309 boolean disableNotebookThreadCheck=false;
310 boolean disableTrashThreadCheck=false;
311 boolean disableSaveThreadCheck=false;
312 boolean disableSyncThreadCheck=false;
313 boolean disableIndexThreadCheck=false;
315 HashMap<String, String> noteCache; // Cash of note content
316 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
317 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
318 List<String> historyGuids; // GUIDs of previously viewed items
319 int historyPosition; // Position within the viewed items
320 boolean fromHistory; // Is this from the history queue?
321 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
322 List<Thumbnailer> thumbGenerators; // generate preview image
323 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
324 boolean encryptOnShutdown; // should I encrypt when I close?
325 boolean decryptOnShutdown; // should I decrypt on shutdown;
326 String encryptCipher; // What cipher should I use?
327 Signal0 minimizeToTray;
328 boolean windowMaximized = false; // Keep track of the window state for restores
329 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
330 List<QPixmap> syncIcons; // Array of icons used in sync animation
331 private boolean closeAction = false; // Used to say when to close or when to minimize
332 private static Logger log = Logger.getLogger(NeverNote.class);
333 private String saveLastPath; // last path we used
334 private final QTimer messageTimer; // Timer to clear the status message.
335 private long blockTime; // When the app. is blocked, this is the time to unblock it.
338 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
341 //***************************************************************
342 //***************************************************************
343 //** Constructor & main entry point
344 //***************************************************************
345 //***************************************************************
346 // Application Constructor
347 @SuppressWarnings("static-access")
348 public NeverNote(DatabaseConnection dbConn) {
350 if (conn.getConnection() == null) {
351 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
352 "is accessing the database or NeverNote is already running.\n\n" +
353 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
355 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
358 setObjectName("mainWindow");
359 // thread().setPriority(Thread.MAX_PRIORITY);
361 logger = new ApplicationLogger("nevernote.log");
362 logger.log(logger.HIGH, "Starting Application");
364 decryptOnShutdown = false;
365 encryptOnShutdown = false;
366 conn.checkDatabaseVersion();
370 // Start building the invalid XML tables
371 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
372 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
374 for (int i=0; i<elements.size(); i++) {
375 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
378 logger.log(logger.EXTREME, "Starting GUI build");
380 QTranslator nevernoteTranslator = new QTranslator();
381 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
382 QApplication.instance().installTranslator(nevernoteTranslator);
384 Global.originalPalette = QApplication.palette();
385 QApplication.setStyle(Global.getStyle());
386 if (Global.useStandardPalette())
387 QApplication.setPalette(QApplication.style().standardPalette());
388 setWindowTitle("NeverNote");
390 mainLeftRightSplitter = new QSplitter();
391 setCentralWidget(mainLeftRightSplitter);
392 leftSplitter1 = new QSplitter();
393 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
395 browserIndexSplitter = new QSplitter();
396 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
398 //* Setup threads & thread timers
399 int indexRunnerCount = Global.getIndexThreads();
400 indexRunnerCount = 1;
401 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
403 logger.log(logger.EXTREME, "Building list manager");
404 listManager = new ListManager(conn, logger);
406 logger.log(logger.EXTREME, "Building index runners & timers");
407 indexRunner = new IndexRunner("indexRunner.log",
408 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
409 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
410 indexThread = new QThread(indexRunner, "Index Thread");
411 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
414 synchronizeAnimationTimer = new QTimer();
415 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
417 indexTimer = new QTimer();
418 indexTime = 1000*Global.getIndexThreadSleepInterval();
419 indexTimer.start(indexTime); // Start indexing timer
420 indexTimer.timeout.connect(this, "indexTimer()");
421 indexDisabled = false;
422 indexRunning = false;
424 logger.log(logger.EXTREME, "Setting sync thread & timers");
426 syncRunner = new SyncRunner("syncRunner.log",
427 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
428 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
429 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
430 syncTimer = new QTimer();
431 syncTimer.timeout.connect(this, "syncTimer()");
432 syncRunner.status.message.connect(this, "setMessage(String)");
433 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
434 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
437 automaticSync = true;
438 syncTimer.start(syncTime*60*1000);
440 automaticSync = false;
443 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
444 syncThread = new QThread(syncRunner, "Synchronization Thread");
448 logger.log(logger.EXTREME, "Starting thumnail thread");
449 pdfReadyQueue = new ArrayList<String>();
450 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
451 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
452 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
453 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
454 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
455 thumbnailThread.start();
456 thumbGenerators = new ArrayList<Thumbnailer>();
457 thumbnailTimer = new QTimer();
458 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
460 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
461 thumbnailTimer.start();
463 logger.log(logger.EXTREME, "Starting authentication timer");
464 authTimer = new QTimer();
465 authTimer.timeout.connect(this, "authTimer()");
466 authTimer.start(1000*60*15);
467 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
469 logger.log(logger.EXTREME, "Setting save note timer");
470 saveTimer = new QTimer();
471 saveTimer.timeout.connect(this, "saveNote()");
472 if (Global.getAutoSaveInterval() > 0) {
473 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
476 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
478 logger.log(logger.EXTREME, "Starting external file monitor timer");
479 externalFileSaveTimer = new QTimer();
480 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
481 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
482 externalFiles = new ArrayList<String>();
483 importFilesDelete = new ArrayList<String>();
484 importFilesKeep = new ArrayList<String>();
485 externalFileSaveTimer.start();
487 notebookTree = new NotebookTreeWidget(conn);
488 attributeTree = new AttributeTreeWidget();
489 tagTree = new TagTreeWidget(conn);
490 savedSearchTree = new SavedSearchTreeWidget();
491 trashTree = new TrashTreeWidget();
492 noteTableView = new TableView(logger, listManager);
495 searchField = new QComboBox();
496 searchField.setObjectName("searchField");
497 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
498 searchField.setEditable(true);
499 searchField.activatedIndex.connect(this, "searchFieldChanged()");
500 searchField.setDuplicatesEnabled(false);
501 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
502 searchShortcut = new QShortcut(this);
503 setupShortcut(searchShortcut, "Focus_Search");
504 searchShortcut.activated.connect(this, "focusSearch()");
506 quotaBar = new QuotaProgressBar();
508 zoomSpinner = new QSpinBox();
509 zoomSpinner.setMinimum(10);
510 zoomSpinner.setMaximum(1000);
511 zoomSpinner.setAccelerated(true);
512 zoomSpinner.setSingleStep(10);
513 zoomSpinner.setValue(100);
514 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
516 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
519 QGridLayout leftGrid = new QGridLayout();
520 leftSplitter1.setContentsMargins(5, 0, 0, 7);
521 leftSplitter1.setLayout(leftGrid);
522 leftGrid.addWidget(searchLayout,1,1);
523 leftGrid.addWidget(tagTree,2,1);
524 leftGrid.addWidget(attributeTree,3,1);
525 leftGrid.addWidget(savedSearchTree,4,1);
526 leftGrid.addWidget(trashTree,5, 1);
528 // Setup the browser window
529 noteCache = new HashMap<String,String>();
530 readOnlyCache = new HashMap<String, Boolean>();
531 inkNoteCache = new HashMap<String, Boolean>();
532 browserWindow = new BrowserWindow(conn);
534 mainLeftRightSplitter.addWidget(leftSplitter1);
535 mainLeftRightSplitter.addWidget(browserIndexSplitter);
537 if (Global.getListView() == Global.View_List_Wide) {
538 browserIndexSplitter.addWidget(noteTableView);
539 browserIndexSplitter.addWidget(browserWindow);
541 mainLeftRightSplitter.addWidget(noteTableView);
542 mainLeftRightSplitter.addWidget(browserWindow);
545 // Setup the thumbnail viewer
546 thumbnailViewer = new ThumbnailViewer();
547 thumbnailViewer.upArrow.connect(this, "upAction()");
548 thumbnailViewer.downArrow.connect(this, "downAction()");
549 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
550 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
552 //Setup external browser manager
553 externalWindows = new HashMap<String, ExternalBrowse>();
555 listManager.loadNotesIndex();
556 initializeNotebookTree();
558 initializeSavedSearchTree();
559 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
560 attributeTreeSelected = null;
561 initializeNoteTable();
563 selectedNoteGUIDs = new ArrayList<String>();
564 statusBar = new QStatusBar();
565 setStatusBar(statusBar);
566 menuBar = new MainMenuBar(this);
567 emitLog = new ArrayList<String>();
569 tagTree.setDeleteAction(menuBar.tagDeleteAction);
570 tagTree.setMergeAction(menuBar.tagMergeAction);
571 tagTree.setEditAction(menuBar.tagEditAction);
572 tagTree.setAddAction(menuBar.tagAddAction);
573 tagTree.setIconAction(menuBar.tagIconAction);
574 tagTree.setVisible(Global.isWindowVisible("tagTree"));
575 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
576 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
577 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
578 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
580 if (!Global.isWindowVisible("zoom")) {
581 searchLayout.hideZoom();
582 menuBar.hideZoom.setChecked(false);
585 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
586 notebookTree.setEditAction(menuBar.notebookEditAction);
587 notebookTree.setAddAction(menuBar.notebookAddAction);
588 notebookTree.setIconAction(menuBar.notebookIconAction);
589 notebookTree.setStackAction(menuBar.notebookStackAction);
590 notebookTree.setPublishAction(menuBar.notebookPublishAction);
591 notebookTree.setShareAction(menuBar.notebookShareAction);
592 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
593 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
594 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
595 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
596 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
598 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
599 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
600 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
601 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
602 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
603 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
604 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
606 noteTableView.setAddAction(menuBar.noteAdd);
607 noteTableView.setDeleteAction(menuBar.noteDelete);
608 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
609 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
610 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
611 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
612 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
613 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
614 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
616 quotaBar.setMouseClickAction(menuBar.accountAction);
619 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
620 trashTree.setEmptyAction(menuBar.emptyTrashAction);
621 trashTree.setVisible(Global.isWindowVisible("trashTree"));
622 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
623 trashTree.updateCounts(listManager.getTrashCount());
624 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
625 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
627 noteTableView.setVisible(Global.isWindowVisible("noteList"));
628 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
630 if (!Global.isWindowVisible("editorButtonBar"))
631 toggleEditorButtonBar();
632 if (!Global.isWindowVisible("leftPanel"))
633 menuBar.hideLeftSide.setChecked(true);
634 if (Global.isWindowVisible("noteInformation"))
635 toggleNoteInformation();
636 quotaBar.setVisible(Global.isWindowVisible("quota"));
637 if (!quotaBar.isVisible())
638 menuBar.hideQuota.setChecked(false);
639 searchField.setVisible(Global.isWindowVisible("searchField"));
640 if (!searchField.isVisible())
641 menuBar.hideSearch.setChecked(false);
643 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
648 find = new FindDialog();
649 find.getOkButton().clicked.connect(this, "doFindText()");
651 // Setup the tray icon menu bar
652 trayShowAction = new QAction("Show/Hide", this);
653 trayExitAction = new QAction("Exit", this);
654 trayAddNoteAction = new QAction("Add Note", this);
656 trayExitAction.triggered.connect(this, "closeNeverNote()");
657 trayAddNoteAction.triggered.connect(this, "addNote()");
658 trayShowAction.triggered.connect(this, "trayToggleVisible()");
660 trayMenu = new QMenu(this);
661 trayMenu.addAction(trayAddNoteAction);
662 trayMenu.addAction(trayShowAction);
663 trayMenu.addAction(trayExitAction);
666 trayIcon = new QSystemTrayIcon(this);
667 trayIcon.setToolTip("NeverNote");
668 trayIcon.setContextMenu(trayMenu);
669 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
672 currentNoteGuid = Global.getLastViewedNoteGuid();
673 historyGuids = new ArrayList<String>();
677 if (!currentNoteGuid.trim().equals("")) {
678 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
681 noteIndexUpdated(true);
683 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
684 if (menuBar.showEditorBar.isChecked())
685 showEditorButtons(browserWindow);
686 tagIndexUpdated(true);
687 savedSearchIndexUpdated();
688 notebookIndexUpdated();
690 setupSyncSignalListeners();
691 setupBrowserSignalListeners();
692 setupIndexListeners();
695 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
696 tagTree.showAllTags(true);
698 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
699 setWindowIcon(appIcon);
700 trayIcon.setIcon(appIcon);
701 if (Global.showTrayIcon())
706 scrollToGuid(currentNoteGuid);
707 if (Global.automaticLogin()) {
709 if (Global.isConnected)
712 setupFolderImports();
715 restoreWindowState(true);
717 if (Global.mimicEvernoteInterface) {
718 notebookTree.selectGuid("");
721 threadMonitorTimer = new QTimer();
722 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
723 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
725 historyGuids.add(currentNoteGuid);
728 menuBar.blockSignals(true);
729 menuBar.narrowListView.blockSignals(true);
730 menuBar.wideListView.blockSignals(true);
731 if (Global.getListView() == Global.View_List_Narrow) {
732 menuBar.narrowListView.setChecked(true);
735 menuBar.wideListView.setChecked(true);
737 menuBar.blockSignals(false);
738 menuBar.narrowListView.blockSignals(false);
739 menuBar.wideListView.blockSignals(false);
741 if (Global.getListView() == Global.View_List_Wide) {
742 browserIndexSplitter.addWidget(noteTableView);
743 browserIndexSplitter.addWidget(browserWindow);
745 mainLeftRightSplitter.addWidget(noteTableView);
746 mainLeftRightSplitter.addWidget(browserWindow);
749 messageTimer = new QTimer();
750 messageTimer.timeout.connect(this, "clearMessage()");
751 messageTimer.setInterval(1000*15);
754 int sortCol = Global.getSortColumn();
755 int sortOrder = Global.getSortOrder();
756 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
757 if (Global.checkVersionUpgrade())
762 public static void main(String[] args) {
763 log.setLevel(Level.FATAL);
764 QApplication.initialize(args);
765 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
766 QSplashScreen splash = new QSplashScreen(pixmap);
769 DatabaseConnection dbConn;
772 initializeGlobalSettings(args);
774 showSplash = Global.isWindowVisible("SplashScreen");
778 dbConn = setupDatabaseConnection();
780 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
781 Global.getFileManager().purgeResDirectory(true);
783 } catch (InitializationException e) {
786 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
790 NeverNote application = new NeverNote(dbConn);
792 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
793 if (Global.startMinimized())
794 application.showMinimized();
796 if (Global.wasWindowMaximized())
797 application.showMaximized();
803 splash.finish(application);
805 System.out.println("Goodbye.");
810 * Open the internal database, or create if not present
812 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
814 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
815 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
817 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
818 boolean dbExists = f.exists();
820 Global.setDatabaseUrl("");
822 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
823 boolean goodCheck = false;
825 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
827 if (!dialog.okPressed())
829 Global.cipherPassword = dialog.getPassword();
830 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
831 Global.getDatabaseUserPassword(), Global.cipherPassword);
834 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
835 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
836 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
840 // Encrypt the database upon shutdown
841 private void encryptOnShutdown() {
842 String dbPath= Global.getFileManager().getDbDirPath("");
843 String dbName = "NeverNote";
845 Statement st = conn.getConnection().createStatement();
846 st.execute("shutdown");
847 if (QMessageBox.question(this, tr("Are you sure"),
848 tr("Are you sure you wish to encrypt the database?"),
849 QMessageBox.StandardButton.Yes,
850 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
851 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
852 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
853 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
855 } catch (SQLException e) {
860 // Decrypt the database upon shutdown
861 private void decryptOnShutdown() {
862 String dbPath= Global.getFileManager().getDbDirPath("");
863 String dbName = "NeverNote";
865 Statement st = conn.getConnection().createStatement();
866 st.execute("shutdown");
867 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
868 encryptCipher = "AES";
870 encryptCipher = "XTEA";
871 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
872 "Are you sure you wish to decrypt the database?"),
873 QMessageBox.StandardButton.Yes,
874 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
876 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
877 Global.setDatabaseUrl("");
878 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
880 } catch (SQLException e) {
885 * Encrypt/Decrypt the local database
887 public void doDatabaseEncrypt() {
888 // The database is not currently encrypted
889 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
890 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
891 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
892 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
893 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
894 "Do you wish to proceed?"),
895 QMessageBox.StandardButton.Yes,
896 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
899 DBEncryptDialog dialog = new DBEncryptDialog();
901 if (dialog.okPressed()) {
902 Global.cipherPassword = dialog.getPassword();
903 encryptOnShutdown = true;
904 encryptCipher = dialog.getEncryptionMethod();
907 DBEncryptDialog dialog = new DBEncryptDialog();
908 dialog.setWindowTitle("Database Decryption");
909 dialog.hideEncryption();
911 if (dialog.okPressed()) {
912 if (!dialog.getPassword().equals(Global.cipherPassword)) {
913 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
916 decryptOnShutdown = true;
923 private static void initializeGlobalSettings(String[] args) throws InitializationException {
924 StartupConfig startupConfig = new StartupConfig();
926 for (String arg : args) {
927 String lower = arg.toLowerCase();
928 if (lower.startsWith("--name="))
929 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
930 if (lower.startsWith("--home="))
931 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
932 if (lower.startsWith("--disable-viewing"))
933 startupConfig.setDisableViewing(true);
935 Global.setup(startupConfig);
940 public void closeEvent(QCloseEvent event) {
941 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
946 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
949 if (currentNote!= null & browserWindow!=null) {
950 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
951 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
954 setMessage(tr("Beginning shutdown."));
956 // Close down external windows
957 Collection<ExternalBrowse> windows = externalWindows.values();
958 Iterator<ExternalBrowse> iterator = windows.iterator();
959 while (iterator.hasNext()) {
960 ExternalBrowse browser = iterator.next();
961 browser.windowClosing.disconnect();
966 externalFileEditedSaver();
967 if (Global.isConnected && Global.synchronizeOnClose()) {
968 setMessage(tr("Performing synchronization before closing."));
969 syncRunner.syncNeeded = true;
970 syncRunner.addWork("SYNC");
972 syncRunner.keepRunning = false;
974 syncRunner.addWork("STOP");
975 setMessage("Closing Program.");
976 threadMonitorTimer.stop();
978 thumbnailRunner.addWork("STOP");
979 indexRunner.addWork("STOP");
984 if (tempFiles != null)
987 browserWindow.noteSignal.tagsChanged.disconnect();
988 browserWindow.noteSignal.titleChanged.disconnect();
989 browserWindow.noteSignal.noteChanged.disconnect();
990 browserWindow.noteSignal.notebookChanged.disconnect();
991 browserWindow.noteSignal.createdDateChanged.disconnect();
992 browserWindow.noteSignal.alteredDateChanged.disconnect();
993 syncRunner.searchSignal.listChanged.disconnect();
994 syncRunner.tagSignal.listChanged.disconnect();
995 syncRunner.notebookSignal.listChanged.disconnect();
996 syncRunner.noteIndexSignal.listChanged.disconnect();
999 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1000 saveNoteColumnPositions();
1001 saveNoteIndexWidth();
1003 int width = notebookTree.columnWidth(0);
1004 Global.setColumnWidth("notebookTreeName", width);
1005 width = tagTree.columnWidth(0);
1006 Global.setColumnWidth("tagTreeName", width);
1008 Global.saveWindowMaximized(isMaximized());
1009 Global.saveCurrentNoteGuid(currentNoteGuid);
1011 int sortCol = noteTableView.proxyModel.sortColumn();
1012 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1013 Global.setSortColumn(sortCol);
1014 Global.setSortOrder(sortOrder);
1018 Global.keepRunning = false;
1020 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1021 if (indexRunner.thread().isAlive())
1022 indexRunner.thread().join(50);
1023 if (!indexRunner.thread().isAlive())
1024 logger.log(logger.MEDIUM, "Index thread has stopped");
1026 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1027 indexRunner.thread().interrupt();
1029 } catch (InterruptedException e1) {
1030 e1.printStackTrace();
1033 if (!syncRunner.thread().isAlive()) {
1034 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1035 if (syncRunner.thread().isAlive()) {
1036 System.out.println(tr("Synchronizing. Please be patient."));
1037 for(;syncRunner.thread().isAlive();) {
1040 } catch (InterruptedException e) {
1041 e.printStackTrace();
1045 logger.log(logger.MEDIUM, "Sync thread has stopped");
1048 if (encryptOnShutdown) {
1049 encryptOnShutdown();
1051 if (decryptOnShutdown) {
1052 decryptOnShutdown();
1055 Global.getFileManager().purgeResDirectory(false);
1056 } catch (InitializationException e) {
1057 System.out.println(tr("Empty res directory purge failed"));
1058 e.printStackTrace();
1060 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1063 @SuppressWarnings("unused")
1064 private void closeNeverNote() {
1068 public void setMessage(String s) {
1069 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1072 logger.log(logger.HIGH, "Message: " +s);
1073 statusBar.showMessage(s);
1077 messageTimer.stop();
1078 messageTimer.setSingleShot(true);
1079 messageTimer.start();
1082 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1085 private void clearMessage() {
1086 statusBar.clearMessage();
1090 private void waitCursor(boolean wait) {
1092 if (QApplication.overrideCursor() == null)
1093 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1096 while (QApplication.overrideCursor() != null)
1097 QApplication.restoreOverrideCursor();
1099 listManager.refreshCounters();
1102 private void setupIndexListeners() {
1103 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1104 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1105 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1106 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1108 private void setupSyncSignalListeners() {
1109 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1110 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1111 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1112 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1113 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1115 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1116 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1117 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1119 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1120 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1121 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1122 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1123 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1125 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1128 private void setupBrowserSignalListeners() {
1129 setupBrowserWindowListeners(browserWindow, true);
1132 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1133 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1134 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1135 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1136 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1137 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1138 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1139 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1140 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1141 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1142 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1143 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1144 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1145 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1146 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1147 if (master) browser.focusLost.connect(this, "saveNote()");
1148 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1151 //**************************************************
1153 //**************************************************
1154 private void setupShortcut(QShortcut action, String text) {
1155 if (!Global.shortcutKeys.containsAction(text))
1157 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1160 //***************************************************************
1161 //***************************************************************
1162 //* Settings and look & feel
1163 //***************************************************************
1164 //***************************************************************
1165 @SuppressWarnings("unused")
1166 private void settings() {
1167 logger.log(logger.HIGH, "Entering NeverNote.settings");
1168 saveNoteColumnPositions();
1169 saveNoteIndexWidth();
1171 ConfigDialog settings = new ConfigDialog(this);
1172 String dateFormat = Global.getDateFormat();
1173 String timeFormat = Global.getTimeFormat();
1175 indexTime = 1000*Global.getIndexThreadSleepInterval();
1176 indexTimer.start(indexTime); // reset indexing timer
1179 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1180 if (Global.showTrayIcon())
1185 if (menuBar.showEditorBar.isChecked())
1186 showEditorButtons(browserWindow);
1188 // Reset the save timer
1189 if (Global.getAutoSaveInterval() > 0)
1190 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1194 // This is a hack to force a reload of the index in case the date or time changed.
1195 // if (!dateFormat.equals(Global.getDateFormat()) ||
1196 // !timeFormat.equals(Global.getTimeFormat())) {
1198 readOnlyCache.clear();
1199 inkNoteCache.clear();
1200 noteIndexUpdated(true);
1203 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1205 // Restore things to the way they were
1206 private void restoreWindowState(boolean mainWindow) {
1207 // We need to name things or this doesn't work.
1208 setObjectName("NeverNote");
1209 restoreState(Global.restoreState(objectName()));
1210 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1211 browserIndexSplitter.setObjectName("browserIndexSplitter");
1212 leftSplitter1.setObjectName("leftSplitter1");
1214 // Restore the actual positions.
1216 restoreGeometry(Global.restoreGeometry(objectName()));
1217 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1218 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1219 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1222 // Save window positions for the next start
1223 private void saveWindowState() {
1224 Global.saveGeometry(objectName(), saveGeometry());
1225 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1226 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1227 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1228 Global.saveState(objectName(), saveState());
1230 // Load the style sheet
1231 private void loadStyleSheet() {
1232 String styleSheetName = "default.qss";
1233 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1234 styleSheetName = "default-cleanlooks.qss";
1235 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1236 QFile file = new QFile(fileName);
1238 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1239 if (!file.exists()) {
1240 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1241 file = new QFile(fileName);
1243 file.open(OpenModeFlag.ReadOnly);
1244 String styleSheet = file.readAll().toString();
1246 setStyleSheet(styleSheet);
1248 // Save column positions for the next time
1249 private void saveNoteColumnPositions() {
1250 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1251 Global.setColumnPosition("noteTableCreationPosition", position);
1252 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1253 Global.setColumnPosition("noteTableTagPosition", position);
1254 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1255 Global.setColumnPosition("noteTableNotebookPosition", position);
1256 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1257 Global.setColumnPosition("noteTableChangedPosition", position);
1258 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1259 Global.setColumnPosition("noteTableAuthorPosition", position);
1260 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1261 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1262 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1263 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1264 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1265 Global.setColumnPosition("noteTableTitlePosition", position);
1266 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1267 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1268 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1269 Global.setColumnPosition("noteTableGuidPosition", position);
1270 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1271 Global.setColumnPosition("noteTableThumbnailPosition", position);
1274 // Save column widths for the next time
1275 private void saveNoteIndexWidth() {
1277 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1278 Global.setColumnWidth("noteTableCreationPosition", width);
1279 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1280 Global.setColumnWidth("noteTableChangedPosition", width);
1281 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1282 Global.setColumnWidth("noteTableGuidPosition", width);
1283 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1284 Global.setColumnWidth("noteTableNotebookPosition", width);
1285 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1286 Global.setColumnWidth("noteTableTagPosition", width);
1287 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1288 Global.setColumnWidth("noteTableTitlePosition", width);
1289 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1290 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1291 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1292 Global.setColumnWidth("noteTableAuthorPosition", width);
1293 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1294 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1295 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1296 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1297 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1298 Global.setColumnWidth("noteTableThumbnailPosition", width);
1299 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1300 Global.setColumnWidth("noteTableGuidPosition", width);
1303 @SuppressWarnings("unused")
1304 private void toggleSearchWindow() {
1305 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1306 searchLayout.toggleSearchField();
1307 menuBar.hideSearch.setChecked(searchField.isVisible());
1308 Global.saveWindowVisible("searchField", searchField.isVisible());
1309 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1311 @SuppressWarnings("unused")
1312 private void toggleQuotaWindow() {
1313 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1314 searchLayout.toggleQuotaBar();
1315 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1316 Global.saveWindowVisible("quota", quotaBar.isVisible());
1317 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1319 @SuppressWarnings("unused")
1320 private void toggleZoomWindow() {
1321 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1322 searchLayout.toggleZoom();
1323 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1324 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1325 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1330 //***************************************************************
1331 //***************************************************************
1332 //** These functions deal with Notebook menu items
1333 //***************************************************************
1334 //***************************************************************
1335 // Setup the tree containing the user's notebooks.
1336 private void initializeNotebookTree() {
1337 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1338 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1339 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1340 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1341 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1343 // Listener when a notebook is selected
1344 private void notebookTreeSelection() {
1345 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1348 clearAttributeFilter();
1349 clearSavedSearchFilter();
1350 if (Global.mimicEvernoteInterface) {
1352 searchField.clear();
1354 menuBar.noteRestoreAction.setVisible(false);
1355 menuBar.notebookEditAction.setEnabled(true);
1356 menuBar.notebookDeleteAction.setEnabled(true);
1357 menuBar.notebookPublishAction.setEnabled(true);
1358 menuBar.notebookShareAction.setEnabled(true);
1359 menuBar.notebookIconAction.setEnabled(true);
1360 menuBar.notebookStackAction.setEnabled(true);
1361 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1362 selectedNotebookGUIDs.clear();
1364 String stackName = "";
1365 if (selections.size() > 0) {
1366 guid = (selections.get(0).text(2));
1367 stackName = selections.get(0).text(0);
1369 if (!Global.mimicEvernoteInterface) {
1370 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1371 if (selections.size()==0) {
1372 selectedNotebookGUIDs.clear();
1373 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1374 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1376 menuBar.notebookEditAction.setEnabled(false);
1377 menuBar.notebookDeleteAction.setEnabled(false);
1378 menuBar.notebookStackAction.setEnabled(false);
1379 menuBar.notebookIconAction.setEnabled(false);
1382 if (!guid.equals("") && !guid.equals("STACK")) {
1383 selectedNotebookGUIDs.add(guid);
1384 menuBar.notebookIconAction.setEnabled(true);
1386 menuBar.notebookIconAction.setEnabled(true);
1387 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1388 Notebook book = listManager.getNotebookIndex().get(j);
1389 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1390 selectedNotebookGUIDs.add(book.getGuid());
1393 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1394 listManager.loadNotesIndex();
1395 noteIndexUpdated(false);
1396 refreshEvernoteNote(true);
1397 listManager.refreshCounters = true;
1398 listManager.refreshCounters();
1399 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1402 private void clearNotebookFilter() {
1403 notebookTree.blockSignals(true);
1404 notebookTree.clearSelection();
1405 menuBar.noteRestoreAction.setVisible(false);
1406 menuBar.notebookEditAction.setEnabled(false);
1407 menuBar.notebookDeleteAction.setEnabled(false);
1408 selectedNotebookGUIDs.clear();
1409 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1410 notebookTree.blockSignals(false);
1412 // Triggered when the notebook DB has been updated
1413 private void notebookIndexUpdated() {
1414 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1416 // Get the possible icons
1417 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1418 notebookTree.setIcons(icons);
1420 if (selectedNotebookGUIDs == null)
1421 selectedNotebookGUIDs = new ArrayList<String>();
1422 List<Notebook> books = conn.getNotebookTable().getAll();
1423 for (int i=books.size()-1; i>=0; i--) {
1424 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1425 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1427 j=listManager.getArchiveNotebookIndex().size();
1433 listManager.countNotebookResults(listManager.getNoteIndex());
1434 notebookTree.blockSignals(true);
1435 notebookTree.load(books, listManager.getLocalNotebooks());
1436 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1437 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1439 selectedNotebookGUIDs.remove(i);
1441 listManager.refreshCounters = true;
1442 listManager.refreshCounters();
1443 notebookTree.blockSignals(false);
1445 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1447 // Show/Hide note information
1448 @SuppressWarnings("unused")
1449 private void toggleNotebookWindow() {
1450 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1451 searchLayout.toggleNotebook();
1452 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1453 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1454 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1456 // Add a new notebook
1457 @SuppressWarnings("unused")
1458 private void addNotebook() {
1459 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1460 NotebookEdit edit = new NotebookEdit();
1461 edit.setNotebooks(listManager.getNotebookIndex());
1464 if (!edit.okPressed())
1467 Calendar currentTime = new GregorianCalendar();
1468 Long l = new Long(currentTime.getTimeInMillis());
1469 String randint = new String(Long.toString(l));
1471 Notebook newBook = new Notebook();
1472 newBook.setUpdateSequenceNum(0);
1473 newBook.setGuid(randint);
1474 newBook.setName(edit.getNotebook());
1475 newBook.setServiceCreated(new Date().getTime());
1476 newBook.setServiceUpdated(new Date().getTime());
1477 newBook.setDefaultNotebook(false);
1478 newBook.setPublished(false);
1480 listManager.getNotebookIndex().add(newBook);
1482 listManager.getLocalNotebooks().add(newBook.getGuid());
1483 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1484 notebookIndexUpdated();
1485 listManager.countNotebookResults(listManager.getNoteIndex());
1486 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1487 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1489 // Edit an existing notebook
1490 @SuppressWarnings("unused")
1491 private void stackNotebook() {
1492 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1493 StackNotebook edit = new StackNotebook();
1495 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1496 QTreeWidgetItem currentSelection;
1497 for (int i=0; i<selections.size(); i++) {
1498 currentSelection = selections.get(0);
1499 String guid = currentSelection.text(2);
1500 if (guid.equalsIgnoreCase("")) {
1501 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1504 if (guid.equalsIgnoreCase("STACK")) {
1505 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1510 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1515 if (!edit.okPressed())
1518 String stack = edit.getStackName();
1520 for (int i=0; i<selections.size(); i++) {
1521 currentSelection = selections.get(i);
1522 String guid = currentSelection.text(2);
1523 listManager.updateNotebookStack(guid, stack);
1525 notebookIndexUpdated();
1526 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1528 // Edit an existing notebook
1529 @SuppressWarnings("unused")
1530 private void editNotebook() {
1531 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1532 NotebookEdit edit = new NotebookEdit();
1534 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1535 QTreeWidgetItem currentSelection;
1536 currentSelection = selections.get(0);
1537 edit.setNotebook(currentSelection.text(0));
1539 String guid = currentSelection.text(2);
1540 if (!guid.equalsIgnoreCase("STACK")) {
1541 edit.setTitle(tr("Edit Notebook"));
1542 edit.setNotebooks(listManager.getNotebookIndex());
1543 edit.setLocalCheckboxEnabled(false);
1544 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1545 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1546 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1547 i=listManager.getNotebookIndex().size();
1551 edit.setTitle(tr("Edit Stack"));
1552 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1553 edit.hideLocalCheckbox();
1554 edit.hideDefaultCheckbox();
1559 if (!edit.okPressed())
1563 if (guid.equalsIgnoreCase("STACK")) {
1564 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1565 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1566 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1567 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1568 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1570 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1571 currentSelection.setText(0, edit.getNotebook());
1575 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1576 currentSelection.setText(0, edit.getNotebook());
1578 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1579 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1580 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1581 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1582 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1583 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1584 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1585 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1587 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1588 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1589 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1590 linkedNotebook.setShareName(edit.getNotebook());
1591 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1593 i=listManager.getNotebookIndex().size();
1597 // Build a list of non-closed notebooks
1598 List<Notebook> nbooks = new ArrayList<Notebook>();
1599 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1600 boolean found=false;
1601 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1602 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1606 nbooks.add(listManager.getNotebookIndex().get(i));
1610 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1611 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1612 browserWindow.setNotebookList(filteredBooks);
1613 Iterator<String> set = externalWindows.keySet().iterator();
1614 while(set.hasNext())
1615 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1616 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1618 // Publish a notebook
1619 @SuppressWarnings("unused")
1620 private void publishNotebook() {
1621 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1622 QTreeWidgetItem currentSelection;
1623 currentSelection = selections.get(0);
1624 String guid = currentSelection.text(2);
1626 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1631 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1632 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1633 n = listManager.getNotebookIndex().get(i);
1635 i = listManager.getNotebookIndex().size();
1641 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1644 if (!publish.okClicked())
1647 Publishing p = publish.getPublishing();
1648 boolean isPublished = !publish.isStopPressed();
1649 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1650 n.setPublished(isPublished);
1652 listManager.getNotebookIndex().set(position, n);
1653 notebookIndexUpdated();
1655 // Publish a notebook
1656 @SuppressWarnings("unused")
1657 private void shareNotebook() {
1658 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1659 QTreeWidgetItem currentSelection;
1660 currentSelection = selections.get(0);
1661 String guid = currentSelection.text(2);
1663 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1667 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1668 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1669 n = listManager.getNotebookIndex().get(i);
1670 i = listManager.getNotebookIndex().size();
1674 String authToken = null;
1675 if (syncRunner.isConnected)
1676 authToken = syncRunner.authToken;
1677 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1682 // Delete an existing notebook
1683 @SuppressWarnings("unused")
1684 private void deleteNotebook() {
1685 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1686 boolean stacksFound = false;
1687 boolean notebooksFound = false;
1688 boolean assigned = false;
1689 // Check if any notes have this notebook
1690 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1691 for (int i=0; i<selections.size(); i++) {
1692 QTreeWidgetItem currentSelection;
1693 currentSelection = selections.get(i);
1694 String guid = currentSelection.text(2);
1695 if (!guid.equalsIgnoreCase("STACK")) {
1696 notebooksFound = true;
1697 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1698 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1699 if (noteGuid.equals(guid)) {
1701 j=listManager.getNoteIndex().size();
1702 i=selections.size();
1710 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1711 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1715 if (conn.getNotebookTable().getAll().size() == 1) {
1716 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1720 // If all notebooks are clear, verify the delete
1721 String msg1 = new String(tr("Delete selected notebooks?"));
1722 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1723 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1724 " not deleted unless selected?"));
1726 if (stacksFound && notebooksFound)
1728 if (!stacksFound && notebooksFound)
1730 if (stacksFound && !notebooksFound)
1732 if (QMessageBox.question(this, tr("Confirmation"), msg,
1733 QMessageBox.StandardButton.Yes,
1734 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1738 // If confirmed, delete the notebook
1739 for (int i=selections.size()-1; i>=0; i--) {
1740 QTreeWidgetItem currentSelection;
1741 currentSelection = selections.get(i);
1742 String guid = currentSelection.text(2);
1743 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1744 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1745 listManager.renameStack(currentSelection.text(0), "");
1747 conn.getNotebookTable().expungeNotebook(guid, true);
1748 listManager.deleteNotebook(guid);
1752 notebookIndexUpdated();
1753 // notebookTreeSelection();
1754 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1755 // listManager.countNotebookResults(listManager.getNoteIndex());
1756 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1758 // A note's notebook has been updated
1759 @SuppressWarnings("unused")
1760 private void updateNoteNotebook(String guid, String notebookGuid) {
1762 // Update the list manager
1763 listManager.updateNoteNotebook(guid, notebookGuid);
1764 listManager.countNotebookResults(listManager.getNoteIndex());
1765 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1767 // Find the name of the notebook
1768 String notebookName = null;
1769 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1770 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1771 notebookName = listManager.getNotebookIndex().get(i).getName();
1776 // If we found the name, update the browser window
1777 if (notebookName != null) {
1778 updateListNoteNotebook(guid, notebookName);
1779 if (guid.equals(currentNoteGuid)) {
1780 int pos = browserWindow.notebookBox.findText(notebookName);
1782 browserWindow.notebookBox.setCurrentIndex(pos);
1786 // If we're dealing with the current note, then we need to be sure and update the notebook there
1787 if (guid.equals(currentNoteGuid)) {
1788 if (currentNote != null) {
1789 currentNote.setNotebookGuid(notebookGuid);
1793 // Open/close notebooks
1794 @SuppressWarnings("unused")
1795 private void closeNotebooks() {
1796 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1798 if (!na.okClicked())
1802 listManager.getArchiveNotebookIndex().clear();
1804 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1805 String text = na.getClosedBookList().takeItem(i).text();
1806 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1807 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1808 Notebook n = listManager.getNotebookIndex().get(j);
1809 conn.getNotebookTable().setArchived(n.getGuid(),true);
1810 listManager.getArchiveNotebookIndex().add(n);
1811 j=listManager.getNotebookIndex().size();
1816 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1817 String text = na.getOpenBookList().takeItem(i).text();
1818 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1819 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1820 Notebook n = listManager.getNotebookIndex().get(j);
1821 conn.getNotebookTable().setArchived(n.getGuid(),false);
1822 j=listManager.getNotebookIndex().size();
1826 notebookTreeSelection();
1827 listManager.loadNotesIndex();
1828 notebookIndexUpdated();
1829 noteIndexUpdated(false);
1830 reloadTagTree(true);
1831 // noteIndexUpdated(false);
1833 // Build a list of non-closed notebooks
1834 List<Notebook> nbooks = new ArrayList<Notebook>();
1835 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1836 boolean found=false;
1837 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1838 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1842 nbooks.add(listManager.getNotebookIndex().get(i));
1845 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1846 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1847 browserWindow.setNotebookList(filteredBooks);
1849 // Update any external windows
1850 Iterator<String> set = externalWindows.keySet().iterator();
1851 while(set.hasNext())
1852 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1856 // Change the notebook's icon
1857 @SuppressWarnings("unused")
1858 private void setNotebookIcon() {
1859 boolean stackSelected = false;
1860 boolean allNotebookSelected = false;
1862 QTreeWidgetItem currentSelection;
1863 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1864 if (selections.size() == 0)
1867 currentSelection = selections.get(0);
1868 String guid = currentSelection.text(2);
1869 if (guid.equalsIgnoreCase(""))
1870 allNotebookSelected = true;
1871 if (guid.equalsIgnoreCase("STACK"))
1872 stackSelected = true;
1874 QIcon currentIcon = currentSelection.icon(0);
1878 if (!stackSelected && !allNotebookSelected) {
1879 icon = conn.getNotebookTable().getIcon(guid);
1881 dialog = new SetIcon(currentIcon, saveLastPath);
1882 dialog.setUseDefaultIcon(true);
1884 dialog = new SetIcon(icon, saveLastPath);
1885 dialog.setUseDefaultIcon(false);
1888 if (stackSelected) {
1889 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1891 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1894 dialog = new SetIcon(currentIcon, saveLastPath);
1895 dialog.setUseDefaultIcon(true);
1897 dialog = new SetIcon(icon, saveLastPath);
1898 dialog.setUseDefaultIcon(false);
1902 if (dialog.okPressed()) {
1903 saveLastPath = dialog.getPath();
1905 QIcon newIcon = dialog.getIcon();
1906 if (stackSelected) {
1907 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1908 if (newIcon == null) {
1909 newIcon = new QIcon(iconPath+"books2.png");
1911 currentSelection.setIcon(0,newIcon);
1914 if (allNotebookSelected) {
1915 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1916 if (newIcon == null) {
1917 newIcon = new QIcon(iconPath+"notebook-green.png");
1919 currentSelection.setIcon(0,newIcon);
1922 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1923 if (newIcon == null) {
1924 boolean isPublished = false;;
1925 boolean found = false;
1926 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1927 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1928 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1932 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1934 currentSelection.setIcon(0, newIcon);
1940 //***************************************************************
1941 //***************************************************************
1942 //** These functions deal with Tag menu items
1943 //***************************************************************
1944 //***************************************************************
1945 // Add a new notebook
1946 @SuppressWarnings("unused")
1947 private void addTag() {
1948 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1949 TagEdit edit = new TagEdit();
1950 edit.setTagList(listManager.getTagIndex());
1952 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1953 QTreeWidgetItem currentSelection = null;
1954 if (selections.size() > 0) {
1955 currentSelection = selections.get(0);
1956 edit.setParentTag(currentSelection.text(0));
1961 if (!edit.okPressed())
1964 Calendar currentTime = new GregorianCalendar();
1965 Long l = new Long(currentTime.getTimeInMillis());
1966 String randint = new String(Long.toString(l));
1968 Tag newTag = new Tag();
1969 newTag.setUpdateSequenceNum(0);
1970 newTag.setGuid(randint);
1971 newTag.setName(edit.getTag());
1972 if (edit.getParentTag().isChecked()) {
1973 newTag.setParentGuid(currentSelection.text(2));
1974 newTag.setParentGuidIsSet(true);
1975 currentSelection.setExpanded(true);
1977 conn.getTagTable().addTag(newTag, true);
1978 listManager.getTagIndex().add(newTag);
1979 reloadTagTree(true);
1981 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1983 @SuppressWarnings("unused")
1984 private void reloadTagTree() {
1985 reloadTagTree(false);
1987 private void reloadTagTree(boolean reload) {
1988 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1989 tagIndexUpdated(reload);
1990 boolean filter = false;
1992 listManager.countTagResults(listManager.getNoteIndex());
1993 if (notebookTree.selectedItems().size() > 0
1994 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1996 if (tagTree.selectedItems().size() > 0)
1998 tagTree.showAllTags(!filter);
1999 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2001 // Edit an existing tag
2002 @SuppressWarnings("unused")
2003 private void editTag() {
2004 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2005 TagEdit edit = new TagEdit();
2006 edit.setTitle("Edit Tag");
2007 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2008 QTreeWidgetItem currentSelection;
2009 currentSelection = selections.get(0);
2010 edit.setTag(currentSelection.text(0));
2011 edit.setTagList(listManager.getTagIndex());
2014 if (!edit.okPressed())
2017 String guid = currentSelection.text(2);
2018 currentSelection.setText(0,edit.getTag());
2020 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2021 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2022 listManager.getTagIndex().get(i).setName(edit.getTag());
2023 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2024 updateListTagName(guid);
2025 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2026 browserWindow.setTag(getTagNamesForNote(currentNote));
2027 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2031 browserWindow.setTag(getTagNamesForNote(currentNote));
2032 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2034 // Delete an existing tag
2035 @SuppressWarnings("unused")
2036 private void deleteTag() {
2037 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2039 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2040 QMessageBox.StandardButton.Yes,
2041 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2045 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2046 for (int i=selections.size()-1; i>=0; i--) {
2047 QTreeWidgetItem currentSelection;
2048 currentSelection = selections.get(i);
2049 removeTagItem(currentSelection.text(2));
2051 tagIndexUpdated(true);
2053 listManager.countTagResults(listManager.getNoteIndex());
2054 // tagTree.updateCounts(listManager.getTagCounter());
2055 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2057 // Remove a tag tree item. Go recursively down & remove the children too
2058 private void removeTagItem(String guid) {
2059 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2060 String parent = listManager.getTagIndex().get(j).getParentGuid();
2061 if (parent != null && parent.equals(guid)) {
2062 //Remove this tag's children
2063 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2066 //Now, remove this tag
2067 removeListTagName(guid);
2068 conn.getTagTable().expungeTag(guid, true);
2069 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2070 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2071 listManager.getTagIndex().remove(a);
2076 // Setup the tree containing the user's tags
2077 private void initializeTagTree() {
2078 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2079 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2080 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2081 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2082 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2083 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2085 // Listener when a tag is selected
2086 private void tagTreeSelection() {
2087 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2090 clearAttributeFilter();
2091 clearSavedSearchFilter();
2093 menuBar.noteRestoreAction.setVisible(false);
2095 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2096 QTreeWidgetItem currentSelection;
2097 selectedTagGUIDs.clear();
2098 for (int i=0; i<selections.size(); i++) {
2099 currentSelection = selections.get(i);
2100 selectedTagGUIDs.add(currentSelection.text(2));
2102 if (selections.size() > 0) {
2103 menuBar.tagEditAction.setEnabled(true);
2104 menuBar.tagDeleteAction.setEnabled(true);
2105 menuBar.tagIconAction.setEnabled(true);
2108 menuBar.tagEditAction.setEnabled(false);
2109 menuBar.tagDeleteAction.setEnabled(false);
2110 menuBar.tagIconAction.setEnabled(true);
2112 if (selections.size() > 1)
2113 menuBar.tagMergeAction.setEnabled(true);
2115 menuBar.tagMergeAction.setEnabled(false);
2116 listManager.setSelectedTags(selectedTagGUIDs);
2117 listManager.loadNotesIndex();
2118 noteIndexUpdated(false);
2119 refreshEvernoteNote(true);
2120 listManager.refreshCounters = true;
2121 listManager.refreshCounters();
2122 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2124 // trigger the tag index to be refreshed
2125 @SuppressWarnings("unused")
2126 private void tagIndexUpdated() {
2127 tagIndexUpdated(true);
2129 private void tagIndexUpdated(boolean reload) {
2130 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2131 if (selectedTagGUIDs == null)
2132 selectedTagGUIDs = new ArrayList<String>();
2134 listManager.reloadTagIndex();
2136 tagTree.blockSignals(true);
2138 tagTree.setIcons(conn.getTagTable().getAllIcons());
2139 tagTree.load(listManager.getTagIndex());
2142 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2143 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2145 selectedTagGUIDs.remove(i);
2147 tagTree.blockSignals(false);
2149 browserWindow.setTag(getTagNamesForNote(currentNote));
2150 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2152 // Show/Hide note information
2153 @SuppressWarnings("unused")
2154 private void toggleTagWindow() {
2155 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2156 if (tagTree.isVisible())
2160 menuBar.hideTags.setChecked(tagTree.isVisible());
2161 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2162 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2164 // A note's tags have been updated
2165 @SuppressWarnings("unused")
2166 private void updateNoteTags(String guid, List<String> tags) {
2167 // Save any new tags. We'll need them later.
2168 List<String> newTags = new ArrayList<String>();
2169 for (int i=0; i<tags.size(); i++) {
2170 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2171 newTags.add(tags.get(i));
2174 listManager.saveNoteTags(guid, tags);
2175 listManager.countTagResults(listManager.getNoteIndex());
2176 StringBuffer names = new StringBuffer("");
2177 for (int i=0; i<tags.size(); i++) {
2178 names = names.append(tags.get(i));
2179 if (i<tags.size()-1) {
2180 names.append(Global.tagDelimeter + " ");
2183 browserWindow.setTag(names.toString());
2186 // Now, we need to add any new tags to the tag tree
2187 for (int i=0; i<newTags.size(); i++)
2188 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2190 // Get a string containing all tag names for a note
2191 private String getTagNamesForNote(Note n) {
2192 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2193 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2195 StringBuffer buffer = new StringBuffer(100);
2196 Vector<String> v = new Vector<String>();
2197 List<String> guids = n.getTagGuids();
2202 for (int i=0; i<guids.size(); i++) {
2203 v.add(listManager.getTagNameByGuid(guids.get(i)));
2205 Comparator<String> comparator = Collections.reverseOrder();
2206 Collections.sort(v,comparator);
2207 Collections.reverse(v);
2209 for (int i = 0; i<v.size(); i++) {
2211 buffer.append(", ");
2212 buffer.append(v.get(i));
2215 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2216 return buffer.toString();
2218 // Tags were added via dropping notes from the note list
2219 @SuppressWarnings("unused")
2220 private void tagsAdded(String noteGuid, String tagGuid) {
2221 String tagName = null;
2222 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2223 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2224 tagName = listManager.getTagIndex().get(i).getName();
2225 i=listManager.getTagIndex().size();
2228 if (tagName == null)
2231 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2232 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2233 List<String> tagNames = new ArrayList<String>();
2234 tagNames.add(new String(tagName));
2235 Note n = listManager.getMasterNoteIndex().get(i);
2236 for (int j=0; j<n.getTagNames().size(); j++) {
2237 tagNames.add(new String(n.getTagNames().get(j)));
2239 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2240 if (n.getGuid().equals(currentNoteGuid)) {
2241 Collections.sort(tagNames);
2242 String display = "";
2243 for (int j=0; j<tagNames.size(); j++) {
2244 display = display+tagNames.get(j);
2245 if (j+2<tagNames.size())
2246 display = display+Global.tagDelimeter+" ";
2248 browserWindow.setTag(display);
2250 i=listManager.getMasterNoteIndex().size();
2255 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2257 private void clearTagFilter() {
2258 tagTree.blockSignals(true);
2259 tagTree.clearSelection();
2260 menuBar.noteRestoreAction.setVisible(false);
2261 menuBar.tagEditAction.setEnabled(false);
2262 menuBar.tagMergeAction.setEnabled(false);
2263 menuBar.tagDeleteAction.setEnabled(false);
2264 menuBar.tagIconAction.setEnabled(false);
2265 selectedTagGUIDs.clear();
2266 listManager.setSelectedTags(selectedTagGUIDs);
2267 tagTree.blockSignals(false);
2269 // Change the icon for a tag
2270 @SuppressWarnings("unused")
2271 private void setTagIcon() {
2272 QTreeWidgetItem currentSelection;
2273 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2274 if (selections.size() == 0)
2277 currentSelection = selections.get(0);
2278 String guid = currentSelection.text(2);
2280 QIcon currentIcon = currentSelection.icon(0);
2281 QIcon icon = conn.getTagTable().getIcon(guid);
2284 dialog = new SetIcon(currentIcon, saveLastPath);
2285 dialog.setUseDefaultIcon(true);
2287 dialog = new SetIcon(icon, saveLastPath);
2288 dialog.setUseDefaultIcon(false);
2291 if (dialog.okPressed()) {
2292 saveLastPath = dialog.getPath();
2293 QIcon newIcon = dialog.getIcon();
2294 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2295 if (newIcon == null)
2296 newIcon = new QIcon(iconPath+"tag.png");
2297 currentSelection.setIcon(0, newIcon);
2302 private void mergeTags() {
2303 List<Tag> tags = new ArrayList<Tag>();
2304 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2305 for (int i=0; i<selections.size(); i++) {
2306 Tag record = new Tag();
2307 record.setGuid(selections.get(i).text(2));
2308 record.setName(selections.get(i).text(0));
2312 TagMerge mergeDialog = new TagMerge(tags);
2314 if (!mergeDialog.okClicked())
2316 String newGuid = mergeDialog.getNewTagGuid();
2318 for (int i=0; i<tags.size(); i++) {
2319 if (!tags.get(i).getGuid().equals(newGuid)) {
2320 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2321 for (int j=0; j<noteGuids.size(); j++) {
2322 String noteGuid = noteGuids.get(j);
2323 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2324 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2325 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2329 listManager.reloadIndexes();
2332 //***************************************************************
2333 //***************************************************************
2334 //** These functions deal with Saved Search menu items
2335 //***************************************************************
2336 //***************************************************************
2337 // Add a new notebook
2338 @SuppressWarnings("unused")
2339 private void addSavedSearch() {
2340 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2341 SavedSearchEdit edit = new SavedSearchEdit();
2342 edit.setSearchList(listManager.getSavedSearchIndex());
2345 if (!edit.okPressed())
2348 Calendar currentTime = new GregorianCalendar();
2349 Long l = new Long(currentTime.getTimeInMillis());
2350 String randint = new String(Long.toString(l));
2352 SavedSearch search = new SavedSearch();
2353 search.setUpdateSequenceNum(0);
2354 search.setGuid(randint);
2355 search.setName(edit.getName());
2356 search.setQuery(edit.getQuery());
2357 search.setFormat(QueryFormat.USER);
2358 listManager.getSavedSearchIndex().add(search);
2359 conn.getSavedSearchTable().addSavedSearch(search, true);
2360 savedSearchIndexUpdated();
2361 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2363 // Edit an existing tag
2364 @SuppressWarnings("unused")
2365 private void editSavedSearch() {
2366 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2367 SavedSearchEdit edit = new SavedSearchEdit();
2368 edit.setTitle(tr("Edit Search"));
2369 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2370 QTreeWidgetItem currentSelection;
2371 currentSelection = selections.get(0);
2372 String guid = currentSelection.text(1);
2373 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2374 edit.setName(currentSelection.text(0));
2375 edit.setQuery(s.getQuery());
2376 edit.setSearchList(listManager.getSavedSearchIndex());
2379 if (!edit.okPressed())
2382 List<SavedSearch> list = listManager.getSavedSearchIndex();
2383 SavedSearch search = null;
2384 boolean found = false;
2385 for (int i=0; i<list.size(); i++) {
2386 search = list.get(i);
2387 if (search.getGuid().equals(guid)) {
2394 search.setName(edit.getName());
2395 search.setQuery(edit.getQuery());
2396 conn.getSavedSearchTable().updateSavedSearch(search, true);
2397 savedSearchIndexUpdated();
2398 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2400 // Delete an existing tag
2401 @SuppressWarnings("unused")
2402 private void deleteSavedSearch() {
2403 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2405 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2406 QMessageBox.StandardButton.Yes,
2407 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2411 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2412 for (int i=selections.size()-1; i>=0; i--) {
2413 QTreeWidgetItem currentSelection;
2414 currentSelection = selections.get(i);
2415 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2416 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2417 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2418 listManager.getSavedSearchIndex().remove(j);
2419 j=listManager.getSavedSearchIndex().size()+1;
2422 selections.remove(i);
2424 savedSearchIndexUpdated();
2425 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2427 // Setup the tree containing the user's tags
2428 private void initializeSavedSearchTree() {
2429 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2430 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2431 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2433 // Listener when a tag is selected
2434 @SuppressWarnings("unused")
2435 private void savedSearchTreeSelection() {
2436 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2438 clearNotebookFilter();
2441 clearAttributeFilter();
2443 String currentGuid = selectedSavedSearchGUID;
2444 menuBar.savedSearchEditAction.setEnabled(true);
2445 menuBar.savedSearchDeleteAction.setEnabled(true);
2446 menuBar.savedSearchIconAction.setEnabled(true);
2447 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2448 QTreeWidgetItem currentSelection;
2449 selectedSavedSearchGUID = "";
2450 for (int i=0; i<selections.size(); i++) {
2451 currentSelection = selections.get(i);
2452 if (currentSelection.text(1).equals(currentGuid)) {
2453 currentSelection.setSelected(false);
2455 selectedSavedSearchGUID = currentSelection.text(1);
2457 // i = selections.size() +1;
2460 // There is the potential for no notebooks to be selected if this
2461 // happens then we make it look like all notebooks were selecetd.
2462 // If that happens, just select the "all notebooks"
2463 if (selections.size()==0) {
2464 clearSavedSearchFilter();
2466 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2468 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2470 private void clearSavedSearchFilter() {
2471 menuBar.savedSearchEditAction.setEnabled(false);
2472 menuBar.savedSearchDeleteAction.setEnabled(false);
2473 menuBar.savedSearchIconAction.setEnabled(false);
2474 savedSearchTree.blockSignals(true);
2475 savedSearchTree.clearSelection();
2476 savedSearchTree.blockSignals(false);
2477 selectedSavedSearchGUID = "";
2478 searchField.setEditText("");
2479 searchPerformed = false;
2480 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2482 // trigger the tag index to be refreshed
2483 private void savedSearchIndexUpdated() {
2484 if (selectedSavedSearchGUID == null)
2485 selectedSavedSearchGUID = new String();
2486 savedSearchTree.blockSignals(true);
2487 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2488 savedSearchTree.load(listManager.getSavedSearchIndex());
2489 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2490 savedSearchTree.blockSignals(false);
2492 // trigger when the saved search selection changes
2493 @SuppressWarnings("unused")
2494 private void updateSavedSearchSelection() {
2495 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2497 menuBar.savedSearchEditAction.setEnabled(true);
2498 menuBar.savedSearchDeleteAction.setEnabled(true);
2499 menuBar.savedSearchIconAction.setEnabled(true);
2500 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2502 if (selections.size() > 0) {
2503 menuBar.savedSearchEditAction.setEnabled(true);
2504 menuBar.savedSearchDeleteAction.setEnabled(true);
2505 menuBar.savedSearchIconAction.setEnabled(true);
2506 selectedSavedSearchGUID = selections.get(0).text(1);
2507 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2508 searchField.setEditText(s.getQuery());
2510 menuBar.savedSearchEditAction.setEnabled(false);
2511 menuBar.savedSearchDeleteAction.setEnabled(false);
2512 menuBar.savedSearchIconAction.setEnabled(false);
2513 selectedSavedSearchGUID = "";
2514 searchField.setEditText("");
2516 searchFieldChanged();
2518 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2522 // Show/Hide note information
2523 @SuppressWarnings("unused")
2524 private void toggleSavedSearchWindow() {
2525 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2526 if (savedSearchTree.isVisible())
2527 savedSearchTree.hide();
2529 savedSearchTree.show();
2530 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2532 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2533 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2535 // Change the icon for a saved search
2536 @SuppressWarnings("unused")
2537 private void setSavedSearchIcon() {
2538 QTreeWidgetItem currentSelection;
2539 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2540 if (selections.size() == 0)
2543 currentSelection = selections.get(0);
2544 String guid = currentSelection.text(1);
2546 QIcon currentIcon = currentSelection.icon(0);
2547 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2550 dialog = new SetIcon(currentIcon, saveLastPath);
2551 dialog.setUseDefaultIcon(true);
2553 dialog = new SetIcon(icon, saveLastPath);
2554 dialog.setUseDefaultIcon(false);
2557 if (dialog.okPressed()) {
2558 saveLastPath = dialog.getPath();
2559 QIcon newIcon = dialog.getIcon();
2560 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2561 if (newIcon == null)
2562 newIcon = new QIcon(iconPath+"search.png");
2563 currentSelection.setIcon(0, newIcon);
2571 //***************************************************************
2572 //***************************************************************
2573 //** These functions deal with Help menu & tool menu items
2574 //***************************************************************
2575 //***************************************************************
2576 // Show database status
2577 @SuppressWarnings("unused")
2578 private void databaseStatus() {
2580 indexRunner.interrupt = true;
2581 int dirty = conn.getNoteTable().getDirtyCount();
2582 int unindexed = conn.getNoteTable().getUnindexedCount();
2583 DatabaseStatus status = new DatabaseStatus();
2584 status.setUnsynchronized(dirty);
2585 status.setUnindexed(unindexed);
2586 status.setNoteCount(conn.getNoteTable().getNoteCount());
2587 status.setNotebookCount(listManager.getNotebookIndex().size());
2588 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2589 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2590 status.setTagCount(listManager.getTagIndex().size());
2591 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2592 status.setWordCount(conn.getWordsTable().getWordCount());
2596 // Compact the database
2597 @SuppressWarnings("unused")
2598 private void compactDatabase() {
2599 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2600 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2601 "but please be aware that depending upon the size of your database this can be time consuming " +
2602 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2603 QMessageBox.StandardButton.Yes,
2604 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2607 setMessage("Compacting database.");
2609 listManager.compactDatabase();
2611 setMessage("Database compact is complete.");
2612 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2614 @SuppressWarnings("unused")
2615 private void accountInformation() {
2616 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2617 AccountDialog dialog = new AccountDialog();
2619 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2621 @SuppressWarnings("unused")
2622 private void releaseNotes() {
2623 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2624 QDialog dialog = new QDialog(this);
2625 QHBoxLayout layout = new QHBoxLayout();
2626 QTextEdit textBox = new QTextEdit();
2627 layout.addWidget(textBox);
2628 textBox.setReadOnly(true);
2629 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2630 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2631 QIODevice.OpenModeFlag.Text)))
2633 textBox.setText(file.readAll().toString());
2635 dialog.setWindowTitle(tr("Release Notes"));
2636 dialog.setLayout(layout);
2638 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2640 // Called when user picks Log from the help menu
2641 @SuppressWarnings("unused")
2642 private void logger() {
2643 logger.log(logger.HIGH, "Entering NeverNote.logger");
2644 LogFileDialog dialog = new LogFileDialog(emitLog);
2646 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2648 // Menu option "help/about" was selected
2649 @SuppressWarnings("unused")
2650 private void about() {
2651 logger.log(logger.HIGH, "Entering NeverNote.about");
2652 QMessageBox.about(this,
2653 tr("About NeverNote"),
2654 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2656 +tr("<hr></center>Evernote"
2657 +"An Open Source Evernote Client.<br><br>"
2658 +"Licensed under GPL v2. <br><hr><br>"
2659 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2660 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2661 +"PDFRenderer is licened under the LGPL<br>"
2662 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2663 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2664 +"Jazzy is licened under the LGPL<br>"
2665 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2666 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2667 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2668 logger.log(logger.HIGH, "Leaving NeverNote.about");
2670 // Hide the entire left hand side
2671 @SuppressWarnings("unused")
2672 private void toggleLeftSide() {
2675 hidden = !menuBar.hideLeftSide.isChecked();
2676 menuBar.hideLeftSide.setChecked(!hidden);
2679 leftSplitter1.setHidden(true);
2681 leftSplitter1.setHidden(false);
2683 Global.saveWindowVisible("leftPanel", hidden);
2686 public void checkForUpdates() {
2687 // Send off thread to check for a new version
2688 versionChecker = new QNetworkAccessManager(this);
2689 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2690 QNetworkRequest request = new QNetworkRequest();
2691 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2692 versionChecker.get(request);
2694 @SuppressWarnings("unused")
2695 private void upgradeFileRead(QNetworkReply reply) {
2696 if (!reply.isReadable())
2699 String winVersion = Global.version;
2700 String osxVersion = Global.version;
2701 String linuxVersion = Global.version;
2702 String linux64Version = Global.version;
2703 String version = Global.version;
2705 // Determine the versions available
2706 QByteArray data = reply.readLine();
2707 while (data != null && !reply.atEnd()) {
2708 String line = data.toString();
2710 if (line.contains(":"))
2711 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2714 if (line.toLowerCase().contains("windows"))
2715 winVersion = lineVersion;
2716 else if (line.toLowerCase().contains("os-x"))
2717 osxVersion = lineVersion;
2718 else if (line.toLowerCase().contains("linux amd64"))
2719 linux64Version = lineVersion;
2720 else if (line.toLowerCase().contains("linux i386"))
2721 linuxVersion = lineVersion;
2722 else if (line.toLowerCase().contains("default"))
2723 version = lineVersion;
2725 // Read the next line
2726 data = reply.readLine();
2729 // Now we need to determine what system we are on.
2730 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2731 version = winVersion;
2732 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2733 version = osxVersion;
2734 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2735 if (System.getProperty("os.arch").contains("amd64") ||
2736 System.getProperty("os.arch").contains("x86_64"))
2737 version = linux64Version;
2739 version = linuxVersion;
2743 for (String validVersion : Global.validVersions) {
2744 if (version.equals(validVersion))
2748 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2750 if (dialog.remindMe())
2751 Global.setCheckVersionUpgrade(true);
2753 Global.setCheckVersionUpgrade(false);
2757 //***************************************************************
2758 //***************************************************************
2759 //** These functions deal with the Toolbar
2760 //***************************************************************
2761 //***************************************************************
2762 @SuppressWarnings("unused")
2763 private void focusSearch() {
2764 searchField.setFocus();
2767 // Text in the search bar has been cleared
2768 private void searchFieldCleared() {
2771 // This is done because we want to force a reload of
2772 // images. Some images we may want to highlight the text.
2773 readOnlyCache.clear();
2774 inkNoteCache.clear();
2776 QWebSettings.setMaximumPagesInCache(0);
2777 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2779 searchField.setEditText("");
2780 saveNoteColumnPositions();
2781 saveNoteIndexWidth();
2782 noteIndexUpdated(true);
2783 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2784 currentNote = listManager.getNoteIndex().get(0);
2785 currentNoteGuid = currentNote.getGuid();
2787 refreshEvernoteNote(true);
2788 if (currentNote != null)
2789 loadNoteBrowserInformation(browserWindow);
2791 // text in the search bar changed. We only use this to tell if it was cleared,
2792 // otherwise we trigger off searchFieldChanged.
2793 @SuppressWarnings("unused")
2794 private void searchFieldTextChanged(String text) {
2795 QWebSettings.setMaximumPagesInCache(0);
2796 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2798 if (text.trim().equals("")) {
2799 searchFieldCleared();
2800 if (searchPerformed) {
2802 // This is done because we want to force a reload of
2803 // images. Some images we may want to highlight the text.
2805 readOnlyCache.clear();
2806 inkNoteCache.clear();
2808 listManager.setEnSearch("");
2809 listManager.loadNotesIndex();
2810 refreshEvernoteNote(true);
2811 noteIndexUpdated(false);
2812 refreshEvernoteNote(true);
2814 searchPerformed = false;
2817 // Text in the toolbar has changed
2818 private void searchFieldChanged() {
2819 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2821 readOnlyCache.clear();
2822 inkNoteCache.clear();
2823 saveNoteColumnPositions();
2824 saveNoteIndexWidth();
2825 String text = searchField.currentText();
2826 listManager.setEnSearch(text.trim());
2827 listManager.loadNotesIndex();
2828 noteIndexUpdated(false);
2829 refreshEvernoteNote(true);
2830 searchPerformed = true;
2831 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2834 // Build the window tool bar
2835 private void setupToolBar() {
2836 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2837 toolBar = addToolBar(tr("Tool Bar"));
2838 toolBar.setObjectName("toolBar");
2839 menuBar.setupToolBarVisible();
2840 if (!Global.isWindowVisible("toolBar"))
2841 toolBar.setVisible(false);
2843 toolBar.setVisible(true);
2845 // toolBar.addWidget(menuBar);
2846 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2847 // toolBar.addSeparator();
2848 prevButton = toolBar.addAction("Previous");
2849 QIcon prevIcon = new QIcon(iconPath+"back.png");
2850 prevButton.setIcon(prevIcon);
2851 prevButton.triggered.connect(this, "previousViewedAction()");
2852 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2854 nextButton = toolBar.addAction("Next");
2855 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2856 nextButton.setIcon(nextIcon);
2857 nextButton.triggered.connect(this, "nextViewedAction()");
2858 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2860 upButton = toolBar.addAction("Up");
2861 QIcon upIcon = new QIcon(iconPath+"up.png");
2862 upButton.setIcon(upIcon);
2863 upButton.triggered.connect(this, "upAction()");
2864 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2867 downButton = toolBar.addAction("Down");
2868 QIcon downIcon = new QIcon(iconPath+"down.png");
2869 downButton.setIcon(downIcon);
2870 downButton.triggered.connect(this, "downAction()");
2871 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2873 synchronizeButton = toolBar.addAction("Synchronize");
2874 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2875 synchronizeIconAngle = 0;
2876 synchronizeButton.triggered.connect(this, "evernoteSync()");
2877 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2879 printButton = toolBar.addAction("Print");
2880 QIcon printIcon = new QIcon(iconPath+"print.png");
2881 printButton.setIcon(printIcon);
2882 printButton.triggered.connect(this, "printNote()");
2883 togglePrintButton(Global.isToolbarButtonVisible("print"));
2885 tagButton = toolBar.addAction("Tag");
2886 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2887 tagButton.setIcon(tagIcon);
2888 tagButton.triggered.connect(browserWindow, "modifyTags()");
2889 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2891 attributeButton = toolBar.addAction("Attributes");
2892 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2893 attributeButton.setIcon(attributeIcon);
2894 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2895 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2897 emailButton = toolBar.addAction("Email");
2898 QIcon emailIcon = new QIcon(iconPath+"email.png");
2899 emailButton.setIcon(emailIcon);
2900 emailButton.triggered.connect(this, "emailNote()");
2901 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2903 deleteButton = toolBar.addAction("Delete");
2904 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2905 deleteButton.setIcon(deleteIcon);
2906 deleteButton.triggered.connect(this, "deleteNote()");
2907 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2909 newButton = toolBar.addAction("New");
2910 QIcon newIcon = new QIcon(iconPath+"new.png");
2911 newButton.triggered.connect(this, "addNote()");
2912 newButton.setIcon(newIcon);
2913 toggleNewButton(Global.isToolbarButtonVisible("new"));
2915 allNotesButton = toolBar.addAction("All Notes");
2916 QIcon allIcon = new QIcon(iconPath+"books.png");
2917 allNotesButton.triggered.connect(this, "allNotes()");
2918 allNotesButton.setIcon(allIcon);
2919 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2921 //toolBar.addSeparator();
2922 //toolBar.addWidget(new QLabel(tr("Quota:")));
2923 //toolBar.addWidget(quotaBar);
2924 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2926 //toolBar.addSeparator();
2928 //toolBar.addWidget(new QLabel(tr("Zoom")));
2929 //toolBar.addWidget(zoomSpinner);
2931 //toolBar.addWidget(new QLabel(" "));
2932 //toolBar.addSeparator();
2933 //toolBar.addWidget(new QLabel(tr(" Search:")));
2934 //toolBar.addWidget(searchField);
2935 QSizePolicy sizePolicy = new QSizePolicy();
2936 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2937 QLabel spacer = new QLabel("");
2938 spacer.setSizePolicy(sizePolicy);
2939 toolBar.addWidget(spacer);
2940 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2942 //searchClearButton = toolBar.addAction("Search Clear");
2943 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2944 //searchClearButton.setIcon(searchClearIcon);
2945 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2946 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2948 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2950 // Update the sychronize button picture
2952 public QMenu createPopupMenu() {
2953 QMenu contextMenu = super.createPopupMenu();
2955 contextMenu.addSeparator();
2956 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2957 contextMenu.addAction(prevAction);
2958 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2960 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2961 contextMenu.addAction(nextAction);
2962 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2964 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2965 contextMenu.addAction(upAction);
2966 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2968 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2969 contextMenu.addAction(downAction);
2970 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2972 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2973 contextMenu.addAction(synchronizeAction);
2974 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2976 QAction printAction = addContextAction("print", tr("Print"));
2977 contextMenu.addAction(printAction);
2978 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2980 QAction tagAction = addContextAction("tag", tr("Tag"));
2981 contextMenu.addAction(tagAction);
2982 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2984 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2985 contextMenu.addAction(attributeAction);
2986 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2988 QAction emailAction = addContextAction("email", tr("Email"));
2989 contextMenu.addAction(emailAction);
2990 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2992 QAction deleteAction = addContextAction("delete", tr("Delete"));
2993 contextMenu.addAction(deleteAction);
2994 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2996 QAction newAction = addContextAction("new", tr("Add"));
2997 contextMenu.addAction(newAction);
2998 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3000 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3001 contextMenu.addAction(allNotesAction);
3002 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3004 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3005 contextMenu.addAction(searchClearAction);
3006 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3011 private QAction addContextAction(String config, String name) {
3012 QAction newAction = new QAction(this);
3013 newAction.setText(name);
3014 newAction.setCheckable(true);
3015 newAction.setChecked(Global.isToolbarButtonVisible(config));
3018 private void togglePrevArrowButton(Boolean toggle) {
3019 prevButton.setVisible(toggle);
3020 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3022 private void toggleNextArrowButton(Boolean toggle) {
3023 nextButton.setVisible(toggle);
3024 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3026 private void toggleUpArrowButton(Boolean toggle) {
3027 upButton.setVisible(toggle);
3028 Global.saveToolbarButtonsVisible("upArrow", toggle);
3030 private void toggleDownArrowButton(Boolean toggle) {
3031 downButton.setVisible(toggle);
3032 Global.saveToolbarButtonsVisible("downArrow", toggle);
3034 private void toggleSynchronizeButton(Boolean toggle) {
3035 synchronizeButton.setVisible(toggle);
3036 Global.saveToolbarButtonsVisible("synchronize", toggle);
3038 private void togglePrintButton(Boolean toggle) {
3039 printButton.setVisible(toggle);
3040 Global.saveToolbarButtonsVisible("print", toggle);
3042 private void toggleTagButton(Boolean toggle) {
3043 tagButton.setVisible(toggle);
3044 Global.saveToolbarButtonsVisible("tag", toggle);
3046 private void toggleAttributeButton(Boolean toggle) {
3047 attributeButton.setVisible(toggle);
3048 Global.saveToolbarButtonsVisible("attribute", toggle);
3050 private void toggleEmailButton(Boolean toggle) {
3051 emailButton.setVisible(toggle);
3052 Global.saveToolbarButtonsVisible("email", toggle);
3054 private void toggleDeleteButton(Boolean toggle) {
3055 deleteButton.setVisible(toggle);
3056 Global.saveToolbarButtonsVisible("delete", toggle);
3058 private void toggleNewButton(Boolean toggle) {
3059 newButton.setVisible(toggle);
3060 Global.saveToolbarButtonsVisible("new", toggle);
3062 private void toggleAllNotesButton(Boolean toggle) {
3063 allNotesButton.setVisible(toggle);
3064 Global.saveToolbarButtonsVisible("allNotes", toggle);
3066 @SuppressWarnings("unused")
3067 private void toggleSearchClearButton(Boolean toggle) {
3068 searchClearButton.setVisible(toggle);
3069 Global.saveToolbarButtonsVisible("searchClear", toggle);
3076 @SuppressWarnings("unused")
3077 private void updateSyncButton() {
3079 if (syncIcons == null) {
3080 syncIcons = new ArrayList<QPixmap>();
3082 synchronizeIconAngle = 0;
3083 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3085 for (int i=0; i<=360; i++) {
3086 QPixmap rotatedPix = new QPixmap(pix.size());
3087 QPainter p = new QPainter(rotatedPix);
3088 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3089 QSize size = pix.size();
3090 p.translate(size.width()/2, size.height()/2);
3093 p.setBackgroundMode(BGMode.OpaqueMode);
3094 p.translate(-size.width()/2, -size.height()/2);
3095 p.drawPixmap(0,0, pix);
3097 syncIcons.add(rotatedPix);
3101 synchronizeIconAngle++;
3102 if (synchronizeIconAngle > 359)
3103 synchronizeIconAngle=0;
3104 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3107 // Synchronize with Evernote
3108 @SuppressWarnings("unused")
3109 private void evernoteSync() {
3110 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3111 if (!Global.isConnected)
3113 if (Global.isConnected)
3114 synchronizeAnimationTimer.start(5);
3115 // synchronizeAnimationTimer.start(200);
3117 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3119 private void updateQuotaBar() {
3120 long limit = Global.getUploadLimit();
3121 long amount = Global.getUploadAmount();
3122 if (amount>0 && limit>0) {
3123 int percent =(int)(amount*100/limit);
3124 quotaBar.setValue(percent);
3126 quotaBar.setValue(0);
3129 @SuppressWarnings("unused")
3130 private void zoomChanged() {
3131 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3134 //****************************************************************
3135 //****************************************************************
3136 //* System Tray functions
3137 //****************************************************************
3138 //****************************************************************
3139 private void trayToggleVisible() {
3144 if (windowMaximized)
3151 @SuppressWarnings("unused")
3152 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3153 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3154 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3155 trayToggleVisible();
3160 //***************************************************************
3161 //***************************************************************
3162 //** These functions deal with the trash tree
3163 //***************************************************************
3164 //***************************************************************
3165 // Setup the tree containing the trash.
3166 @SuppressWarnings("unused")
3167 private void trashTreeSelection() {
3168 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3170 clearNotebookFilter();
3172 clearAttributeFilter();
3173 clearSavedSearchFilter();
3175 String tempGuid = currentNoteGuid;
3177 // currentNoteGuid = "";
3178 currentNote = new Note();
3179 selectedNoteGUIDs.clear();
3180 listManager.getSelectedNotebooks().clear();
3181 listManager.getSelectedTags().clear();
3182 listManager.setSelectedSavedSearch("");
3183 browserWindow.clear();
3185 // toggle the add buttons
3186 newButton.setEnabled(!newButton.isEnabled());
3187 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3188 menuBar.noteAdd.setVisible(true);
3190 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3191 if (selections.size() == 0) {
3192 currentNoteGuid = trashNoteGuid;
3193 trashNoteGuid = tempGuid;
3194 Global.showDeleted = false;
3195 menuBar.noteRestoreAction.setEnabled(false);
3196 menuBar.noteRestoreAction.setVisible(false);
3199 currentNoteGuid = trashNoteGuid;
3200 trashNoteGuid = tempGuid;
3201 menuBar.noteRestoreAction.setEnabled(true);
3202 menuBar.noteRestoreAction.setVisible(true);
3203 Global.showDeleted = true;
3205 listManager.loadNotesIndex();
3206 noteIndexUpdated(false);
3207 //// browserWindow.setEnabled(newButton.isEnabled());
3208 browserWindow.setReadOnly(!newButton.isEnabled());
3209 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3211 // Empty the trash file
3212 @SuppressWarnings("unused")
3213 private void emptyTrash() {
3214 // browserWindow.clear();
3215 listManager.emptyTrash();
3216 if (trashTree.selectedItems().size() > 0) {
3217 listManager.getSelectedNotebooks().clear();
3218 listManager.getSelectedTags().clear();
3219 listManager.setSelectedSavedSearch("");
3220 newButton.setEnabled(!newButton.isEnabled());
3221 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3222 menuBar.noteAdd.setVisible(true);
3223 browserWindow.clear();
3226 clearNotebookFilter();
3227 clearSavedSearchFilter();
3228 clearAttributeFilter();
3230 Global.showDeleted = false;
3231 menuBar.noteRestoreAction.setEnabled(false);
3232 menuBar.noteRestoreAction.setVisible(false);
3234 listManager.loadNotesIndex();
3235 noteIndexUpdated(false);
3238 // Show/Hide trash window
3239 @SuppressWarnings("unused")
3240 private void toggleTrashWindow() {
3241 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3242 if (trashTree.isVisible())
3246 menuBar.hideTrash.setChecked(trashTree.isVisible());
3248 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3249 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3251 private void clearTrashFilter() {
3252 Global.showDeleted = false;
3253 newButton.setEnabled(true);
3254 menuBar.noteAdd.setEnabled(true);
3255 menuBar.noteAdd.setVisible(true);
3256 trashTree.blockSignals(true);
3257 trashTree.clearSelection();
3258 trashTree.blockSignals(false);
3263 //***************************************************************
3264 //***************************************************************
3265 //** These functions deal with connection settings
3266 //***************************************************************
3267 //***************************************************************
3268 // SyncRunner had a problem and things are disconnected
3269 @SuppressWarnings("unused")
3270 private void remoteErrorDisconnect() {
3271 menuBar.connectAction.setText(tr("Connect"));
3272 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3273 menuBar.synchronizeAction.setEnabled(false);
3274 Global.isConnected = false;
3275 synchronizeAnimationTimer.stop();
3278 // Do a manual connect/disconnect
3279 private void remoteConnect() {
3280 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3282 if (Global.isConnected) {
3283 Global.isConnected = false;
3284 syncRunner.enDisconnect();
3285 setupConnectMenuOptions();
3290 AESEncrypter aes = new AESEncrypter();
3292 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3293 } catch (FileNotFoundException e) {
3294 // File not found, so we'll just get empty strings anyway.
3297 if (Global.getProxyValue("url").equals("")) {
3298 System.setProperty("http.proxyHost","") ;
3299 System.setProperty("http.proxyPort", "") ;
3300 System.setProperty("https.proxyHost","") ;
3301 System.setProperty("https.proxyPort", "") ;
3304 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3305 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3306 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3307 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3309 if (Global.getProxyValue("userid").equals("")) {
3310 Authenticator.setDefault(new Authenticator() {
3312 protected PasswordAuthentication getPasswordAuthentication() {
3314 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3320 syncRunner.userStoreUrl = Global.userStoreUrl;
3321 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3322 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3324 String userid = aes.getUserid();
3325 String password = aes.getPassword();
3326 if (!userid.equals("") && !password.equals("")) {
3327 Global.username = userid;
3328 Global.password = password;
3329 syncRunner.username = Global.username;
3330 syncRunner.password = Global.password;
3331 syncRunner.enConnect();
3334 Global.isConnected = syncRunner.isConnected;
3336 if (!Global.isConnected) {
3337 // Show the login dialog box
3338 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3339 LoginDialog login = new LoginDialog();
3342 if (!login.okPressed()) {
3346 Global.username = login.getUserid();
3347 Global.password = login.getPassword();
3349 syncRunner.username = Global.username;
3350 syncRunner.password = Global.password;
3351 syncRunner.enConnect();
3352 Global.isConnected = syncRunner.isConnected;
3355 if (!Global.isConnected)
3358 setupConnectMenuOptions();
3359 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3361 private void setupConnectMenuOptions() {
3362 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3363 if (!Global.isConnected) {
3364 menuBar.connectAction.setText(tr("Connect"));
3365 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3366 menuBar.synchronizeAction.setEnabled(false);
3368 menuBar.connectAction.setText(tr("Disconnect"));
3369 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3370 menuBar.synchronizeAction.setEnabled(true);
3372 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3377 //***************************************************************
3378 //***************************************************************
3379 //** These functions deal with the GUI Attribute tree
3380 //***************************************************************
3381 //***************************************************************
3382 @SuppressWarnings("unused")
3383 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3385 // clearTagFilter();
3386 // clearNotebookFilter();
3388 // clearSavedSearchFilter();
3390 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3391 if (item.childCount() > 0) {
3392 item.setSelected(false);
3394 Global.createdBeforeFilter.reset();
3395 Global.createdSinceFilter.reset();
3396 Global.changedBeforeFilter.reset();
3397 Global.changedSinceFilter.reset();
3398 Global.containsFilter.reset();
3399 attributeTreeSelected = item;
3400 DateAttributeFilterTable f = null;
3401 f = findDateAttributeFilterTable(item.parent());
3403 f.select(item.parent().indexOfChild(item));
3405 Global.containsFilter.select(item.parent().indexOfChild(item));
3408 listManager.loadNotesIndex();
3409 noteIndexUpdated(false);
3412 attributeTreeSelected = null;
3413 item.setSelected(false);
3414 Global.createdBeforeFilter.reset();
3415 Global.createdSinceFilter.reset();
3416 Global.changedBeforeFilter.reset();
3417 Global.changedSinceFilter.reset();
3418 Global.containsFilter.reset();
3419 listManager.loadNotesIndex();
3420 noteIndexUpdated(false);
3422 // This determines what attribute filter we need, depending upon the selection
3423 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3424 if (w.parent() != null && w.childCount() > 0) {
3425 QTreeWidgetItem parent = w.parent();
3426 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3427 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3428 return Global.createdSinceFilter;
3429 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3430 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3431 return Global.createdBeforeFilter;
3432 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3433 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3434 return Global.changedSinceFilter;
3435 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3436 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3437 return Global.changedBeforeFilter;
3442 // Show/Hide attribute search window
3443 @SuppressWarnings("unused")
3444 private void toggleAttributesWindow() {
3445 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3446 if (attributeTree.isVisible())
3447 attributeTree.hide();
3449 attributeTree.show();
3450 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3452 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3453 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3455 private void clearAttributeFilter() {
3456 Global.createdBeforeFilter.reset();
3457 Global.createdSinceFilter.reset();
3458 Global.changedBeforeFilter.reset();
3459 Global.changedSinceFilter.reset();
3460 Global.containsFilter.reset();
3461 attributeTreeSelected = null;
3462 attributeTree.blockSignals(true);
3463 attributeTree.clearSelection();
3464 attributeTree.blockSignals(false);
3468 //***************************************************************
3469 //***************************************************************
3470 //** These functions deal with the GUI Note index table
3471 //***************************************************************
3472 //***************************************************************
3473 // Initialize the note list table
3474 private void initializeNoteTable() {
3475 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3476 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3477 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3478 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3480 // Show/Hide trash window
3481 @SuppressWarnings("unused")
3482 private void toggleNoteListWindow() {
3483 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3484 if (noteTableView.isVisible())
3485 noteTableView.hide();
3487 noteTableView.show();
3488 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3490 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3491 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3493 // Handle the event that a user selects a note from the table
3494 @SuppressWarnings("unused")
3495 private void noteTableSelection() {
3496 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3498 if (historyGuids.size() == 0) {
3499 historyGuids.add(currentNoteGuid);
3500 historyPosition = 1;
3502 noteTableView.showColumn(Global.noteTableGuidPosition);
3504 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3505 if (!Global.isColumnVisible("guid"))
3506 noteTableView.hideColumn(Global.noteTableGuidPosition);
3508 if (selections.size() > 0) {
3510 menuBar.noteDuplicateAction.setEnabled(true);
3511 menuBar.noteOnlineHistoryAction.setEnabled(true);
3512 menuBar.noteMergeAction.setEnabled(true);
3513 selectedNoteGUIDs.clear();
3514 if (selections.size() != 1 || Global.showDeleted) {
3515 menuBar.noteDuplicateAction.setEnabled(false);
3517 if (selections.size() != 1 || !Global.isConnected) {
3518 menuBar.noteOnlineHistoryAction.setEnabled(false);
3520 if (selections.size() == 1) {
3521 menuBar.noteMergeAction.setEnabled(false);
3523 for (int i=0; i<selections.size(); i++) {
3524 int row = selections.get(i).row();
3526 upButton.setEnabled(false);
3528 upButton.setEnabled(true);
3529 if (row < listManager.getNoteTableModel().rowCount()-1)
3530 downButton.setEnabled(true);
3532 downButton.setEnabled(false);
3533 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3534 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3535 currentNoteGuid = (String)ix.values().toArray()[0];
3536 selectedNoteGUIDs.add(currentNoteGuid);
3540 nextButton.setEnabled(true);
3541 prevButton.setEnabled(true);
3543 int endPosition = historyGuids.size()-1;
3544 for (int j=historyPosition; j<=endPosition; j++) {
3545 historyGuids.remove(historyGuids.size()-1);
3547 historyGuids.add(currentNoteGuid);
3548 historyPosition = historyGuids.size();
3550 if (historyPosition <= 1)
3551 prevButton.setEnabled(false);
3552 if (historyPosition == historyGuids.size())
3553 nextButton.setEnabled(false);
3555 fromHistory = false;
3556 scrollToGuid(currentNoteGuid);
3557 refreshEvernoteNote(true);
3558 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3560 // Trigger a refresh when the note db has been updated
3561 private void noteIndexUpdated(boolean reload) {
3562 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3564 refreshEvernoteNoteList();
3565 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3566 noteTableView.load(reload);
3567 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3569 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3570 pos = noteTableView.proxyModel.rowCount();
3573 if (noteTableView.proxyModel.rowCount() == 0)
3576 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3578 currentNoteGuid = (String)i.data();
3582 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3584 scrollToGuid(currentNoteGuid);
3585 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3587 // Called when the list of notes is updated
3588 private void refreshEvernoteNoteList() {
3589 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3590 browserWindow.setDisabled(false);
3591 if (selectedNoteGUIDs == null)
3592 selectedNoteGUIDs = new ArrayList<String>();
3593 selectedNoteGUIDs.clear(); // clear out old entries
3595 String saveCurrentNoteGuid = new String();
3596 String tempNoteGuid = new String();
3598 historyGuids.clear();
3599 historyPosition = 0;
3600 prevButton.setEnabled(false);
3601 nextButton.setEnabled(false);
3603 if (currentNoteGuid == null)
3604 currentNoteGuid = new String();
3606 //determine current note guid
3607 for (Note note : listManager.getNoteIndex()) {
3608 tempNoteGuid = note.getGuid();
3609 if (currentNoteGuid.equals(tempNoteGuid)) {
3610 saveCurrentNoteGuid = tempNoteGuid;
3614 if (listManager.getNoteIndex().size() == 0) {
3615 currentNoteGuid = "";
3617 browserWindow.clear();
3618 browserWindow.setDisabled(true);
3621 if (!saveCurrentNoteGuid.equals("")) {
3622 refreshEvernoteNote(false);
3624 currentNoteGuid = "";
3626 reloadTagTree(false);
3628 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3630 // Called when the previous arrow button is clicked
3631 @SuppressWarnings("unused")
3632 private void previousViewedAction() {
3633 if (!prevButton.isEnabled())
3635 if (historyPosition == 0)
3638 if (historyPosition <= 0)
3640 String historyGuid = historyGuids.get(historyPosition-1);
3642 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3643 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3644 if (modelIndex != null) {
3645 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3646 String tableGuid = (String)ix.values().toArray()[0];
3647 if (tableGuid.equals(historyGuid)) {
3648 noteTableView.selectRow(i);
3654 @SuppressWarnings("unused")
3655 private void nextViewedAction() {
3656 if (!nextButton.isEnabled())
3658 String historyGuid = historyGuids.get(historyPosition);
3661 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3662 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3663 if (modelIndex != null) {
3664 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3665 String tableGuid = (String)ix.values().toArray()[0];
3666 if (tableGuid.equals(historyGuid)) {
3667 noteTableView.selectRow(i);
3673 // Called when the up arrow is clicked
3674 @SuppressWarnings("unused")
3675 private void upAction() {
3676 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3677 int row = selections.get(0).row();
3679 noteTableView.selectRow(row-1);
3682 // Called when the down arrow is clicked
3683 @SuppressWarnings("unused")
3684 private void downAction() {
3685 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3686 int row = selections.get(0).row();
3687 int max = listManager.getNoteTableModel().rowCount();
3689 noteTableView.selectRow(row+1);
3692 // Update a tag string for a specific note in the list
3693 @SuppressWarnings("unused")
3694 private void updateListTags(String guid, List<String> tags) {
3695 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3696 StringBuffer tagBuffer = new StringBuffer();
3697 for (int i=0; i<tags.size(); i++) {
3698 tagBuffer.append(tags.get(i));
3699 if (i<tags.size()-1)
3700 tagBuffer.append(", ");
3703 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3704 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3705 if (modelIndex != null) {
3706 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3707 String tableGuid = (String)ix.values().toArray()[0];
3708 if (tableGuid.equals(guid)) {
3709 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3710 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3711 noteTableView.proxyModel.invalidate();
3716 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3718 // Update a title for a specific note in the list
3719 @SuppressWarnings("unused")
3720 private void updateListAuthor(String guid, String author) {
3721 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3723 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3724 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3725 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3726 if (modelIndex != null) {
3727 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3728 String tableGuid = (String)ix.values().toArray()[0];
3729 if (tableGuid.equals(guid)) {
3730 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3731 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3732 noteTableView.proxyModel.invalidate();
3738 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3740 private void updateListNoteNotebook(String guid, String notebook) {
3741 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3742 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3743 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3745 // Update a title for a specific note in the list
3746 @SuppressWarnings("unused")
3747 private void updateListSourceUrl(String guid, String url) {
3748 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3750 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3751 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3752 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3753 if (modelIndex != null) {
3754 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3755 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3756 String tableGuid = (String)ix.values().toArray()[0];
3757 if (tableGuid.equals(guid)) {
3758 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3759 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3760 noteTableView.proxyModel.invalidate();
3765 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3767 @SuppressWarnings("unused")
3768 private void updateListGuid(String oldGuid, String newGuid) {
3769 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3771 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3772 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3773 if (modelIndex != null) {
3774 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3775 String tableGuid = (String)ix.values().toArray()[0];
3776 if (tableGuid.equals(oldGuid)) {
3777 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3778 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3783 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3785 private void updateListTagName(String guid) {
3786 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3788 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3789 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3790 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3792 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3793 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3794 if (modelIndex != null) {
3795 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3796 String noteGuid = (String)ix.values().toArray()[0];
3797 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3798 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3799 i=listManager.getNoteTableModel().rowCount();
3805 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3807 private void removeListTagName(String guid) {
3808 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3810 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3811 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3812 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3813 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3814 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3817 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3818 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3819 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3820 if (modelIndex != null) {
3821 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3822 String noteGuid = (String)ix.values().toArray()[0];
3823 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3824 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3825 i=listManager.getNoteTableModel().rowCount();
3831 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3833 private void updateListNotebookName(String oldName, String newName) {
3834 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3836 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3837 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3838 if (modelIndex != null) {
3839 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3840 String tableName = (String)ix.values().toArray()[0];
3841 if (tableName.equalsIgnoreCase(oldName)) {
3842 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3846 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3848 @SuppressWarnings("unused")
3849 private void updateListDateCreated(String guid, QDateTime date) {
3850 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3852 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3853 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3854 if (modelIndex != null) {
3855 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3856 String tableGuid = (String)ix.values().toArray()[0];
3857 if (tableGuid.equals(guid)) {
3858 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3859 noteTableView.proxyModel.invalidate();
3864 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3866 @SuppressWarnings("unused")
3867 private void updateListDateSubject(String guid, QDateTime date) {
3868 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3870 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3871 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3872 if (modelIndex != null) {
3873 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3874 String tableGuid = (String)ix.values().toArray()[0];
3875 if (tableGuid.equals(guid)) {
3876 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3877 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3878 noteTableView.proxyModel.invalidate();
3883 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3885 private void updateListDateChanged(String guid, QDateTime date) {
3886 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3888 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3889 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3890 if (modelIndex != null) {
3891 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3892 String tableGuid = (String)ix.values().toArray()[0];
3893 if (tableGuid.equals(guid)) {
3894 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3895 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3900 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3902 private void updateListDateChanged() {
3903 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3904 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3905 updateListDateChanged(currentNoteGuid, date);
3906 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3909 private void scrollToCurrentGuid() {
3910 //scrollToGuid(currentNoteGuid);
3911 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3912 if (selections.size() == 0)
3914 QModelIndex index = selections.get(0);
3915 int row = selections.get(0).row();
3916 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3919 // Scroll to the current GUID in tthe list.
3920 // Scroll to a particular index item
3921 private void scrollToGuid(String guid) {
3922 if (currentNote == null || guid == null)
3924 if (currentNote.isActive() && Global.showDeleted) {
3925 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3926 if (!listManager.getNoteIndex().get(i).isActive()) {
3927 currentNote = listManager.getNoteIndex().get(i);
3928 currentNoteGuid = currentNote.getGuid();
3929 i = listManager.getNoteIndex().size();
3933 if (!currentNote.isActive() && !Global.showDeleted) {
3934 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3935 if (listManager.getNoteIndex().get(i).isActive()) {
3936 currentNote = listManager.getNoteIndex().get(i);
3937 currentNoteGuid = currentNote.getGuid();
3938 i = listManager.getNoteIndex().size();
3943 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3944 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3945 if (currentNoteGuid.equals(index.data())) {
3946 // noteTableView.selectionModel().blockSignals(true);
3947 noteTableView.selectRow(i);
3948 // noteTableView.selectionModel().blockSignals(false);
3949 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3950 i=listManager.getNoteTableModel().rowCount();
3953 noteTableView.repaint();
3955 // Show/Hide columns
3956 private void showColumns() {
3957 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3958 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3959 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3960 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3961 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3962 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3963 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3964 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3965 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3966 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3967 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3969 // Title color has changed
3970 @SuppressWarnings("unused")
3971 private void titleColorChanged(Integer color) {
3972 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3974 QColor backgroundColor = new QColor();
3975 QColor foregroundColor = new QColor(QColor.black);
3976 backgroundColor.setRgb(color);
3978 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3979 foregroundColor.setRgb(QColor.white.rgb());
3981 if (selectedNoteGUIDs.size() == 0)
3982 selectedNoteGUIDs.add(currentNoteGuid);
3984 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3985 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3986 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3987 if (modelIndex != null) {
3988 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3989 String tableGuid = (String)ix.values().toArray()[0];
3990 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3991 for (int k=0; k<Global.noteTableColumnCount; k++) {
3992 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3993 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3994 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3996 i=listManager.getNoteTableModel().rowCount();
4001 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
4003 // Wide list was chosen
4004 public void narrowListView() {
4005 saveNoteColumnPositions();
4006 saveNoteIndexWidth();
4008 int sortCol = noteTableView.proxyModel.sortColumn();
4009 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4010 Global.setSortColumn(sortCol);
4011 Global.setSortOrder(sortOrder);
4013 Global.setListView(Global.View_List_Narrow);
4015 menuBar.wideListView.blockSignals(true);
4016 menuBar.narrowListView.blockSignals(true);
4018 menuBar.wideListView.setChecked(false);
4019 menuBar.narrowListView.setChecked(true);
4021 menuBar.wideListView.blockSignals(false);
4022 menuBar.narrowListView.blockSignals(false);
4024 mainLeftRightSplitter.addWidget(noteTableView);
4025 mainLeftRightSplitter.addWidget(browserWindow);
4026 restoreWindowState(false);
4027 noteTableView.repositionColumns();
4028 noteTableView.resizeColumnWidths();
4029 noteTableView.resizeRowHeights();
4031 sortCol = Global.getSortColumn();
4032 sortOrder = Global.getSortOrder();
4033 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4036 noteTableView.load(false);
4037 refreshEvernoteNote(true);
4038 scrollToCurrentGuid();
4040 public void wideListView() {
4041 int sortCol = noteTableView.proxyModel.sortColumn();
4042 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4043 Global.setSortColumn(sortCol);
4044 Global.setSortOrder(sortOrder);
4047 saveNoteColumnPositions();
4048 saveNoteIndexWidth();
4049 Global.setListView(Global.View_List_Wide);
4051 menuBar.wideListView.blockSignals(true);
4052 menuBar.narrowListView.blockSignals(true);
4054 menuBar.wideListView.setChecked(true);
4055 menuBar.narrowListView.setChecked(false);
4057 menuBar.wideListView.blockSignals(false);
4058 menuBar.narrowListView.blockSignals(false);
4059 browserIndexSplitter.setVisible(true);
4060 browserIndexSplitter.addWidget(noteTableView);
4061 browserIndexSplitter.addWidget(browserWindow);
4062 restoreWindowState(false);
4063 noteTableView.repositionColumns();
4064 noteTableView.resizeColumnWidths();
4065 noteTableView.resizeRowHeights();
4067 sortCol = Global.getSortColumn();
4068 sortOrder = Global.getSortOrder();
4069 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4072 noteTableView.load(false);
4073 scrollToCurrentGuid();
4077 //***************************************************************
4078 //***************************************************************
4079 //** External editor window functions
4080 //***************************************************************
4081 //***************************************************************
4082 private void listDoubleClick() {
4084 if (externalWindows.containsKey(currentNoteGuid)) {
4085 externalWindows.get(currentNoteGuid).raise();
4088 // We have a new external editor to create
4089 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4090 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4091 newBrowser.setWindowIcon(appIcon);
4092 externalWindows.put(currentNoteGuid, newBrowser);
4093 showEditorButtons(newBrowser.getBrowserWindow());
4094 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
4095 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4096 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4097 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4098 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4099 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4101 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4102 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4103 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4104 browserWindow.blockApplication.connect(this, "blockApplication(Long)");
4105 browserWindow.unblockApplication.connect(this, "unblockApplication()");
4109 @SuppressWarnings("unused")
4110 private void externalWindowTitleEdited(String guid, String text) {
4111 if (guid.equals(currentNoteGuid)) {
4112 browserWindow.setTitle(text);
4115 @SuppressWarnings({ "rawtypes", "unused" })
4116 private void externalWindowTagsEdited(String guid, List values) {
4117 StringBuffer line = new StringBuffer(100);
4118 for (int i=0; i<values.size(); i++) {
4120 line.append(Global.tagDelimeter+" ");
4121 line.append(values.get(i));
4123 if (guid.equals(currentNoteGuid)) {
4124 browserWindow.setTag(line.toString());
4127 @SuppressWarnings("unused")
4128 private void externalWindowClosing(String guid) {
4129 externalWindows.remove(guid);
4134 //***************************************************************
4135 //***************************************************************
4136 //** These functions deal with Note specific things
4137 //***************************************************************
4138 //***************************************************************
4139 @SuppressWarnings("unused")
4140 private void setNoteDirty() {
4141 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4143 // Find if the note is being edited externally. If it is, update it.
4144 if (externalWindows.containsKey(currentNoteGuid)) {
4145 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4146 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4147 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4148 window.getBrowserWindow().getBrowser().setContent(unicode);
4151 // If the note is dirty, then it is unsynchronized by default.
4155 // Set the note as dirty and check if its status is synchronized in the display table
4157 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4158 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4162 // If this wasn't already marked as unsynchronized, then we need to update the table
4163 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4164 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4165 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4166 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4167 if (modelIndex != null) {
4168 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4169 String tableGuid = (String)ix.values().toArray()[0];
4170 if (tableGuid.equals(currentNoteGuid)) {
4171 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4177 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4179 @SuppressWarnings("unused")
4180 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4181 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4182 QByteArray unicode = codec.fromUnicode(content);
4183 noteCache.remove(guid);
4184 noteCache.put(guid, unicode.toString());
4185 if (guid.equals(currentNoteGuid)) {
4187 browserWindow.getBrowser().setContent(unicode);
4190 thumbnailRunner.addWork("GENERATE "+ guid);
4191 saveNote(guid, browser);
4195 private void saveNote() {
4197 saveNote(currentNoteGuid, browserWindow);
4198 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4202 private void saveNote(String guid, BrowserWindow window) {
4203 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4204 logger.log(logger.EXTREME, "Note is dirty.");
4207 logger.log(logger.EXTREME, "Saving to cache");
4208 QTextCodec codec = QTextCodec.codecForLocale();
4209 // QTextDecoder decoder = codec.makeDecoder();
4210 codec = QTextCodec.codecForName("UTF-8");
4211 QByteArray unicode = codec.fromUnicode(window.getContent());
4212 noteCache.put(guid, unicode.toString());
4214 logger.log(logger.EXTREME, "updating list manager");
4215 listManager.updateNoteContent(guid, window.getContent());
4216 logger.log(logger.EXTREME, "Updating title");
4217 listManager.updateNoteTitle(guid, window.getTitle());
4218 updateListDateChanged();
4220 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4221 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4222 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4223 currentNote = listManager.getNoteIndex().get(i);
4224 i = listManager.getNoteIndex().size();
4229 // Get a note from Evernote (and put it in the browser)
4230 private void refreshEvernoteNote(boolean reload) {
4231 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4233 if (Global.disableViewing) {
4234 browserWindow.setEnabled(false);
4239 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4241 Global.cryptCounter =0;
4243 browserWindow.setReadOnly(true);
4251 browserWindow.loadingData(true);
4253 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4254 if (currentNote == null)
4256 loadNoteBrowserInformation(browserWindow);
4259 private void loadNoteBrowserInformation(BrowserWindow browser) {
4260 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4261 formatter.setNote(currentNote, Global.pdfPreview());
4262 formatter.setHighlight(listManager.getEnSearch());
4264 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4265 js = new QByteArray();
4266 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4267 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4268 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>");
4269 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4270 js.append("<style> img { max-width:100%; }</style>");
4271 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4272 js.append("</head>");
4273 formatter.setNote(currentNote, Global.pdfPreview());
4274 js.append(formatter.rebuildNoteHTML());
4275 js.append("</HTML>");
4276 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4277 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4278 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4279 browser.getBrowser().setContent(js);
4280 noteCache.put(currentNoteGuid, js.toString());
4282 if (formatter.resourceError)
4283 resourceErrorMessage();
4284 readOnly = formatter.readOnly;
4285 inkNote = formatter.inkNote;
4287 readOnlyCache.put(currentNoteGuid, true);
4289 inkNoteCache.put(currentNoteGuid, true);
4291 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4292 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4293 js = new QByteArray(cachedContent);
4294 browser.getBrowser().setContent(js);
4295 if (readOnlyCache.containsKey(currentNoteGuid))
4297 if (inkNoteCache.containsKey(currentNoteGuid))
4300 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4301 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4303 if (readOnly || inkNote)
4304 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4306 browser.getBrowser().page().setContentEditable(true);
4307 browser.setReadOnly(readOnly);
4308 deleteButton.setEnabled(!readOnly);
4309 tagButton.setEnabled(!readOnly);
4310 menuBar.noteDelete.setEnabled(!readOnly);
4311 menuBar.noteTags.setEnabled(!readOnly);
4312 browser.setNote(currentNote);
4314 if (currentNote != null && currentNote.getNotebookGuid() != null &&
4315 conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4316 deleteButton.setEnabled(false);
4317 menuBar.notebookDeleteAction.setEnabled(false);
4319 deleteButton.setEnabled(true);
4320 menuBar.notebookDeleteAction.setEnabled(true);
4323 // Build a list of non-closed notebooks
4324 List<Notebook> nbooks = new ArrayList<Notebook>();
4325 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4326 boolean found=false;
4327 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4328 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4332 nbooks.add(listManager.getNotebookIndex().get(i));
4335 browser.setTitle(currentNote.getTitle());
4336 browser.setTag(getTagNamesForNote(currentNote));
4337 browser.setAuthor(currentNote.getAttributes().getAuthor());
4339 browser.setAltered(currentNote.getUpdated());
4340 browser.setCreation(currentNote.getCreated());
4341 if (currentNote.getAttributes().getSubjectDate() > 0)
4342 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4344 browser.setSubjectDate(currentNote.getCreated());
4345 browser.setUrl(currentNote.getAttributes().getSourceURL());
4347 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4348 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4349 browser.setAllTags(tagList);
4351 browser.setCurrentTags(currentNote.getTagNames());
4353 scrollToGuid(currentNoteGuid);
4355 browser.loadingData(false);
4356 if (thumbnailViewer.isActiveWindow())
4359 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4360 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4363 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4365 // Save a generated thumbnail
4366 private void toggleNoteInformation() {
4367 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4368 browserWindow.toggleInformation();
4369 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4370 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4371 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4373 // Listener triggered when a print button is pressed
4374 @SuppressWarnings("unused")
4375 private void printNote() {
4376 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4378 QPrintDialog dialog = new QPrintDialog();
4379 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4380 QPrinter printer = dialog.printer();
4381 browserWindow.getBrowser().print(printer);
4383 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4386 // Listener triggered when the email button is pressed
4387 @SuppressWarnings("unused")
4388 private void emailNote() {
4389 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4391 if (Desktop.isDesktopSupported()) {
4392 Desktop desktop = Desktop.getDesktop();
4394 String text2 = browserWindow.getContentsToEmail();
4395 QUrl url = new QUrl("mailto:");
4396 url.addQueryItem("subject", currentNote.getTitle());
4397 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4398 url.addQueryItem("body", text2);
4399 QDesktopServices.openUrl(url);
4403 if (desktop.isSupported(Desktop.Action.MAIL)) {
4404 URI uriMailTo = null;
4406 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4407 String text = browserWindow.getContentsToEmail();
4408 //text = "<b>" +text +"</b>";
4409 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4410 +"&BODY=" +text, null);
4411 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4412 +"&ATTACHMENT=d:/test.pdf", null);
4413 desktop.mail(uriMailTo);
4414 } catch (URISyntaxException e) {
4415 e.printStackTrace();
4416 } catch (IOException e) {
4417 e.printStackTrace();
4424 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4426 // Reindex all notes
4427 @SuppressWarnings("unused")
4428 private void fullReindex() {
4429 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4430 indexRunner.addWork("REINDEXALL");
4431 setMessage(tr("Database will be reindexed."));
4432 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4434 // Listener when a user wants to reindex a specific note
4435 @SuppressWarnings("unused")
4436 private void reindexNote() {
4437 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4438 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4439 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4441 if (selectedNotebookGUIDs.size() > 1)
4442 setMessage(tr("Notes will be reindexed."));
4444 setMessage(tr("Note will be reindexed."));
4445 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4448 @SuppressWarnings("unused")
4449 private void deleteNote() {
4450 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4451 if (currentNote == null)
4453 if (currentNoteGuid.equals(""))
4455 String title = null;
4456 if (selectedNoteGUIDs.size() == 1)
4457 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4459 // If we are deleting non-trash notes
4460 if (currentNote.isActive()) {
4461 if (Global.verifyDelete()) {
4463 if (selectedNoteGUIDs.size() > 1) {
4464 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4467 msg = new String(tr("Delete note \"") +title +"\"?");
4469 msg = new String(tr("Delete note selected note?"));
4471 if (QMessageBox.question(this, tr("Confirmation"), msg,
4472 QMessageBox.StandardButton.Yes,
4473 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4477 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4478 selectedNoteGUIDs.add(currentNoteGuid);
4479 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4480 listManager.deleteNote(selectedNoteGUIDs.get(i));
4483 // If we are deleting from the trash.
4484 if (Global.verifyDelete()) {
4486 if (selectedNoteGUIDs.size() > 1) {
4487 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4490 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4492 msg = new String(tr("Permanently delete note selected note?"));
4494 if (QMessageBox.question(this, "Confirmation", msg,
4495 QMessageBox.StandardButton.Yes,
4496 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4500 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4501 selectedNoteGUIDs.add(currentNoteGuid);
4502 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4503 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4504 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4505 if (modelIndex != null) {
4506 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4507 String tableGuid = (String)ix.values().toArray()[0];
4508 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4509 listManager.getNoteTableModel().removeRow(j);
4514 listManager.expungeNote(selectedNoteGUIDs.get(i));
4517 currentNoteGuid = "";
4518 listManager.loadNotesIndex();
4519 noteIndexUpdated(false);
4520 refreshEvernoteNote(true);
4521 scrollToGuid(currentNoteGuid);
4522 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4525 @SuppressWarnings("unused")
4526 private void addNote() {
4527 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4528 // browserWindow.setEnabled(true);
4529 browserWindow.setReadOnly(false);
4531 Calendar currentTime = new GregorianCalendar();
4532 StringBuffer noteString = new StringBuffer(100);
4533 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4534 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4537 if (Global.overrideDefaultFont()) {
4538 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4539 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4540 noteString.append("<br clear=\"none\" />\n");
4541 noteString.append("</span>\n</font>\n");
4543 noteString.append("<br clear=\"none\" />\n");
4544 noteString.append("</en-note>");
4546 Long l = new Long(currentTime.getTimeInMillis());
4547 String randint = new String(Long.toString(l));
4549 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4551 // for the first non-archived notebook. Finally, if nothing else we
4552 // pick the first notebook in the list.
4553 String notebook = null;
4554 listManager.getNotebookIndex().get(0).getGuid();
4555 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4556 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4557 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4558 notebook = currentSelectedNotebook.text(2);
4560 boolean found = false;
4561 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4562 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4563 boolean match = false;
4564 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4565 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4567 j = listManager.getArchiveNotebookIndex().size();
4571 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4572 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4574 // Now we have a list of good notebooks, so we can look for the default
4576 for (int i=0; i<goodNotebooks.size(); i++) {
4577 if (goodNotebooks.get(i).isDefaultNotebook()) {
4578 notebook = goodNotebooks.get(i).getGuid();
4580 i = goodNotebooks.size();
4584 if (goodNotebooks.size() > 0 && !found)
4585 notebook = goodNotebooks.get(0).getGuid();
4588 notebook = listManager.getNotebookIndex().get(0).getGuid();
4591 Note newNote = new Note();
4592 newNote.setUpdateSequenceNum(0);
4593 newNote.setGuid(randint);
4594 newNote.setNotebookGuid(notebook);
4595 newNote.setTitle("");
4596 newNote.setContent(noteString.toString());
4597 newNote.setDeleted(0);
4598 newNote.setCreated(System.currentTimeMillis());
4599 newNote.setUpdated(System.currentTimeMillis());
4600 newNote.setActive(true);
4601 NoteAttributes na = new NoteAttributes();
4602 na.setLatitude(0.0);
4603 na.setLongitude(0.0);
4604 na.setAltitude(0.0);
4605 newNote.setAttributes(new NoteAttributes());
4606 newNote.setTagGuids(new ArrayList<String>());
4607 newNote.setTagNames(new ArrayList<String>());
4609 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4610 if (Global.newNoteWithSelectedTags()) {
4611 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4612 QTreeWidgetItem currentSelection;
4613 for (int i=0; i<selections.size(); i++) {
4614 currentSelection = selections.get(i);
4615 newNote.getTagGuids().add(currentSelection.text(2));
4616 newNote.getTagNames().add(currentSelection.text(0));
4620 conn.getNoteTable().addNote(newNote, true);
4621 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4622 listManager.addNote(newNote);
4623 // noteTableView.insertRow(newNote, true, -1);
4625 currentNote = newNote;
4626 currentNoteGuid = currentNote.getGuid();
4627 noteTableView.clearSelection();
4628 refreshEvernoteNote(true);
4629 listManager.countNotebookResults(listManager.getNoteIndex());
4630 browserWindow.titleLabel.setFocus();
4631 browserWindow.titleLabel.selectAll();
4632 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4634 // If the window is hidden, then we want to popup this in an external window &
4637 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4639 // Restore a note from the trash;
4640 @SuppressWarnings("unused")
4641 private void restoreNote() {
4643 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4644 selectedNoteGUIDs.add(currentNoteGuid);
4645 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4646 listManager.restoreNote(selectedNoteGUIDs.get(i));
4648 currentNoteGuid = "";
4649 listManager.loadNotesIndex();
4650 noteIndexUpdated(false);
4653 // Search a note for specific txt
4654 @SuppressWarnings("unused")
4655 private void findText() {
4657 find.setFocusOnTextField();
4659 @SuppressWarnings("unused")
4660 private void doFindText() {
4661 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4664 @SuppressWarnings("unused")
4665 private void updateNoteTitle(String guid, String title) {
4666 listManager.setNoteSynchronized(guid, false);
4668 // Signal received that note content has changed. Normally we just need the guid to remove
4669 // it from the cache.
4670 @SuppressWarnings("unused")
4671 private void invalidateNoteCache(String guid, String content) {
4672 String v = noteCache.remove(guid);
4673 // if (guid.equals(currentNoteGuid) && !noteDirty)
4674 refreshEvernoteNote(true);
4676 // Signal received that a note guid has changed
4677 @SuppressWarnings("unused")
4678 private void noteGuidChanged(String oldGuid, String newGuid) {
4679 if (noteCache.containsKey(oldGuid)) {
4680 if (!oldGuid.equals(currentNoteGuid)) {
4681 String cache = noteCache.get(oldGuid);
4682 noteCache.put(newGuid, cache);
4683 noteCache.remove(oldGuid);
4685 noteCache.remove(oldGuid);
4686 noteCache.put(newGuid, browserWindow.getContent());
4690 listManager.updateNoteGuid(oldGuid, newGuid, false);
4691 if (currentNoteGuid.equals(oldGuid)) {
4692 if (currentNote != null)
4693 currentNote.setGuid(newGuid);
4694 currentNoteGuid = newGuid;
4697 if (externalWindows.containsKey(oldGuid)) {
4698 ExternalBrowse b = externalWindows.get(oldGuid);
4699 externalWindows.remove(oldGuid);
4700 b.getBrowserWindow().getNote().setGuid(newGuid);
4701 externalWindows.put(newGuid, b);
4704 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4705 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4706 noteTableView.proxyModel.addGuid(newGuid);
4707 i=listManager.getNoteIndex().size();
4711 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4712 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4713 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4714 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4718 // Toggle the note editor button bar
4719 private void toggleEditorButtonBar() {
4720 if (browserWindow.buttonsVisible) {
4721 browserWindow.hideButtons();
4722 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4723 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4725 browserWindow.buttonsVisible = true;
4726 showEditorButtons(browserWindow);
4728 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4730 // Show editor buttons
4731 private void showEditorButtons(BrowserWindow browser) {
4732 browser.buttonLayout.setVisible(true);
4733 browser.undoAction.setVisible(false);
4735 browser.undoButton.setVisible(false);
4737 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4738 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4739 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4740 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4741 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4742 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4743 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4744 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4745 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4746 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4747 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4748 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4749 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4750 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4751 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4752 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4753 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4754 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4755 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4756 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4757 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4758 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4759 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4761 private void duplicateNote(String guid) {
4763 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4764 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4765 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4766 oldNote.setResources(resList);
4767 duplicateNote(oldNote);
4769 private void duplicateNote(Note oldNote) {
4771 // Now that we have a good notebook guid, we need to move the conflicting note
4772 // to the local notebook
4773 Calendar currentTime = new GregorianCalendar();
4774 Long l = new Long(currentTime.getTimeInMillis());
4775 String newGuid = new String(Long.toString(l));
4777 // Note newNote = oldNote.deepCopy();
4778 Note newNote = (Note)Global.deepCopy(oldNote);
4779 newNote.setUpdateSequenceNum(0);
4780 newNote.setGuid(newGuid);
4781 newNote.setDeleted(0);
4782 newNote.setActive(true);
4785 List<String> tagNames = new ArrayList<String>();
4786 List<String> tagGuids = new ArrayList<String>();;
4787 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4788 tagNames.add(oldNote.getTagNames().get(i));
4789 tagGuids.add(oldNote.getTagGuids().get(i));
4792 // Sort note Tags to make them look nice
4793 for (int i=0; i<tagNames.size()-1; i++) {
4794 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4795 String n1 = tagNames.get(i);
4796 String n2 = tagNames.get(i+1);
4797 tagNames.set(i, n2);
4798 tagNames.set(i+1, n1);
4801 newNote.setTagGuids(tagGuids);
4802 newNote.setTagNames(tagNames);
4804 // Add tag guids to note
4807 // Duplicate resources
4808 List<Resource> resList = oldNote.getResources();
4809 if (resList == null)
4810 resList = new ArrayList<Resource>();
4812 for (int i=0; i<resList.size(); i++) {
4814 while (l == prevGuid) {
4815 currentTime = new GregorianCalendar();
4816 l = new Long(currentTime.getTimeInMillis());
4819 String newResGuid = new String(Long.toString(l));
4820 resList.get(i).setNoteGuid(newGuid);
4821 resList.get(i).setGuid(newResGuid);
4822 resList.get(i).setUpdateSequenceNum(0);
4823 resList.get(i).setActive(true);
4824 conn.getNoteTable().noteResourceTable.saveNoteResource(
4825 (Resource)Global.deepCopy(resList.get(i)), true);
4827 newNote.setResources(resList);
4829 // Add note to the database
4830 listManager.addNote(newNote);
4831 conn.getNoteTable().addNote(newNote, true);
4832 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4833 noteTableView.insertRow(newNote, true, -1);
4834 currentNoteGuid = newNote.getGuid();
4835 currentNote = newNote;
4836 refreshEvernoteNote(true);
4837 listManager.countNotebookResults(listManager.getNoteIndex());
4841 @SuppressWarnings("unused")
4842 private void allNotes() {
4843 clearAttributeFilter();
4844 clearNotebookFilter();
4845 clearSavedSearchFilter();
4848 searchField.clear();
4849 if (Global.mimicEvernoteInterface) {
4850 notebookTree.selectGuid("");
4852 notebookTreeSelection();
4853 refreshEvernoteNote(true);
4856 @SuppressWarnings("unused")
4857 private void mergeNotes() {
4858 logger.log(logger.HIGH, "Merging notes");
4861 String masterGuid = null;
4862 List<String> sources = new ArrayList<String>();
4864 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4865 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4866 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4867 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4869 masterGuid = (String)ix.values().toArray()[0];
4871 sources.add((String)ix.values().toArray()[0]);
4874 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4875 logger.log(logger.EXTREME, "Children count: "+sources.size());
4876 mergeNoteContents(masterGuid, sources);
4877 currentNoteGuid = masterGuid;
4878 noteIndexUpdated(false);
4879 refreshEvernoteNote(true);
4882 private void mergeNoteContents(String targetGuid, List<String> sources) {
4883 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4884 String newContent = target.getContent();
4885 newContent = newContent.replace("</en-note>", "<br></br>");
4887 for (int i=0; i<sources.size(); i++) {
4888 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4889 if (source.isSetTitle()) {
4890 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4892 String sourceContent = source.getContent();
4893 logger.log(logger.EXTREME, "Merging contents into note");
4894 logger.log(logger.EXTREME, sourceContent);
4895 logger.log(logger.EXTREME, "End of content");
4896 int startOfNote = sourceContent.indexOf("<en-note>");
4897 sourceContent = sourceContent.substring(startOfNote+9);
4898 int endOfNote = sourceContent.indexOf("</en-note>");
4899 sourceContent = sourceContent.substring(0,endOfNote);
4900 newContent = newContent + sourceContent;
4901 logger.log(logger.EXTREME, "New note content");
4902 logger.log(logger.EXTREME, newContent);
4903 logger.log(logger.EXTREME, "End of content");
4904 for (int j=0; j<source.getResourcesSize(); j++) {
4905 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4906 Resource r = source.getResources().get(j);
4907 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4909 Calendar currentTime = new GregorianCalendar();
4910 Long l = new Long(currentTime.getTimeInMillis());
4914 while (l == prevGuid) {
4915 currentTime = new GregorianCalendar();
4916 l = new Long(currentTime.getTimeInMillis());
4918 String newResGuid = new String(Long.toString(l));
4919 newRes.setNoteGuid(targetGuid);
4920 newRes.setGuid(newResGuid);
4921 newRes.setUpdateSequenceNum(0);
4922 newRes.setActive(true);
4923 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4926 logger.log(logger.EXTREME, "Updating note");
4927 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4928 for (int i=0; i<sources.size(); i++) {
4929 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4930 listManager.deleteNote(sources.get(i));
4932 logger.log(logger.EXTREME, "Exiting merge note");
4934 // A resource within a note has had a guid change
4935 @SuppressWarnings("unused")
4936 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4937 if (!oldGuid.equals(newGuid))
4938 Global.resourceMap.put(oldGuid, newGuid);
4940 // View a thumbnail of the note
4941 public void thumbnailView() {
4943 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4944 QFile thumbnail = new QFile(thumbnailName);
4945 if (!thumbnail.exists()) {
4947 QImage img = new QImage();
4948 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4949 thumbnailViewer.setThumbnail(img);
4951 thumbnailViewer.setThumbnail(thumbnailName);
4952 if (!thumbnailViewer.isVisible())
4953 thumbnailViewer.showFullScreen();
4955 // An error happened while saving a note. Inform the user
4956 @SuppressWarnings("unused")
4957 private void saveRunnerError(String guid, String msg) {
4959 String title = "*Unknown*";
4960 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4961 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4962 title = listManager.getMasterNoteIndex().get(i).getTitle();
4963 i=listManager.getMasterNoteIndex().size();
4966 msg = "An error has happened while saving the note \"" +title+
4967 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4968 "As a result, changes to the note may not be saved properly in the database."+
4969 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4970 "\nbe lost. Please review the note to recover any critical data before restarting.";
4972 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4975 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4976 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4977 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4978 // Find an idle preview object
4979 for (int i=0; i<thumbGenerators.size(); i++) {
4980 if (thumbGenerators.get(i).mutex.tryLock()) {
4981 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4982 thumbGenerators.get(i).loadContent(guid, html, zoom);
4986 if (thumbGenerators.size() >= 1) {
4987 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4991 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4992 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4993 thumbGenerators.add(preview);
4995 if (preview.mutex.tryLock()) {
4996 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4997 preview.loadContent(guid, html, zoom);
4999 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5004 //**********************************************************
5005 //**********************************************************
5006 //* Online user actions
5007 //**********************************************************
5008 //**********************************************************
5009 private void setupOnlineMenu() {
5010 if (!Global.isConnected) {
5011 menuBar.noteOnlineHistoryAction.setEnabled(false);
5012 menuBar.selectiveSyncAction.setEnabled(false);
5015 menuBar.noteOnlineHistoryAction.setEnabled(true);
5016 menuBar.selectiveSyncAction.setEnabled(true);
5019 @SuppressWarnings("unused")
5020 private void viewNoteHistory() {
5021 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5023 if (currentNote.getUpdateSequenceNum() == 0) {
5024 setMessage(tr("Note has never been synchronized."));
5025 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5029 setMessage(tr("Getting Note History"));
5031 Note currentOnlineNote = null;
5034 if (Global.isPremium())
5035 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5037 versions = new ArrayList<NoteVersionId>();
5038 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5039 } catch (EDAMUserException e) {
5040 setMessage("EDAMUserException: " +e.getMessage());
5042 } catch (EDAMSystemException e) {
5043 setMessage("EDAMSystemException: " +e.getMessage());
5045 } catch (EDAMNotFoundException e) {
5046 setMessage(tr("Note not found on server."));
5047 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
5049 } catch (TException e) {
5050 setMessage("EDAMTransactionException: " +e.getMessage());
5054 // If we've gotten this far, we have a good note.
5055 if (historyWindow == null) {
5056 historyWindow = new OnlineNoteHistory(logger, conn);
5057 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5058 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5059 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5061 historyWindow.historyCombo.clear();
5063 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5064 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5066 historyWindow.setCurrent(isDirty);
5068 loadHistoryWindowContent(currentOnlineNote);
5069 historyWindow.load(versions);
5070 setMessage(tr("History retrieved"));
5072 historyWindow.exec();
5074 private Note reloadHistoryWindow(String selection) {
5076 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5077 String dateTimeFormat = new String(fmt);
5078 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5082 for (int i=0; i<versions.size(); i++) {
5083 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5084 if (versionDate.toString().equals(selection))
5088 if (index > -1 || selection.indexOf("Current") > -1) {
5089 Note historyNote = null;
5092 usn = versions.get(index).getUpdateSequenceNum();
5093 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5095 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5096 } catch (EDAMUserException e) {
5097 setMessage("EDAMUserException: " +e.getMessage());
5100 } catch (EDAMSystemException e) {
5101 setMessage("EDAMSystemException: " +e.getMessage());
5104 } catch (EDAMNotFoundException e) {
5105 setMessage("EDAMNotFoundException: " +e.getMessage());
5108 } catch (TException e) {
5109 setMessage("EDAMTransactionException: " +e.getMessage());
5115 if (historyNote != null)
5116 historyWindow.setContent(historyNote);
5122 private void loadHistoryWindowContent(Note note) {
5123 note.setUpdateSequenceNum(0);
5124 historyWindow.setContent(note);
5126 @SuppressWarnings("unused")
5127 private void restoreHistoryNoteAsNew() {
5128 setMessage(tr("Restoring as new note."));
5129 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5130 setMessage(tr("Note has been restored as a new note."));
5132 @SuppressWarnings("unused")
5133 private void restoreHistoryNote() {
5134 setMessage(tr("Restoring note."));
5135 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5136 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5139 for (int i=0; i<n.getResourcesSize(); i++) {
5140 n.getResources().get(i).setActive(true);
5141 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5143 listManager.addNote(n);
5144 conn.getNoteTable().addNote(n, true);
5145 refreshEvernoteNote(true);
5146 setMessage(tr("Note has been restored."));
5148 @SuppressWarnings("unused")
5149 private void setupSelectiveSync() {
5151 // Get a list of valid notebooks
5152 List<Notebook> notebooks = null;
5153 List<Tag> tags = null;
5154 List<LinkedNotebook> linkedNotebooks = null;
5156 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5157 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5158 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5159 } catch (EDAMUserException e) {
5160 setMessage("EDAMUserException: " +e.getMessage());
5162 } catch (EDAMSystemException e) {
5163 setMessage("EDAMSystemException: " +e.getMessage());
5165 } catch (TException e) {
5166 setMessage("EDAMTransactionException: " +e.getMessage());
5168 } catch (EDAMNotFoundException e) {
5169 setMessage("EDAMNotFoundException: " +e.getMessage());
5173 // Split up notebooks into synchronized & non-synchronized
5174 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5175 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5177 for (int i=notebooks.size()-1; i>=0; i--) {
5178 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5179 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5180 ignoredBooks.add(notebooks.get(i));
5181 j=dbIgnoredNotebooks.size();
5186 // split up tags into synchronized & non-synchronized
5187 List<Tag> ignoredTags = new ArrayList<Tag>();
5188 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5190 for (int i=tags.size()-1; i>=0; i--) {
5191 for (int j=0; j<dbIgnoredTags.size(); j++) {
5192 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5193 ignoredTags.add(tags.get(i));
5194 j=dbIgnoredTags.size();
5199 // split up linked notebooks into synchronized & non-synchronized
5200 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5201 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5202 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5203 String notebookGuid = linkedNotebooks.get(i).getGuid();
5204 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5205 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5206 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5207 j=dbIgnoredLinkedNotebooks.size();
5212 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5214 if (!ignore.okClicked())
5219 // Clear out old notebooks & add the new ones
5220 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5221 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5222 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5225 List<String> newNotebooks = new ArrayList<String>();
5226 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5227 String text = ignore.getIgnoredBookList().takeItem(i).text();
5228 for (int j=0; j<notebooks.size(); j++) {
5229 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5230 Notebook n = notebooks.get(j);
5231 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5233 newNotebooks.add(n.getGuid());
5238 // Clear out old tags & add new ones
5239 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5240 for (int i=0; i<oldIgnoreTags.size(); i++) {
5241 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5244 List<String> newTags = new ArrayList<String>();
5245 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5246 String text = ignore.getIgnoredTagList().takeItem(i).text();
5247 for (int j=0; j<tags.size(); j++) {
5248 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5249 Tag t = tags.get(j);
5250 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5251 newTags.add(t.getGuid());
5257 // Clear out old tags & add new ones
5258 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5259 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5260 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5263 List<String> newLinked = new ArrayList<String>();
5264 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5265 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5266 for (int j=0; j<linkedNotebooks.size(); j++) {
5267 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5268 LinkedNotebook t = linkedNotebooks.get(j);
5269 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5270 newLinked.add(t.getGuid());
5271 j=linkedNotebooks.size();
5276 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5282 //**********************************************************
5283 //**********************************************************
5284 //* XML Modifying methods
5285 //**********************************************************
5286 //**********************************************************
5287 // An error has happended fetching a resource. let the user know
5288 private void resourceErrorMessage() {
5291 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5292 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5293 "In a perfect world this wouldn't happen, but it has.\n" +
5294 "It is embarasing when a program like me, designed to save all your\n"+
5295 "precious data, has a problem finding data.\n\n" +
5296 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5297 "In the mean time, I'm not going to let you make changes to this note.\n" +
5298 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5299 "this note on the Evernote servers. Sorry."+
5300 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5302 browserWindow.setReadOnly(true);
5308 //**********************************************************
5309 //**********************************************************
5311 //**********************************************************
5312 //**********************************************************
5313 // We should now do a sync with Evernote
5314 private void syncTimer() {
5315 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5316 syncRunner.syncNeeded = true;
5317 syncRunner.disableUploads = Global.disableUploads;
5319 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5321 private void syncStart() {
5322 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5324 if (!syncRunning && Global.isConnected) {
5325 syncRunner.setConnected(true);
5326 syncRunner.setKeepRunning(Global.keepRunning);
5327 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5329 if (syncThreadsReady > 0) {
5330 thumbnailRunner.interrupt = true;
5331 saveNoteIndexWidth();
5332 saveNoteColumnPositions();
5333 if (syncRunner.addWork("SYNC")) {
5335 syncRunner.syncNeeded = true;
5340 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5342 @SuppressWarnings("unused")
5343 private void syncThreadComplete(Boolean refreshNeeded) {
5344 setMessage(tr("Finalizing Synchronization"));
5346 syncRunning = false;
5347 syncRunner.syncNeeded = false;
5348 synchronizeAnimationTimer.stop();
5349 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5351 if (currentNote == null) {
5352 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5354 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5355 noteIndexUpdated(false);
5356 noteTableView.selectionModel().blockSignals(true);
5357 scrollToGuid(currentNoteGuid);
5358 noteTableView.selectionModel().blockSignals(false);
5359 refreshEvernoteNote(false);
5360 scrollToGuid(currentNoteGuid);
5362 if (!syncRunner.error)
5363 setMessage(tr("Synchronization Complete"));
5365 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5366 logger.log(logger.MEDIUM, "Sync complete.");
5368 public void saveUploadAmount(long t) {
5369 Global.saveUploadAmount(t);
5371 public void saveUserInformation(User user) {
5372 Global.saveUserInformation(user);
5374 public void saveEvernoteUpdateCount(int i) {
5375 Global.saveEvernoteUpdateCount(i);
5377 public void refreshLists() {
5378 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5380 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5381 tagIndexUpdated(true);
5382 notebookIndexUpdated();
5383 savedSearchIndexUpdated();
5384 listManager.loadNotesIndex();
5386 noteTableView.selectionModel().blockSignals(true);
5387 noteIndexUpdated(true);
5388 noteTableView.selectionModel().blockSignals(false);
5389 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5393 @SuppressWarnings("unused")
5394 private void authTimer() {
5395 Calendar cal = Calendar.getInstance();
5397 // If we are not connected let's get out of here
5398 if (!Global.isConnected)
5401 // If this is the first time through, then we need to set this
5402 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5403 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5405 // long now = new Date().getTime();
5406 // if (now > Global.authRefreshTime && Global.isConnected) {
5407 syncRunner.authRefreshNeeded = true;
5411 @SuppressWarnings("unused")
5412 private void authRefreshComplete(boolean goodSync) {
5413 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5414 Global.isConnected = syncRunner.isConnected;
5416 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5417 authTimer.start(1000*60*15);
5418 logger.log(logger.LOW, "Authentication token has been renewed");
5419 // setMessage("Authentication token has been renewed.");
5421 authTimer.start(1000*60*5);
5422 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5423 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5425 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5429 @SuppressWarnings("unused")
5430 private synchronized void indexTimer() {
5431 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5434 if (!indexDisabled && indexRunner.idle) {
5435 thumbnailRunner.interrupt = true;
5436 indexRunner.addWork("SCAN");
5438 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5441 @SuppressWarnings("unused")
5442 private void indexStarted() {
5443 setMessage(tr("Indexing notes"));
5445 @SuppressWarnings("unused")
5446 private void indexComplete() {
5447 setMessage(tr("Index complete"));
5449 @SuppressWarnings("unused")
5450 private synchronized void toggleNoteIndexing() {
5451 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5452 indexDisabled = !indexDisabled;
5454 setMessage(tr("Indexing is now enabled."));
5456 setMessage(tr("Indexing is now disabled."));
5457 menuBar.disableIndexing.setChecked(indexDisabled);
5458 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5461 @SuppressWarnings("unused")
5462 private void threadMonitorCheck() {
5467 alive = listManager.threadCheck(Global.tagCounterThreadId);
5470 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5471 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5472 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5473 disableTagThreadCheck = true;
5478 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5480 notebookThreadDeadCount++;
5481 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5482 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5483 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5484 disableNotebookThreadCheck=true;
5487 notebookThreadDeadCount=0;
5489 alive = listManager.threadCheck(Global.trashCounterThreadId);
5492 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5493 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5494 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5495 disableTrashThreadCheck = true;
5500 alive = listManager.threadCheck(Global.saveThreadId);
5502 saveThreadDeadCount++;
5503 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5504 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5505 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5506 disableSaveThreadCheck = true;
5509 saveThreadDeadCount=0;
5511 if (!syncThread.isAlive()) {
5512 syncThreadDeadCount++;
5513 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5514 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5515 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5516 disableSyncThreadCheck = true;
5519 syncThreadDeadCount=0;
5521 if (!indexThread.isAlive()) {
5522 indexThreadDeadCount++;
5523 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5524 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5525 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5526 disableIndexThreadCheck = true;
5529 indexThreadDeadCount=0;
5534 private void thumbnailTimer() {
5535 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5536 thumbnailRunner.addWork("SCAN");
5540 //**************************************************
5541 //* Backup & Restore
5542 //**************************************************
5543 @SuppressWarnings("unused")
5544 private void databaseBackup() {
5545 QFileDialog fd = new QFileDialog(this);
5546 fd.setFileMode(FileMode.AnyFile);
5547 fd.setConfirmOverwrite(true);
5548 fd.setWindowTitle(tr("Backup Database"));
5549 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5550 fd.setAcceptMode(AcceptMode.AcceptSave);
5551 if (saveLastPath == null || saveLastPath.equals(""))
5552 fd.setDirectory(System.getProperty("user.home"));
5554 fd.setDirectory(saveLastPath);
5555 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5561 saveLastPath = fd.selectedFiles().get(0);
5562 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5563 setMessage(tr("Backing up database"));
5565 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5567 ExportData noteWriter = new ExportData(conn, true);
5568 String fileName = fd.selectedFiles().get(0);
5570 if (!fileName.endsWith(".nnex"))
5571 fileName = fileName +".nnex";
5572 noteWriter.exportData(fileName);
5573 setMessage(tr("Database backup completed."));
5578 @SuppressWarnings("unused")
5579 private void databaseRestore() {
5580 if (QMessageBox.question(this, tr("Confirmation"),
5581 tr("This is used to restore a database from backups.\n" +
5582 "It is HIGHLY recommened that this only be used to populate\n" +
5583 "an empty database. Restoring into a database that\n already has data" +
5584 " can cause problems.\n\nAre you sure you want to continue?"),
5585 QMessageBox.StandardButton.Yes,
5586 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5591 QFileDialog fd = new QFileDialog(this);
5592 fd.setFileMode(FileMode.ExistingFile);
5593 fd.setConfirmOverwrite(true);
5594 fd.setWindowTitle(tr("Restore Database"));
5595 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5596 fd.setAcceptMode(AcceptMode.AcceptOpen);
5597 if (saveLastPath == null || saveLastPath.equals(""))
5598 fd.setDirectory(System.getProperty("user.home"));
5600 fd.setDirectory(saveLastPath);
5601 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5607 saveLastPath = fd.selectedFiles().get(0);
5608 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5610 setMessage(tr("Restoring database"));
5611 ImportData noteReader = new ImportData(conn, true);
5612 noteReader.importData(fd.selectedFiles().get(0));
5614 if (noteReader.lastError != 0) {
5615 setMessage(noteReader.getErrorMessage());
5616 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5621 listManager.loadNoteTitleColors();
5623 refreshEvernoteNote(true);
5624 setMessage(tr("Database has been restored."));
5627 @SuppressWarnings("unused")
5628 private void exportNotes() {
5629 QFileDialog fd = new QFileDialog(this);
5630 fd.setFileMode(FileMode.AnyFile);
5631 fd.setConfirmOverwrite(true);
5632 fd.setWindowTitle(tr("Backup Database"));
5633 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5634 fd.setAcceptMode(AcceptMode.AcceptSave);
5635 fd.setDirectory(System.getProperty("user.home"));
5636 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5642 setMessage(tr("Exporting Notes"));
5645 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5646 selectedNoteGUIDs.add(currentNoteGuid);
5648 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5649 String fileName = fd.selectedFiles().get(0);
5651 if (!fileName.endsWith(".nnex"))
5652 fileName = fileName +".nnex";
5653 noteWriter.exportData(fileName);
5654 setMessage(tr("Export completed."));
5660 @SuppressWarnings("unused")
5661 private void importNotes() {
5662 QFileDialog fd = new QFileDialog(this);
5663 fd.setFileMode(FileMode.ExistingFile);
5664 fd.setConfirmOverwrite(true);
5665 fd.setWindowTitle(tr("Import Notes"));
5666 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5667 fd.setAcceptMode(AcceptMode.AcceptOpen);
5668 if (saveLastPath == null || saveLastPath.equals(""))
5669 fd.setDirectory(System.getProperty("user.home"));
5671 fd.setDirectory(saveLastPath);
5672 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5678 setMessage("Importing Notes");
5681 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5682 selectedNoteGUIDs.add(currentNoteGuid);
5684 ImportData noteReader = new ImportData(conn, false);
5685 String fileName = fd.selectedFiles().get(0);
5686 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5688 if (!fileName.endsWith(".nnex"))
5689 fileName = fileName +".nnex";
5690 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5691 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5693 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5695 noteReader.importData(fileName);
5697 if (noteReader.lastError != 0) {
5698 setMessage(noteReader.getErrorMessage());
5699 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5704 listManager.loadNoteTitleColors();
5706 refreshEvernoteNote(false);
5707 setMessage(tr("Notes have been imported."));
5710 setMessage("Import completed.");
5717 //**************************************************
5718 //* Duplicate a note
5719 //**************************************************
5720 @SuppressWarnings("unused")
5721 private void duplicateNote() {
5723 duplicateNote(currentNoteGuid);
5728 //**************************************************
5730 //**************************************************
5731 public void setupFolderImports() {
5732 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5734 if (importKeepWatcher == null)
5735 importKeepWatcher = new QFileSystemWatcher();
5736 if (importDeleteWatcher == null) {
5737 importDeleteWatcher = new QFileSystemWatcher();
5738 for (int i=0; i<records.size(); i++) {
5739 if (!records.get(i).keep)
5740 folderImportDelete(records.get(i).folder);
5746 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5747 for (int i=0; i<records.size(); i++) {
5748 if (records.get(i).keep)
5749 importKeepWatcher.addPath(records.get(i).folder);
5751 importDeleteWatcher.addPath(records.get(i).folder);
5754 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5755 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5757 // Look at the files already there so we don't import them again if a new file is created
5758 if (importedFiles == null) {
5759 importedFiles = new ArrayList<String>();
5760 for (int j=0; j<records.size(); j++) {
5761 QDir dir = new QDir(records.get(j).folder);
5762 List<QFileInfo> list = dir.entryInfoList();
5763 for (int k=0; k<list.size(); k++) {
5764 if (list.get(k).isFile())
5765 importedFiles.add(list.get(k).absoluteFilePath());
5770 public void folderImport() {
5771 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5772 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5774 if (!dialog.okClicked())
5777 // We have some sort of update.
5778 if (importKeepWatcher.directories().size() > 0)
5779 importKeepWatcher.removePaths(importKeepWatcher.directories());
5780 if (importDeleteWatcher.directories().size() > 0)
5781 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5783 conn.getWatchFolderTable().expungeAll();
5784 // Start building from the table
5785 for (int i=0; i<dialog.table.rowCount(); i++) {
5786 QTableWidgetItem item = dialog.table.item(i, 0);
5787 String dir = item.text();
5788 item = dialog.table.item(i, 1);
5789 String notebook = item.text();
5790 item = dialog.table.item(i, 2);
5792 if (item.text().equalsIgnoreCase("Keep"))
5797 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5798 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5800 setupFolderImports();
5803 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5805 String whichOS = System.getProperty("os.name");
5806 if (whichOS.contains("Windows"))
5807 dirName = dirName.replace('/','\\');
5809 FileImporter importer = new FileImporter(logger, conn);
5811 QDir dir = new QDir(dirName);
5812 List<QFileInfo> list = dir.entryInfoList();
5813 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5815 for (int i=0; i<list.size(); i++){
5817 boolean redundant = false;
5818 // Check if we've already imported this one or if it existed before
5819 for (int j=0; j<importedFiles.size(); j++) {
5820 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5825 importer.setFileInfo(list.get(i));
5826 importer.setFileName(list.get(i).absoluteFilePath());
5829 if (list.get(i).isFile() && importer.isValidType()) {
5831 if (!importer.importFile()) {
5832 // If we can't get to the file, it is probably locked. We'll try again later.
5833 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5834 importFilesKeep.add(list.get(i).absoluteFilePath());
5838 Note newNote = importer.getNote();
5839 newNote.setNotebookGuid(notebook);
5840 newNote.setTitle(dir.at(i));
5841 listManager.addNote(newNote);
5842 conn.getNoteTable().addNote(newNote, true);
5843 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5844 noteTableView.insertRow(newNote, true, -1);
5845 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5846 listManager.countNotebookResults(listManager.getNoteIndex());
5847 importedFiles.add(list.get(i).absoluteFilePath());
5855 public void folderImportDelete(String dirName) {
5857 String whichOS = System.getProperty("os.name");
5858 if (whichOS.contains("Windows"))
5859 dirName = dirName.replace('/','\\');
5861 FileImporter importer = new FileImporter(logger, conn);
5862 QDir dir = new QDir(dirName);
5863 List<QFileInfo> list = dir.entryInfoList();
5864 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5866 for (int i=0; i<list.size(); i++){
5867 importer.setFileInfo(list.get(i));
5868 importer.setFileName(list.get(i).absoluteFilePath());
5870 if (list.get(i).isFile() && importer.isValidType()) {
5872 if (!importer.importFile()) {
5873 // If we can't get to the file, it is probably locked. We'll try again later.
5874 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5875 importFilesKeep.add(list.get(i).absoluteFilePath());
5879 Note newNote = importer.getNote();
5880 newNote.setNotebookGuid(notebook);
5881 newNote.setTitle(dir.at(i));
5882 listManager.addNote(newNote);
5883 conn.getNoteTable().addNote(newNote, true);
5884 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5885 noteTableView.insertRow(newNote, true, -1);
5886 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5887 listManager.countNotebookResults(listManager.getNoteIndex());
5888 dir.remove(dir.at(i));
5894 //**************************************************
5896 //**************************************************
5897 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5898 logger.log(logger.HIGH, "Entering exernalFileEdited");
5900 // Strip URL prefix and base dir path
5901 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5902 String name = fileName.replace(dPath, "");
5903 int pos = name.lastIndexOf('.');
5906 guid = guid.substring(0,pos);
5908 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5910 guid = name.substring(0, pos);
5913 QFile file = new QFile(fileName);
5914 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5915 // If we can't get to the file, it is probably locked. We'll try again later.
5916 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5917 externalFiles.add(fileName);
5920 QByteArray binData = file.readAll();
5922 if (binData.size() == 0) {
5923 // If we can't get to the file, it is probably locked. We'll try again later.
5924 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5925 externalFiles.add(fileName);
5929 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5931 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5932 if (r == null || r.getData() == null || r.getData().getBody() == null)
5934 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5935 MessageDigest md = MessageDigest.getInstance("MD5");
5936 md.update(binData.toByteArray());
5937 byte[] hash = md.digest();
5938 String newHash = Global.byteArrayToHexString(hash);
5939 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5940 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5942 if (externalWindows.containsKey(r.getNoteGuid())) {
5943 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5944 r.getGuid(), oldHash, newHash);
5946 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5947 Data data = r.getData();
5948 data.setBody(binData.toByteArray());
5949 data.setBodyHash(hash);
5950 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5952 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5954 if (r.getNoteGuid().equals(currentNoteGuid)) {
5955 QWebSettings.setMaximumPagesInCache(0);
5956 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5957 refreshEvernoteNote(true);
5958 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5961 if (externalWindows.containsKey(r.getNoteGuid())) {
5962 QWebSettings.setMaximumPagesInCache(0);
5963 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5964 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5968 logger.log(logger.HIGH, "Exiting externalFielEdited");
5970 // This is a timer event that tries to save any external files that were edited. This
5971 // is only needed if we couldn't save a file earlier.
5972 public void externalFileEditedSaver() {
5973 for (int i=externalFiles.size()-1; i>=0; i--) {
5975 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5976 externalFileEdited(externalFiles.get(i));
5977 externalFiles.remove(i);
5978 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5980 for (int i=0; i<importFilesKeep.size(); i++) {
5982 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5983 folderImportKeep(importFilesKeep.get(i));
5984 importFilesKeep.remove(i);
5985 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5987 for (int i=0; i<importFilesDelete.size(); i++) {
5988 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5989 folderImportDelete(importFilesDelete.get(i));
5990 importFilesDelete.remove(i);
5997 // If an attachment on the current note was edited, we need to update the current notes's hash
5998 // Update a note content's hash. This happens if a resource is edited outside of NN
5999 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6000 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6002 for (;position>-1;) {
6003 endPos = browser.getContent().indexOf(">", position+1);
6004 String oldSegment = browser.getContent().substring(position,endPos);
6005 int hashPos = oldSegment.indexOf("hash=\"");
6006 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6007 String hash = oldSegment.substring(hashPos+6, hashEnd);
6008 if (hash.equalsIgnoreCase(oldHash)) {
6009 String newSegment = oldSegment.replace(oldHash, newHash);
6010 String content = browser.getContent().substring(0,position) +
6012 browser.getContent().substring(endPos);
6013 browser.getBrowser().setContent(new QByteArray(content));;
6016 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6021 //*************************************************
6022 //* Minimize to tray
6023 //*************************************************
6025 public void changeEvent(QEvent e) {
6026 if (e.type() == QEvent.Type.WindowStateChange) {
6027 if (isMinimized() && Global.showTrayIcon()) {
6029 QTimer.singleShot(10, this, "hide()");
6033 windowMaximized = true;
6035 windowMaximized = false;
6039 //*************************************************
6040 //* Check database userid & passwords
6041 //*************************************************
6042 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6043 Connection connection;
6046 Class.forName("org.h2.Driver");
6047 } catch (ClassNotFoundException e1) {
6048 e1.printStackTrace();
6053 String passwordString = null;
6054 if (cypherPassword==null || cypherPassword.trim().equals(""))
6055 passwordString = userPassword;
6057 passwordString = cypherPassword+" "+userPassword;
6058 connection = DriverManager.getConnection(url,userid,passwordString);
6059 } catch (SQLException e) {
6064 } catch (SQLException e) {
6065 e.printStackTrace();
6071 //*************************************************
6072 // Block the program. This is used for things
6073 // like async web calls.
6074 //*************************************************
6075 @SuppressWarnings("unused")
6076 private void blockApplication(Long time) {
6077 Calendar currentTime = new GregorianCalendar();
6079 blockTime = new Long(currentTime.getTimeInMillis())+time;
6081 for (;currentTime.getTimeInMillis()>blockTime;) {
6084 } catch (InterruptedException e) {
6085 e.printStackTrace();
6091 @SuppressWarnings("unused")
6092 private void unblockApplication() {