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 QTimer blockTimer;
336 BrowserWindow blockingWindow;
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 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1148 browser.unblockApplication.connect(this, "unblockApplication()");
1149 if (master) browser.focusLost.connect(this, "saveNote()");
1150 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1153 //**************************************************
1155 //**************************************************
1156 private void setupShortcut(QShortcut action, String text) {
1157 if (!Global.shortcutKeys.containsAction(text))
1159 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1162 //***************************************************************
1163 //***************************************************************
1164 //* Settings and look & feel
1165 //***************************************************************
1166 //***************************************************************
1167 @SuppressWarnings("unused")
1168 private void settings() {
1169 logger.log(logger.HIGH, "Entering NeverNote.settings");
1170 saveNoteColumnPositions();
1171 saveNoteIndexWidth();
1173 ConfigDialog settings = new ConfigDialog(this);
1174 String dateFormat = Global.getDateFormat();
1175 String timeFormat = Global.getTimeFormat();
1177 indexTime = 1000*Global.getIndexThreadSleepInterval();
1178 indexTimer.start(indexTime); // reset indexing timer
1181 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1182 if (Global.showTrayIcon())
1187 if (menuBar.showEditorBar.isChecked())
1188 showEditorButtons(browserWindow);
1190 // Reset the save timer
1191 if (Global.getAutoSaveInterval() > 0)
1192 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1196 // This is a hack to force a reload of the index in case the date or time changed.
1197 // if (!dateFormat.equals(Global.getDateFormat()) ||
1198 // !timeFormat.equals(Global.getTimeFormat())) {
1200 readOnlyCache.clear();
1201 inkNoteCache.clear();
1202 noteIndexUpdated(true);
1205 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1207 // Restore things to the way they were
1208 private void restoreWindowState(boolean mainWindow) {
1209 // We need to name things or this doesn't work.
1210 setObjectName("NeverNote");
1211 restoreState(Global.restoreState(objectName()));
1212 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1213 browserIndexSplitter.setObjectName("browserIndexSplitter");
1214 leftSplitter1.setObjectName("leftSplitter1");
1216 // Restore the actual positions.
1218 restoreGeometry(Global.restoreGeometry(objectName()));
1219 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1220 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1221 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1224 // Save window positions for the next start
1225 private void saveWindowState() {
1226 Global.saveGeometry(objectName(), saveGeometry());
1227 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1228 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1229 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1230 Global.saveState(objectName(), saveState());
1232 // Load the style sheet
1233 private void loadStyleSheet() {
1234 String styleSheetName = "default.qss";
1235 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1236 styleSheetName = "default-cleanlooks.qss";
1237 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1238 QFile file = new QFile(fileName);
1240 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1241 if (!file.exists()) {
1242 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1243 file = new QFile(fileName);
1245 file.open(OpenModeFlag.ReadOnly);
1246 String styleSheet = file.readAll().toString();
1248 setStyleSheet(styleSheet);
1250 // Save column positions for the next time
1251 private void saveNoteColumnPositions() {
1252 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1253 Global.setColumnPosition("noteTableCreationPosition", position);
1254 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1255 Global.setColumnPosition("noteTableTagPosition", position);
1256 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1257 Global.setColumnPosition("noteTableNotebookPosition", position);
1258 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1259 Global.setColumnPosition("noteTableChangedPosition", position);
1260 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1261 Global.setColumnPosition("noteTableAuthorPosition", position);
1262 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1263 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1264 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1265 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1266 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1267 Global.setColumnPosition("noteTableTitlePosition", position);
1268 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1269 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1270 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1271 Global.setColumnPosition("noteTableGuidPosition", position);
1272 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1273 Global.setColumnPosition("noteTableThumbnailPosition", position);
1276 // Save column widths for the next time
1277 private void saveNoteIndexWidth() {
1279 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1280 Global.setColumnWidth("noteTableCreationPosition", width);
1281 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1282 Global.setColumnWidth("noteTableChangedPosition", width);
1283 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1284 Global.setColumnWidth("noteTableGuidPosition", width);
1285 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1286 Global.setColumnWidth("noteTableNotebookPosition", width);
1287 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1288 Global.setColumnWidth("noteTableTagPosition", width);
1289 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1290 Global.setColumnWidth("noteTableTitlePosition", width);
1291 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1292 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1293 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1294 Global.setColumnWidth("noteTableAuthorPosition", width);
1295 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1296 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1297 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1298 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1299 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1300 Global.setColumnWidth("noteTableThumbnailPosition", width);
1301 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1302 Global.setColumnWidth("noteTableGuidPosition", width);
1305 @SuppressWarnings("unused")
1306 private void toggleSearchWindow() {
1307 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1308 searchLayout.toggleSearchField();
1309 menuBar.hideSearch.setChecked(searchField.isVisible());
1310 Global.saveWindowVisible("searchField", searchField.isVisible());
1311 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1313 @SuppressWarnings("unused")
1314 private void toggleQuotaWindow() {
1315 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1316 searchLayout.toggleQuotaBar();
1317 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1318 Global.saveWindowVisible("quota", quotaBar.isVisible());
1319 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1321 @SuppressWarnings("unused")
1322 private void toggleZoomWindow() {
1323 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1324 searchLayout.toggleZoom();
1325 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1326 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1327 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1332 //***************************************************************
1333 //***************************************************************
1334 //** These functions deal with Notebook menu items
1335 //***************************************************************
1336 //***************************************************************
1337 // Setup the tree containing the user's notebooks.
1338 private void initializeNotebookTree() {
1339 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1340 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1341 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1342 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1343 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1345 // Listener when a notebook is selected
1346 private void notebookTreeSelection() {
1347 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1350 clearAttributeFilter();
1351 clearSavedSearchFilter();
1352 if (Global.mimicEvernoteInterface) {
1354 searchField.clear();
1356 menuBar.noteRestoreAction.setVisible(false);
1357 menuBar.notebookEditAction.setEnabled(true);
1358 menuBar.notebookDeleteAction.setEnabled(true);
1359 menuBar.notebookPublishAction.setEnabled(true);
1360 menuBar.notebookShareAction.setEnabled(true);
1361 menuBar.notebookIconAction.setEnabled(true);
1362 menuBar.notebookStackAction.setEnabled(true);
1363 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1364 selectedNotebookGUIDs.clear();
1366 String stackName = "";
1367 if (selections.size() > 0) {
1368 guid = (selections.get(0).text(2));
1369 stackName = selections.get(0).text(0);
1371 if (!Global.mimicEvernoteInterface) {
1372 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1373 if (selections.size()==0) {
1374 selectedNotebookGUIDs.clear();
1375 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1376 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1378 menuBar.notebookEditAction.setEnabled(false);
1379 menuBar.notebookDeleteAction.setEnabled(false);
1380 menuBar.notebookStackAction.setEnabled(false);
1381 menuBar.notebookIconAction.setEnabled(false);
1384 if (!guid.equals("") && !guid.equals("STACK")) {
1385 selectedNotebookGUIDs.add(guid);
1386 menuBar.notebookIconAction.setEnabled(true);
1388 menuBar.notebookIconAction.setEnabled(true);
1389 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1390 Notebook book = listManager.getNotebookIndex().get(j);
1391 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1392 selectedNotebookGUIDs.add(book.getGuid());
1395 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1396 listManager.loadNotesIndex();
1397 noteIndexUpdated(false);
1398 refreshEvernoteNote(true);
1399 listManager.refreshCounters = true;
1400 listManager.refreshCounters();
1401 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1404 private void clearNotebookFilter() {
1405 notebookTree.blockSignals(true);
1406 notebookTree.clearSelection();
1407 menuBar.noteRestoreAction.setVisible(false);
1408 menuBar.notebookEditAction.setEnabled(false);
1409 menuBar.notebookDeleteAction.setEnabled(false);
1410 selectedNotebookGUIDs.clear();
1411 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1412 notebookTree.blockSignals(false);
1414 // Triggered when the notebook DB has been updated
1415 private void notebookIndexUpdated() {
1416 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1418 // Get the possible icons
1419 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1420 notebookTree.setIcons(icons);
1422 if (selectedNotebookGUIDs == null)
1423 selectedNotebookGUIDs = new ArrayList<String>();
1424 List<Notebook> books = conn.getNotebookTable().getAll();
1425 for (int i=books.size()-1; i>=0; i--) {
1426 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1427 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1429 j=listManager.getArchiveNotebookIndex().size();
1435 listManager.countNotebookResults(listManager.getNoteIndex());
1436 notebookTree.blockSignals(true);
1437 notebookTree.load(books, listManager.getLocalNotebooks());
1438 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1439 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1441 selectedNotebookGUIDs.remove(i);
1443 listManager.refreshCounters = true;
1444 listManager.refreshCounters();
1445 notebookTree.blockSignals(false);
1447 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1449 // Show/Hide note information
1450 @SuppressWarnings("unused")
1451 private void toggleNotebookWindow() {
1452 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1453 searchLayout.toggleNotebook();
1454 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1455 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1456 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1458 // Add a new notebook
1459 @SuppressWarnings("unused")
1460 private void addNotebook() {
1461 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1462 NotebookEdit edit = new NotebookEdit();
1463 edit.setNotebooks(listManager.getNotebookIndex());
1466 if (!edit.okPressed())
1469 Calendar currentTime = new GregorianCalendar();
1470 Long l = new Long(currentTime.getTimeInMillis());
1471 String randint = new String(Long.toString(l));
1473 Notebook newBook = new Notebook();
1474 newBook.setUpdateSequenceNum(0);
1475 newBook.setGuid(randint);
1476 newBook.setName(edit.getNotebook());
1477 newBook.setServiceCreated(new Date().getTime());
1478 newBook.setServiceUpdated(new Date().getTime());
1479 newBook.setDefaultNotebook(false);
1480 newBook.setPublished(false);
1482 listManager.getNotebookIndex().add(newBook);
1484 listManager.getLocalNotebooks().add(newBook.getGuid());
1485 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1486 notebookIndexUpdated();
1487 listManager.countNotebookResults(listManager.getNoteIndex());
1488 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1489 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1491 // Edit an existing notebook
1492 @SuppressWarnings("unused")
1493 private void stackNotebook() {
1494 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1495 StackNotebook edit = new StackNotebook();
1497 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1498 QTreeWidgetItem currentSelection;
1499 for (int i=0; i<selections.size(); i++) {
1500 currentSelection = selections.get(0);
1501 String guid = currentSelection.text(2);
1502 if (guid.equalsIgnoreCase("")) {
1503 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1506 if (guid.equalsIgnoreCase("STACK")) {
1507 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1512 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1517 if (!edit.okPressed())
1520 String stack = edit.getStackName();
1522 for (int i=0; i<selections.size(); i++) {
1523 currentSelection = selections.get(i);
1524 String guid = currentSelection.text(2);
1525 listManager.updateNotebookStack(guid, stack);
1527 notebookIndexUpdated();
1528 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1530 // Edit an existing notebook
1531 @SuppressWarnings("unused")
1532 private void editNotebook() {
1533 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1534 NotebookEdit edit = new NotebookEdit();
1536 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1537 QTreeWidgetItem currentSelection;
1538 currentSelection = selections.get(0);
1539 edit.setNotebook(currentSelection.text(0));
1541 String guid = currentSelection.text(2);
1542 if (!guid.equalsIgnoreCase("STACK")) {
1543 edit.setTitle(tr("Edit Notebook"));
1544 edit.setNotebooks(listManager.getNotebookIndex());
1545 edit.setLocalCheckboxEnabled(false);
1546 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1547 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1548 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1549 i=listManager.getNotebookIndex().size();
1553 edit.setTitle(tr("Edit Stack"));
1554 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1555 edit.hideLocalCheckbox();
1556 edit.hideDefaultCheckbox();
1561 if (!edit.okPressed())
1565 if (guid.equalsIgnoreCase("STACK")) {
1566 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1567 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1568 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1569 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1570 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1572 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1573 currentSelection.setText(0, edit.getNotebook());
1577 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1578 currentSelection.setText(0, edit.getNotebook());
1580 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1581 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1582 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1583 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1584 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1585 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1586 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1587 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1589 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1590 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1591 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1592 linkedNotebook.setShareName(edit.getNotebook());
1593 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1595 i=listManager.getNotebookIndex().size();
1599 // Build a list of non-closed notebooks
1600 List<Notebook> nbooks = new ArrayList<Notebook>();
1601 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1602 boolean found=false;
1603 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1604 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1608 nbooks.add(listManager.getNotebookIndex().get(i));
1612 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1613 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1614 browserWindow.setNotebookList(filteredBooks);
1615 Iterator<String> set = externalWindows.keySet().iterator();
1616 while(set.hasNext())
1617 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1618 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1620 // Publish a notebook
1621 @SuppressWarnings("unused")
1622 private void publishNotebook() {
1623 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1624 QTreeWidgetItem currentSelection;
1625 currentSelection = selections.get(0);
1626 String guid = currentSelection.text(2);
1628 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1633 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1634 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1635 n = listManager.getNotebookIndex().get(i);
1637 i = listManager.getNotebookIndex().size();
1643 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1646 if (!publish.okClicked())
1649 Publishing p = publish.getPublishing();
1650 boolean isPublished = !publish.isStopPressed();
1651 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1652 n.setPublished(isPublished);
1654 listManager.getNotebookIndex().set(position, n);
1655 notebookIndexUpdated();
1657 // Publish a notebook
1658 @SuppressWarnings("unused")
1659 private void shareNotebook() {
1660 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1661 QTreeWidgetItem currentSelection;
1662 currentSelection = selections.get(0);
1663 String guid = currentSelection.text(2);
1665 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1669 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1670 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1671 n = listManager.getNotebookIndex().get(i);
1672 i = listManager.getNotebookIndex().size();
1676 String authToken = null;
1677 if (syncRunner.isConnected)
1678 authToken = syncRunner.authToken;
1679 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1684 // Delete an existing notebook
1685 @SuppressWarnings("unused")
1686 private void deleteNotebook() {
1687 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1688 boolean stacksFound = false;
1689 boolean notebooksFound = false;
1690 boolean assigned = false;
1691 // Check if any notes have this notebook
1692 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1693 for (int i=0; i<selections.size(); i++) {
1694 QTreeWidgetItem currentSelection;
1695 currentSelection = selections.get(i);
1696 String guid = currentSelection.text(2);
1697 if (!guid.equalsIgnoreCase("STACK")) {
1698 notebooksFound = true;
1699 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1700 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1701 if (noteGuid.equals(guid)) {
1703 j=listManager.getNoteIndex().size();
1704 i=selections.size();
1712 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1713 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1717 if (conn.getNotebookTable().getAll().size() == 1) {
1718 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1722 // If all notebooks are clear, verify the delete
1723 String msg1 = new String(tr("Delete selected notebooks?"));
1724 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1725 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1726 " not deleted unless selected?"));
1728 if (stacksFound && notebooksFound)
1730 if (!stacksFound && notebooksFound)
1732 if (stacksFound && !notebooksFound)
1734 if (QMessageBox.question(this, tr("Confirmation"), msg,
1735 QMessageBox.StandardButton.Yes,
1736 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1740 // If confirmed, delete the notebook
1741 for (int i=selections.size()-1; i>=0; i--) {
1742 QTreeWidgetItem currentSelection;
1743 currentSelection = selections.get(i);
1744 String guid = currentSelection.text(2);
1745 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1746 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1747 listManager.renameStack(currentSelection.text(0), "");
1749 conn.getNotebookTable().expungeNotebook(guid, true);
1750 listManager.deleteNotebook(guid);
1754 notebookIndexUpdated();
1755 // notebookTreeSelection();
1756 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1757 // listManager.countNotebookResults(listManager.getNoteIndex());
1758 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1760 // A note's notebook has been updated
1761 @SuppressWarnings("unused")
1762 private void updateNoteNotebook(String guid, String notebookGuid) {
1764 // Update the list manager
1765 listManager.updateNoteNotebook(guid, notebookGuid);
1766 listManager.countNotebookResults(listManager.getNoteIndex());
1767 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1769 // Find the name of the notebook
1770 String notebookName = null;
1771 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1772 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1773 notebookName = listManager.getNotebookIndex().get(i).getName();
1778 // If we found the name, update the browser window
1779 if (notebookName != null) {
1780 updateListNoteNotebook(guid, notebookName);
1781 if (guid.equals(currentNoteGuid)) {
1782 int pos = browserWindow.notebookBox.findText(notebookName);
1784 browserWindow.notebookBox.setCurrentIndex(pos);
1788 // If we're dealing with the current note, then we need to be sure and update the notebook there
1789 if (guid.equals(currentNoteGuid)) {
1790 if (currentNote != null) {
1791 currentNote.setNotebookGuid(notebookGuid);
1795 // Open/close notebooks
1796 @SuppressWarnings("unused")
1797 private void closeNotebooks() {
1798 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1800 if (!na.okClicked())
1804 listManager.getArchiveNotebookIndex().clear();
1806 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1807 String text = na.getClosedBookList().takeItem(i).text();
1808 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1809 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1810 Notebook n = listManager.getNotebookIndex().get(j);
1811 conn.getNotebookTable().setArchived(n.getGuid(),true);
1812 listManager.getArchiveNotebookIndex().add(n);
1813 j=listManager.getNotebookIndex().size();
1818 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1819 String text = na.getOpenBookList().takeItem(i).text();
1820 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1821 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1822 Notebook n = listManager.getNotebookIndex().get(j);
1823 conn.getNotebookTable().setArchived(n.getGuid(),false);
1824 j=listManager.getNotebookIndex().size();
1828 notebookTreeSelection();
1829 listManager.loadNotesIndex();
1830 notebookIndexUpdated();
1831 noteIndexUpdated(false);
1832 reloadTagTree(true);
1833 // noteIndexUpdated(false);
1835 // Build a list of non-closed notebooks
1836 List<Notebook> nbooks = new ArrayList<Notebook>();
1837 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1838 boolean found=false;
1839 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1840 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1844 nbooks.add(listManager.getNotebookIndex().get(i));
1847 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1848 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1849 browserWindow.setNotebookList(filteredBooks);
1851 // Update any external windows
1852 Iterator<String> set = externalWindows.keySet().iterator();
1853 while(set.hasNext())
1854 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1858 // Change the notebook's icon
1859 @SuppressWarnings("unused")
1860 private void setNotebookIcon() {
1861 boolean stackSelected = false;
1862 boolean allNotebookSelected = false;
1864 QTreeWidgetItem currentSelection;
1865 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1866 if (selections.size() == 0)
1869 currentSelection = selections.get(0);
1870 String guid = currentSelection.text(2);
1871 if (guid.equalsIgnoreCase(""))
1872 allNotebookSelected = true;
1873 if (guid.equalsIgnoreCase("STACK"))
1874 stackSelected = true;
1876 QIcon currentIcon = currentSelection.icon(0);
1880 if (!stackSelected && !allNotebookSelected) {
1881 icon = conn.getNotebookTable().getIcon(guid);
1883 dialog = new SetIcon(currentIcon, saveLastPath);
1884 dialog.setUseDefaultIcon(true);
1886 dialog = new SetIcon(icon, saveLastPath);
1887 dialog.setUseDefaultIcon(false);
1890 if (stackSelected) {
1891 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1893 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1896 dialog = new SetIcon(currentIcon, saveLastPath);
1897 dialog.setUseDefaultIcon(true);
1899 dialog = new SetIcon(icon, saveLastPath);
1900 dialog.setUseDefaultIcon(false);
1904 if (dialog.okPressed()) {
1905 saveLastPath = dialog.getPath();
1907 QIcon newIcon = dialog.getIcon();
1908 if (stackSelected) {
1909 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1910 if (newIcon == null) {
1911 newIcon = new QIcon(iconPath+"books2.png");
1913 currentSelection.setIcon(0,newIcon);
1916 if (allNotebookSelected) {
1917 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1918 if (newIcon == null) {
1919 newIcon = new QIcon(iconPath+"notebook-green.png");
1921 currentSelection.setIcon(0,newIcon);
1924 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1925 if (newIcon == null) {
1926 boolean isPublished = false;;
1927 boolean found = false;
1928 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1929 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1930 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1934 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1936 currentSelection.setIcon(0, newIcon);
1942 //***************************************************************
1943 //***************************************************************
1944 //** These functions deal with Tag menu items
1945 //***************************************************************
1946 //***************************************************************
1947 // Add a new notebook
1948 @SuppressWarnings("unused")
1949 private void addTag() {
1950 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1951 TagEdit edit = new TagEdit();
1952 edit.setTagList(listManager.getTagIndex());
1954 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1955 QTreeWidgetItem currentSelection = null;
1956 if (selections.size() > 0) {
1957 currentSelection = selections.get(0);
1958 edit.setParentTag(currentSelection.text(0));
1963 if (!edit.okPressed())
1966 Calendar currentTime = new GregorianCalendar();
1967 Long l = new Long(currentTime.getTimeInMillis());
1968 String randint = new String(Long.toString(l));
1970 Tag newTag = new Tag();
1971 newTag.setUpdateSequenceNum(0);
1972 newTag.setGuid(randint);
1973 newTag.setName(edit.getTag());
1974 if (edit.getParentTag().isChecked()) {
1975 newTag.setParentGuid(currentSelection.text(2));
1976 newTag.setParentGuidIsSet(true);
1977 currentSelection.setExpanded(true);
1979 conn.getTagTable().addTag(newTag, true);
1980 listManager.getTagIndex().add(newTag);
1981 reloadTagTree(true);
1983 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1985 @SuppressWarnings("unused")
1986 private void reloadTagTree() {
1987 reloadTagTree(false);
1989 private void reloadTagTree(boolean reload) {
1990 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1991 tagIndexUpdated(reload);
1992 boolean filter = false;
1994 listManager.countTagResults(listManager.getNoteIndex());
1995 if (notebookTree.selectedItems().size() > 0
1996 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1998 if (tagTree.selectedItems().size() > 0)
2000 tagTree.showAllTags(!filter);
2001 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2003 // Edit an existing tag
2004 @SuppressWarnings("unused")
2005 private void editTag() {
2006 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2007 TagEdit edit = new TagEdit();
2008 edit.setTitle("Edit Tag");
2009 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2010 QTreeWidgetItem currentSelection;
2011 currentSelection = selections.get(0);
2012 edit.setTag(currentSelection.text(0));
2013 edit.setTagList(listManager.getTagIndex());
2016 if (!edit.okPressed())
2019 String guid = currentSelection.text(2);
2020 currentSelection.setText(0,edit.getTag());
2022 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2023 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2024 listManager.getTagIndex().get(i).setName(edit.getTag());
2025 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2026 updateListTagName(guid);
2027 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2028 browserWindow.setTag(getTagNamesForNote(currentNote));
2029 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2033 browserWindow.setTag(getTagNamesForNote(currentNote));
2034 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2036 // Delete an existing tag
2037 @SuppressWarnings("unused")
2038 private void deleteTag() {
2039 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2041 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2042 QMessageBox.StandardButton.Yes,
2043 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2047 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2048 for (int i=selections.size()-1; i>=0; i--) {
2049 QTreeWidgetItem currentSelection;
2050 currentSelection = selections.get(i);
2051 removeTagItem(currentSelection.text(2));
2053 tagIndexUpdated(true);
2055 listManager.countTagResults(listManager.getNoteIndex());
2056 // tagTree.updateCounts(listManager.getTagCounter());
2057 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2059 // Remove a tag tree item. Go recursively down & remove the children too
2060 private void removeTagItem(String guid) {
2061 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2062 String parent = listManager.getTagIndex().get(j).getParentGuid();
2063 if (parent != null && parent.equals(guid)) {
2064 //Remove this tag's children
2065 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2068 //Now, remove this tag
2069 removeListTagName(guid);
2070 conn.getTagTable().expungeTag(guid, true);
2071 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2072 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2073 listManager.getTagIndex().remove(a);
2078 // Setup the tree containing the user's tags
2079 private void initializeTagTree() {
2080 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2081 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2082 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2083 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2084 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2085 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2087 // Listener when a tag is selected
2088 private void tagTreeSelection() {
2089 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2092 clearAttributeFilter();
2093 clearSavedSearchFilter();
2095 menuBar.noteRestoreAction.setVisible(false);
2097 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2098 QTreeWidgetItem currentSelection;
2099 selectedTagGUIDs.clear();
2100 for (int i=0; i<selections.size(); i++) {
2101 currentSelection = selections.get(i);
2102 selectedTagGUIDs.add(currentSelection.text(2));
2104 if (selections.size() > 0) {
2105 menuBar.tagEditAction.setEnabled(true);
2106 menuBar.tagDeleteAction.setEnabled(true);
2107 menuBar.tagIconAction.setEnabled(true);
2110 menuBar.tagEditAction.setEnabled(false);
2111 menuBar.tagDeleteAction.setEnabled(false);
2112 menuBar.tagIconAction.setEnabled(true);
2114 if (selections.size() > 1)
2115 menuBar.tagMergeAction.setEnabled(true);
2117 menuBar.tagMergeAction.setEnabled(false);
2118 listManager.setSelectedTags(selectedTagGUIDs);
2119 listManager.loadNotesIndex();
2120 noteIndexUpdated(false);
2121 refreshEvernoteNote(true);
2122 listManager.refreshCounters = true;
2123 listManager.refreshCounters();
2124 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2126 // trigger the tag index to be refreshed
2127 @SuppressWarnings("unused")
2128 private void tagIndexUpdated() {
2129 tagIndexUpdated(true);
2131 private void tagIndexUpdated(boolean reload) {
2132 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2133 if (selectedTagGUIDs == null)
2134 selectedTagGUIDs = new ArrayList<String>();
2136 listManager.reloadTagIndex();
2138 tagTree.blockSignals(true);
2140 tagTree.setIcons(conn.getTagTable().getAllIcons());
2141 tagTree.load(listManager.getTagIndex());
2144 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2145 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2147 selectedTagGUIDs.remove(i);
2149 tagTree.blockSignals(false);
2151 browserWindow.setTag(getTagNamesForNote(currentNote));
2152 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2154 // Show/Hide note information
2155 @SuppressWarnings("unused")
2156 private void toggleTagWindow() {
2157 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2158 if (tagTree.isVisible())
2162 menuBar.hideTags.setChecked(tagTree.isVisible());
2163 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2164 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2166 // A note's tags have been updated
2167 @SuppressWarnings("unused")
2168 private void updateNoteTags(String guid, List<String> tags) {
2169 // Save any new tags. We'll need them later.
2170 List<String> newTags = new ArrayList<String>();
2171 for (int i=0; i<tags.size(); i++) {
2172 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2173 newTags.add(tags.get(i));
2176 listManager.saveNoteTags(guid, tags);
2177 listManager.countTagResults(listManager.getNoteIndex());
2178 StringBuffer names = new StringBuffer("");
2179 for (int i=0; i<tags.size(); i++) {
2180 names = names.append(tags.get(i));
2181 if (i<tags.size()-1) {
2182 names.append(Global.tagDelimeter + " ");
2185 browserWindow.setTag(names.toString());
2188 // Now, we need to add any new tags to the tag tree
2189 for (int i=0; i<newTags.size(); i++)
2190 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2192 // Get a string containing all tag names for a note
2193 private String getTagNamesForNote(Note n) {
2194 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2195 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2197 StringBuffer buffer = new StringBuffer(100);
2198 Vector<String> v = new Vector<String>();
2199 List<String> guids = n.getTagGuids();
2204 for (int i=0; i<guids.size(); i++) {
2205 v.add(listManager.getTagNameByGuid(guids.get(i)));
2207 Comparator<String> comparator = Collections.reverseOrder();
2208 Collections.sort(v,comparator);
2209 Collections.reverse(v);
2211 for (int i = 0; i<v.size(); i++) {
2213 buffer.append(", ");
2214 buffer.append(v.get(i));
2217 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2218 return buffer.toString();
2220 // Tags were added via dropping notes from the note list
2221 @SuppressWarnings("unused")
2222 private void tagsAdded(String noteGuid, String tagGuid) {
2223 String tagName = null;
2224 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2225 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2226 tagName = listManager.getTagIndex().get(i).getName();
2227 i=listManager.getTagIndex().size();
2230 if (tagName == null)
2233 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2234 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2235 List<String> tagNames = new ArrayList<String>();
2236 tagNames.add(new String(tagName));
2237 Note n = listManager.getMasterNoteIndex().get(i);
2238 for (int j=0; j<n.getTagNames().size(); j++) {
2239 tagNames.add(new String(n.getTagNames().get(j)));
2241 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2242 if (n.getGuid().equals(currentNoteGuid)) {
2243 Collections.sort(tagNames);
2244 String display = "";
2245 for (int j=0; j<tagNames.size(); j++) {
2246 display = display+tagNames.get(j);
2247 if (j+2<tagNames.size())
2248 display = display+Global.tagDelimeter+" ";
2250 browserWindow.setTag(display);
2252 i=listManager.getMasterNoteIndex().size();
2257 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2259 private void clearTagFilter() {
2260 tagTree.blockSignals(true);
2261 tagTree.clearSelection();
2262 menuBar.noteRestoreAction.setVisible(false);
2263 menuBar.tagEditAction.setEnabled(false);
2264 menuBar.tagMergeAction.setEnabled(false);
2265 menuBar.tagDeleteAction.setEnabled(false);
2266 menuBar.tagIconAction.setEnabled(false);
2267 selectedTagGUIDs.clear();
2268 listManager.setSelectedTags(selectedTagGUIDs);
2269 tagTree.blockSignals(false);
2271 // Change the icon for a tag
2272 @SuppressWarnings("unused")
2273 private void setTagIcon() {
2274 QTreeWidgetItem currentSelection;
2275 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2276 if (selections.size() == 0)
2279 currentSelection = selections.get(0);
2280 String guid = currentSelection.text(2);
2282 QIcon currentIcon = currentSelection.icon(0);
2283 QIcon icon = conn.getTagTable().getIcon(guid);
2286 dialog = new SetIcon(currentIcon, saveLastPath);
2287 dialog.setUseDefaultIcon(true);
2289 dialog = new SetIcon(icon, saveLastPath);
2290 dialog.setUseDefaultIcon(false);
2293 if (dialog.okPressed()) {
2294 saveLastPath = dialog.getPath();
2295 QIcon newIcon = dialog.getIcon();
2296 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2297 if (newIcon == null)
2298 newIcon = new QIcon(iconPath+"tag.png");
2299 currentSelection.setIcon(0, newIcon);
2304 @SuppressWarnings("unused")
2305 private void mergeTags() {
2306 List<Tag> tags = new ArrayList<Tag>();
2307 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2308 for (int i=0; i<selections.size(); i++) {
2309 Tag record = new Tag();
2310 record.setGuid(selections.get(i).text(2));
2311 record.setName(selections.get(i).text(0));
2315 TagMerge mergeDialog = new TagMerge(tags);
2317 if (!mergeDialog.okClicked())
2319 String newGuid = mergeDialog.getNewTagGuid();
2321 for (int i=0; i<tags.size(); i++) {
2322 if (!tags.get(i).getGuid().equals(newGuid)) {
2323 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2324 for (int j=0; j<noteGuids.size(); j++) {
2325 String noteGuid = noteGuids.get(j);
2326 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2327 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2328 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2332 listManager.reloadIndexes();
2335 //***************************************************************
2336 //***************************************************************
2337 //** These functions deal with Saved Search menu items
2338 //***************************************************************
2339 //***************************************************************
2340 // Add a new notebook
2341 @SuppressWarnings("unused")
2342 private void addSavedSearch() {
2343 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2344 SavedSearchEdit edit = new SavedSearchEdit();
2345 edit.setSearchList(listManager.getSavedSearchIndex());
2348 if (!edit.okPressed())
2351 Calendar currentTime = new GregorianCalendar();
2352 Long l = new Long(currentTime.getTimeInMillis());
2353 String randint = new String(Long.toString(l));
2355 SavedSearch search = new SavedSearch();
2356 search.setUpdateSequenceNum(0);
2357 search.setGuid(randint);
2358 search.setName(edit.getName());
2359 search.setQuery(edit.getQuery());
2360 search.setFormat(QueryFormat.USER);
2361 listManager.getSavedSearchIndex().add(search);
2362 conn.getSavedSearchTable().addSavedSearch(search, true);
2363 savedSearchIndexUpdated();
2364 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2366 // Edit an existing tag
2367 @SuppressWarnings("unused")
2368 private void editSavedSearch() {
2369 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2370 SavedSearchEdit edit = new SavedSearchEdit();
2371 edit.setTitle(tr("Edit Search"));
2372 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2373 QTreeWidgetItem currentSelection;
2374 currentSelection = selections.get(0);
2375 String guid = currentSelection.text(1);
2376 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2377 edit.setName(currentSelection.text(0));
2378 edit.setQuery(s.getQuery());
2379 edit.setSearchList(listManager.getSavedSearchIndex());
2382 if (!edit.okPressed())
2385 List<SavedSearch> list = listManager.getSavedSearchIndex();
2386 SavedSearch search = null;
2387 boolean found = false;
2388 for (int i=0; i<list.size(); i++) {
2389 search = list.get(i);
2390 if (search.getGuid().equals(guid)) {
2397 search.setName(edit.getName());
2398 search.setQuery(edit.getQuery());
2399 conn.getSavedSearchTable().updateSavedSearch(search, true);
2400 savedSearchIndexUpdated();
2401 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2403 // Delete an existing tag
2404 @SuppressWarnings("unused")
2405 private void deleteSavedSearch() {
2406 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2408 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2409 QMessageBox.StandardButton.Yes,
2410 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2414 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2415 for (int i=selections.size()-1; i>=0; i--) {
2416 QTreeWidgetItem currentSelection;
2417 currentSelection = selections.get(i);
2418 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2419 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2420 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2421 listManager.getSavedSearchIndex().remove(j);
2422 j=listManager.getSavedSearchIndex().size()+1;
2425 selections.remove(i);
2427 savedSearchIndexUpdated();
2428 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2430 // Setup the tree containing the user's tags
2431 private void initializeSavedSearchTree() {
2432 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2433 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2434 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2436 // Listener when a tag is selected
2437 @SuppressWarnings("unused")
2438 private void savedSearchTreeSelection() {
2439 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2441 clearNotebookFilter();
2444 clearAttributeFilter();
2446 String currentGuid = selectedSavedSearchGUID;
2447 menuBar.savedSearchEditAction.setEnabled(true);
2448 menuBar.savedSearchDeleteAction.setEnabled(true);
2449 menuBar.savedSearchIconAction.setEnabled(true);
2450 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2451 QTreeWidgetItem currentSelection;
2452 selectedSavedSearchGUID = "";
2453 for (int i=0; i<selections.size(); i++) {
2454 currentSelection = selections.get(i);
2455 if (currentSelection.text(1).equals(currentGuid)) {
2456 currentSelection.setSelected(false);
2458 selectedSavedSearchGUID = currentSelection.text(1);
2460 // i = selections.size() +1;
2463 // There is the potential for no notebooks to be selected if this
2464 // happens then we make it look like all notebooks were selecetd.
2465 // If that happens, just select the "all notebooks"
2466 if (selections.size()==0) {
2467 clearSavedSearchFilter();
2469 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2471 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2473 private void clearSavedSearchFilter() {
2474 menuBar.savedSearchEditAction.setEnabled(false);
2475 menuBar.savedSearchDeleteAction.setEnabled(false);
2476 menuBar.savedSearchIconAction.setEnabled(false);
2477 savedSearchTree.blockSignals(true);
2478 savedSearchTree.clearSelection();
2479 savedSearchTree.blockSignals(false);
2480 selectedSavedSearchGUID = "";
2481 searchField.setEditText("");
2482 searchPerformed = false;
2483 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2485 // trigger the tag index to be refreshed
2486 private void savedSearchIndexUpdated() {
2487 if (selectedSavedSearchGUID == null)
2488 selectedSavedSearchGUID = new String();
2489 savedSearchTree.blockSignals(true);
2490 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2491 savedSearchTree.load(listManager.getSavedSearchIndex());
2492 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2493 savedSearchTree.blockSignals(false);
2495 // trigger when the saved search selection changes
2496 @SuppressWarnings("unused")
2497 private void updateSavedSearchSelection() {
2498 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2500 menuBar.savedSearchEditAction.setEnabled(true);
2501 menuBar.savedSearchDeleteAction.setEnabled(true);
2502 menuBar.savedSearchIconAction.setEnabled(true);
2503 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2505 if (selections.size() > 0) {
2506 menuBar.savedSearchEditAction.setEnabled(true);
2507 menuBar.savedSearchDeleteAction.setEnabled(true);
2508 menuBar.savedSearchIconAction.setEnabled(true);
2509 selectedSavedSearchGUID = selections.get(0).text(1);
2510 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2511 searchField.setEditText(s.getQuery());
2513 menuBar.savedSearchEditAction.setEnabled(false);
2514 menuBar.savedSearchDeleteAction.setEnabled(false);
2515 menuBar.savedSearchIconAction.setEnabled(false);
2516 selectedSavedSearchGUID = "";
2517 searchField.setEditText("");
2519 searchFieldChanged();
2521 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2525 // Show/Hide note information
2526 @SuppressWarnings("unused")
2527 private void toggleSavedSearchWindow() {
2528 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2529 if (savedSearchTree.isVisible())
2530 savedSearchTree.hide();
2532 savedSearchTree.show();
2533 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2535 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2536 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2538 // Change the icon for a saved search
2539 @SuppressWarnings("unused")
2540 private void setSavedSearchIcon() {
2541 QTreeWidgetItem currentSelection;
2542 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2543 if (selections.size() == 0)
2546 currentSelection = selections.get(0);
2547 String guid = currentSelection.text(1);
2549 QIcon currentIcon = currentSelection.icon(0);
2550 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2553 dialog = new SetIcon(currentIcon, saveLastPath);
2554 dialog.setUseDefaultIcon(true);
2556 dialog = new SetIcon(icon, saveLastPath);
2557 dialog.setUseDefaultIcon(false);
2560 if (dialog.okPressed()) {
2561 saveLastPath = dialog.getPath();
2562 QIcon newIcon = dialog.getIcon();
2563 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2564 if (newIcon == null)
2565 newIcon = new QIcon(iconPath+"search.png");
2566 currentSelection.setIcon(0, newIcon);
2574 //***************************************************************
2575 //***************************************************************
2576 //** These functions deal with Help menu & tool menu items
2577 //***************************************************************
2578 //***************************************************************
2579 // Show database status
2580 @SuppressWarnings("unused")
2581 private void databaseStatus() {
2583 indexRunner.interrupt = true;
2584 int dirty = conn.getNoteTable().getDirtyCount();
2585 int unindexed = conn.getNoteTable().getUnindexedCount();
2586 DatabaseStatus status = new DatabaseStatus();
2587 status.setUnsynchronized(dirty);
2588 status.setUnindexed(unindexed);
2589 status.setNoteCount(conn.getNoteTable().getNoteCount());
2590 status.setNotebookCount(listManager.getNotebookIndex().size());
2591 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2592 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2593 status.setTagCount(listManager.getTagIndex().size());
2594 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2595 status.setWordCount(conn.getWordsTable().getWordCount());
2599 // Compact the database
2600 @SuppressWarnings("unused")
2601 private void compactDatabase() {
2602 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2603 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2604 "but please be aware that depending upon the size of your database this can be time consuming " +
2605 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2606 QMessageBox.StandardButton.Yes,
2607 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2610 setMessage("Compacting database.");
2612 listManager.compactDatabase();
2614 setMessage("Database compact is complete.");
2615 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2617 @SuppressWarnings("unused")
2618 private void accountInformation() {
2619 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2620 AccountDialog dialog = new AccountDialog();
2622 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2624 @SuppressWarnings("unused")
2625 private void releaseNotes() {
2626 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2627 QDialog dialog = new QDialog(this);
2628 QHBoxLayout layout = new QHBoxLayout();
2629 QTextEdit textBox = new QTextEdit();
2630 layout.addWidget(textBox);
2631 textBox.setReadOnly(true);
2632 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2633 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2634 QIODevice.OpenModeFlag.Text)))
2636 textBox.setText(file.readAll().toString());
2638 dialog.setWindowTitle(tr("Release Notes"));
2639 dialog.setLayout(layout);
2641 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2643 // Called when user picks Log from the help menu
2644 @SuppressWarnings("unused")
2645 private void logger() {
2646 logger.log(logger.HIGH, "Entering NeverNote.logger");
2647 LogFileDialog dialog = new LogFileDialog(emitLog);
2649 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2651 // Menu option "help/about" was selected
2652 @SuppressWarnings("unused")
2653 private void about() {
2654 logger.log(logger.HIGH, "Entering NeverNote.about");
2655 QMessageBox.about(this,
2656 tr("About NeverNote"),
2657 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2659 +tr("<hr></center>Evernote"
2660 +"An Open Source Evernote Client.<br><br>"
2661 +"Licensed under GPL v2. <br><hr><br>"
2662 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2663 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2664 +"PDFRenderer is licened under the LGPL<br>"
2665 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2666 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2667 +"Jazzy is licened under the LGPL<br>"
2668 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2669 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2670 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2671 logger.log(logger.HIGH, "Leaving NeverNote.about");
2673 // Hide the entire left hand side
2674 @SuppressWarnings("unused")
2675 private void toggleLeftSide() {
2678 hidden = !menuBar.hideLeftSide.isChecked();
2679 menuBar.hideLeftSide.setChecked(!hidden);
2682 leftSplitter1.setHidden(true);
2684 leftSplitter1.setHidden(false);
2686 Global.saveWindowVisible("leftPanel", hidden);
2689 public void checkForUpdates() {
2690 // Send off thread to check for a new version
2691 versionChecker = new QNetworkAccessManager(this);
2692 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2693 QNetworkRequest request = new QNetworkRequest();
2694 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2695 versionChecker.get(request);
2697 @SuppressWarnings("unused")
2698 private void upgradeFileRead(QNetworkReply reply) {
2699 if (!reply.isReadable())
2702 String winVersion = Global.version;
2703 String osxVersion = Global.version;
2704 String linuxVersion = Global.version;
2705 String linux64Version = Global.version;
2706 String version = Global.version;
2708 // Determine the versions available
2709 QByteArray data = reply.readLine();
2710 while (data != null && !reply.atEnd()) {
2711 String line = data.toString();
2713 if (line.contains(":"))
2714 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2717 if (line.toLowerCase().contains("windows"))
2718 winVersion = lineVersion;
2719 else if (line.toLowerCase().contains("os-x"))
2720 osxVersion = lineVersion;
2721 else if (line.toLowerCase().contains("linux amd64"))
2722 linux64Version = lineVersion;
2723 else if (line.toLowerCase().contains("linux i386"))
2724 linuxVersion = lineVersion;
2725 else if (line.toLowerCase().contains("default"))
2726 version = lineVersion;
2728 // Read the next line
2729 data = reply.readLine();
2732 // Now we need to determine what system we are on.
2733 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2734 version = winVersion;
2735 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2736 version = osxVersion;
2737 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2738 if (System.getProperty("os.arch").contains("amd64") ||
2739 System.getProperty("os.arch").contains("x86_64"))
2740 version = linux64Version;
2742 version = linuxVersion;
2746 for (String validVersion : Global.validVersions) {
2747 if (version.equals(validVersion))
2751 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2753 if (dialog.remindMe())
2754 Global.setCheckVersionUpgrade(true);
2756 Global.setCheckVersionUpgrade(false);
2760 //***************************************************************
2761 //***************************************************************
2762 //** These functions deal with the Toolbar
2763 //***************************************************************
2764 //***************************************************************
2765 @SuppressWarnings("unused")
2766 private void focusSearch() {
2767 searchField.setFocus();
2770 // Text in the search bar has been cleared
2771 private void searchFieldCleared() {
2774 // This is done because we want to force a reload of
2775 // images. Some images we may want to highlight the text.
2776 readOnlyCache.clear();
2777 inkNoteCache.clear();
2779 QWebSettings.setMaximumPagesInCache(0);
2780 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2782 searchField.setEditText("");
2783 saveNoteColumnPositions();
2784 saveNoteIndexWidth();
2785 noteIndexUpdated(true);
2786 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2787 currentNote = listManager.getNoteIndex().get(0);
2788 currentNoteGuid = currentNote.getGuid();
2790 refreshEvernoteNote(true);
2791 if (currentNote != null)
2792 loadNoteBrowserInformation(browserWindow);
2794 // text in the search bar changed. We only use this to tell if it was cleared,
2795 // otherwise we trigger off searchFieldChanged.
2796 @SuppressWarnings("unused")
2797 private void searchFieldTextChanged(String text) {
2798 QWebSettings.setMaximumPagesInCache(0);
2799 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2801 if (text.trim().equals("")) {
2802 searchFieldCleared();
2803 if (searchPerformed) {
2805 // This is done because we want to force a reload of
2806 // images. Some images we may want to highlight the text.
2808 readOnlyCache.clear();
2809 inkNoteCache.clear();
2811 listManager.setEnSearch("");
2812 listManager.loadNotesIndex();
2813 refreshEvernoteNote(true);
2814 noteIndexUpdated(false);
2815 refreshEvernoteNote(true);
2817 searchPerformed = false;
2820 // Text in the toolbar has changed
2821 private void searchFieldChanged() {
2822 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2824 readOnlyCache.clear();
2825 inkNoteCache.clear();
2826 saveNoteColumnPositions();
2827 saveNoteIndexWidth();
2828 String text = searchField.currentText();
2829 listManager.setEnSearch(text.trim());
2830 listManager.loadNotesIndex();
2831 noteIndexUpdated(false);
2832 refreshEvernoteNote(true);
2833 searchPerformed = true;
2834 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2837 // Build the window tool bar
2838 private void setupToolBar() {
2839 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2840 toolBar = addToolBar(tr("Tool Bar"));
2841 toolBar.setObjectName("toolBar");
2842 menuBar.setupToolBarVisible();
2843 if (!Global.isWindowVisible("toolBar"))
2844 toolBar.setVisible(false);
2846 toolBar.setVisible(true);
2848 // toolBar.addWidget(menuBar);
2849 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2850 // toolBar.addSeparator();
2851 prevButton = toolBar.addAction("Previous");
2852 QIcon prevIcon = new QIcon(iconPath+"back.png");
2853 prevButton.setIcon(prevIcon);
2854 prevButton.triggered.connect(this, "previousViewedAction()");
2855 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2857 nextButton = toolBar.addAction("Next");
2858 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2859 nextButton.setIcon(nextIcon);
2860 nextButton.triggered.connect(this, "nextViewedAction()");
2861 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2863 upButton = toolBar.addAction("Up");
2864 QIcon upIcon = new QIcon(iconPath+"up.png");
2865 upButton.setIcon(upIcon);
2866 upButton.triggered.connect(this, "upAction()");
2867 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2870 downButton = toolBar.addAction("Down");
2871 QIcon downIcon = new QIcon(iconPath+"down.png");
2872 downButton.setIcon(downIcon);
2873 downButton.triggered.connect(this, "downAction()");
2874 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2876 synchronizeButton = toolBar.addAction("Synchronize");
2877 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2878 synchronizeIconAngle = 0;
2879 synchronizeButton.triggered.connect(this, "evernoteSync()");
2880 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2882 printButton = toolBar.addAction("Print");
2883 QIcon printIcon = new QIcon(iconPath+"print.png");
2884 printButton.setIcon(printIcon);
2885 printButton.triggered.connect(this, "printNote()");
2886 togglePrintButton(Global.isToolbarButtonVisible("print"));
2888 tagButton = toolBar.addAction("Tag");
2889 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2890 tagButton.setIcon(tagIcon);
2891 tagButton.triggered.connect(browserWindow, "modifyTags()");
2892 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2894 attributeButton = toolBar.addAction("Attributes");
2895 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2896 attributeButton.setIcon(attributeIcon);
2897 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2898 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2900 emailButton = toolBar.addAction("Email");
2901 QIcon emailIcon = new QIcon(iconPath+"email.png");
2902 emailButton.setIcon(emailIcon);
2903 emailButton.triggered.connect(this, "emailNote()");
2904 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2906 deleteButton = toolBar.addAction("Delete");
2907 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2908 deleteButton.setIcon(deleteIcon);
2909 deleteButton.triggered.connect(this, "deleteNote()");
2910 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2912 newButton = toolBar.addAction("New");
2913 QIcon newIcon = new QIcon(iconPath+"new.png");
2914 newButton.triggered.connect(this, "addNote()");
2915 newButton.setIcon(newIcon);
2916 toggleNewButton(Global.isToolbarButtonVisible("new"));
2918 allNotesButton = toolBar.addAction("All Notes");
2919 QIcon allIcon = new QIcon(iconPath+"books.png");
2920 allNotesButton.triggered.connect(this, "allNotes()");
2921 allNotesButton.setIcon(allIcon);
2922 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2924 //toolBar.addSeparator();
2925 //toolBar.addWidget(new QLabel(tr("Quota:")));
2926 //toolBar.addWidget(quotaBar);
2927 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2929 //toolBar.addSeparator();
2931 //toolBar.addWidget(new QLabel(tr("Zoom")));
2932 //toolBar.addWidget(zoomSpinner);
2934 //toolBar.addWidget(new QLabel(" "));
2935 //toolBar.addSeparator();
2936 //toolBar.addWidget(new QLabel(tr(" Search:")));
2937 //toolBar.addWidget(searchField);
2938 QSizePolicy sizePolicy = new QSizePolicy();
2939 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2940 QLabel spacer = new QLabel("");
2941 spacer.setSizePolicy(sizePolicy);
2942 toolBar.addWidget(spacer);
2943 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2945 //searchClearButton = toolBar.addAction("Search Clear");
2946 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2947 //searchClearButton.setIcon(searchClearIcon);
2948 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2949 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2951 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2953 // Update the sychronize button picture
2955 public QMenu createPopupMenu() {
2956 QMenu contextMenu = super.createPopupMenu();
2958 contextMenu.addSeparator();
2959 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2960 contextMenu.addAction(prevAction);
2961 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2963 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2964 contextMenu.addAction(nextAction);
2965 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2967 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2968 contextMenu.addAction(upAction);
2969 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2971 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2972 contextMenu.addAction(downAction);
2973 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2975 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2976 contextMenu.addAction(synchronizeAction);
2977 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2979 QAction printAction = addContextAction("print", tr("Print"));
2980 contextMenu.addAction(printAction);
2981 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2983 QAction tagAction = addContextAction("tag", tr("Tag"));
2984 contextMenu.addAction(tagAction);
2985 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2987 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2988 contextMenu.addAction(attributeAction);
2989 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2991 QAction emailAction = addContextAction("email", tr("Email"));
2992 contextMenu.addAction(emailAction);
2993 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2995 QAction deleteAction = addContextAction("delete", tr("Delete"));
2996 contextMenu.addAction(deleteAction);
2997 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2999 QAction newAction = addContextAction("new", tr("Add"));
3000 contextMenu.addAction(newAction);
3001 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3003 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3004 contextMenu.addAction(allNotesAction);
3005 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3007 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3008 contextMenu.addAction(searchClearAction);
3009 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3014 private QAction addContextAction(String config, String name) {
3015 QAction newAction = new QAction(this);
3016 newAction.setText(name);
3017 newAction.setCheckable(true);
3018 newAction.setChecked(Global.isToolbarButtonVisible(config));
3021 private void togglePrevArrowButton(Boolean toggle) {
3022 prevButton.setVisible(toggle);
3023 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3025 private void toggleNextArrowButton(Boolean toggle) {
3026 nextButton.setVisible(toggle);
3027 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3029 private void toggleUpArrowButton(Boolean toggle) {
3030 upButton.setVisible(toggle);
3031 Global.saveToolbarButtonsVisible("upArrow", toggle);
3033 private void toggleDownArrowButton(Boolean toggle) {
3034 downButton.setVisible(toggle);
3035 Global.saveToolbarButtonsVisible("downArrow", toggle);
3037 private void toggleSynchronizeButton(Boolean toggle) {
3038 synchronizeButton.setVisible(toggle);
3039 Global.saveToolbarButtonsVisible("synchronize", toggle);
3041 private void togglePrintButton(Boolean toggle) {
3042 printButton.setVisible(toggle);
3043 Global.saveToolbarButtonsVisible("print", toggle);
3045 private void toggleTagButton(Boolean toggle) {
3046 tagButton.setVisible(toggle);
3047 Global.saveToolbarButtonsVisible("tag", toggle);
3049 private void toggleAttributeButton(Boolean toggle) {
3050 attributeButton.setVisible(toggle);
3051 Global.saveToolbarButtonsVisible("attribute", toggle);
3053 private void toggleEmailButton(Boolean toggle) {
3054 emailButton.setVisible(toggle);
3055 Global.saveToolbarButtonsVisible("email", toggle);
3057 private void toggleDeleteButton(Boolean toggle) {
3058 deleteButton.setVisible(toggle);
3059 Global.saveToolbarButtonsVisible("delete", toggle);
3061 private void toggleNewButton(Boolean toggle) {
3062 newButton.setVisible(toggle);
3063 Global.saveToolbarButtonsVisible("new", toggle);
3065 private void toggleAllNotesButton(Boolean toggle) {
3066 allNotesButton.setVisible(toggle);
3067 Global.saveToolbarButtonsVisible("allNotes", toggle);
3069 @SuppressWarnings("unused")
3070 private void toggleSearchClearButton(Boolean toggle) {
3071 searchClearButton.setVisible(toggle);
3072 Global.saveToolbarButtonsVisible("searchClear", toggle);
3079 @SuppressWarnings("unused")
3080 private void updateSyncButton() {
3082 if (syncIcons == null) {
3083 syncIcons = new ArrayList<QPixmap>();
3085 synchronizeIconAngle = 0;
3086 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3088 for (int i=0; i<=360; i++) {
3089 QPixmap rotatedPix = new QPixmap(pix.size());
3090 QPainter p = new QPainter(rotatedPix);
3091 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3092 QSize size = pix.size();
3093 p.translate(size.width()/2, size.height()/2);
3096 p.setBackgroundMode(BGMode.OpaqueMode);
3097 p.translate(-size.width()/2, -size.height()/2);
3098 p.drawPixmap(0,0, pix);
3100 syncIcons.add(rotatedPix);
3104 synchronizeIconAngle++;
3105 if (synchronizeIconAngle > 359)
3106 synchronizeIconAngle=0;
3107 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3110 // Synchronize with Evernote
3111 @SuppressWarnings("unused")
3112 private void evernoteSync() {
3113 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3114 if (!Global.isConnected)
3116 if (Global.isConnected)
3117 synchronizeAnimationTimer.start(5);
3118 // synchronizeAnimationTimer.start(200);
3120 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3122 private void updateQuotaBar() {
3123 long limit = Global.getUploadLimit();
3124 long amount = Global.getUploadAmount();
3125 if (amount>0 && limit>0) {
3126 int percent =(int)(amount*100/limit);
3127 quotaBar.setValue(percent);
3129 quotaBar.setValue(0);
3132 @SuppressWarnings("unused")
3133 private void zoomChanged() {
3134 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3137 //****************************************************************
3138 //****************************************************************
3139 //* System Tray functions
3140 //****************************************************************
3141 //****************************************************************
3142 private void trayToggleVisible() {
3147 if (windowMaximized)
3154 @SuppressWarnings("unused")
3155 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3156 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3157 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3158 trayToggleVisible();
3163 //***************************************************************
3164 //***************************************************************
3165 //** These functions deal with the trash tree
3166 //***************************************************************
3167 //***************************************************************
3168 // Setup the tree containing the trash.
3169 @SuppressWarnings("unused")
3170 private void trashTreeSelection() {
3171 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3173 clearNotebookFilter();
3175 clearAttributeFilter();
3176 clearSavedSearchFilter();
3178 String tempGuid = currentNoteGuid;
3180 // currentNoteGuid = "";
3181 currentNote = new Note();
3182 selectedNoteGUIDs.clear();
3183 listManager.getSelectedNotebooks().clear();
3184 listManager.getSelectedTags().clear();
3185 listManager.setSelectedSavedSearch("");
3186 browserWindow.clear();
3188 // toggle the add buttons
3189 newButton.setEnabled(!newButton.isEnabled());
3190 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3191 menuBar.noteAdd.setVisible(true);
3193 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3194 if (selections.size() == 0) {
3195 currentNoteGuid = trashNoteGuid;
3196 trashNoteGuid = tempGuid;
3197 Global.showDeleted = false;
3198 menuBar.noteRestoreAction.setEnabled(false);
3199 menuBar.noteRestoreAction.setVisible(false);
3202 currentNoteGuid = trashNoteGuid;
3203 trashNoteGuid = tempGuid;
3204 menuBar.noteRestoreAction.setEnabled(true);
3205 menuBar.noteRestoreAction.setVisible(true);
3206 Global.showDeleted = true;
3208 listManager.loadNotesIndex();
3209 noteIndexUpdated(false);
3210 //// browserWindow.setEnabled(newButton.isEnabled());
3211 browserWindow.setReadOnly(!newButton.isEnabled());
3212 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3214 // Empty the trash file
3215 @SuppressWarnings("unused")
3216 private void emptyTrash() {
3217 // browserWindow.clear();
3218 listManager.emptyTrash();
3219 if (trashTree.selectedItems().size() > 0) {
3220 listManager.getSelectedNotebooks().clear();
3221 listManager.getSelectedTags().clear();
3222 listManager.setSelectedSavedSearch("");
3223 newButton.setEnabled(!newButton.isEnabled());
3224 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3225 menuBar.noteAdd.setVisible(true);
3226 browserWindow.clear();
3229 clearNotebookFilter();
3230 clearSavedSearchFilter();
3231 clearAttributeFilter();
3233 Global.showDeleted = false;
3234 menuBar.noteRestoreAction.setEnabled(false);
3235 menuBar.noteRestoreAction.setVisible(false);
3237 listManager.loadNotesIndex();
3238 noteIndexUpdated(false);
3241 // Show/Hide trash window
3242 @SuppressWarnings("unused")
3243 private void toggleTrashWindow() {
3244 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3245 if (trashTree.isVisible())
3249 menuBar.hideTrash.setChecked(trashTree.isVisible());
3251 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3252 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3254 private void clearTrashFilter() {
3255 Global.showDeleted = false;
3256 newButton.setEnabled(true);
3257 menuBar.noteAdd.setEnabled(true);
3258 menuBar.noteAdd.setVisible(true);
3259 trashTree.blockSignals(true);
3260 trashTree.clearSelection();
3261 trashTree.blockSignals(false);
3266 //***************************************************************
3267 //***************************************************************
3268 //** These functions deal with connection settings
3269 //***************************************************************
3270 //***************************************************************
3271 // SyncRunner had a problem and things are disconnected
3272 @SuppressWarnings("unused")
3273 private void remoteErrorDisconnect() {
3274 menuBar.connectAction.setText(tr("Connect"));
3275 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3276 menuBar.synchronizeAction.setEnabled(false);
3277 Global.isConnected = false;
3278 synchronizeAnimationTimer.stop();
3281 // Do a manual connect/disconnect
3282 private void remoteConnect() {
3283 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3285 if (Global.isConnected) {
3286 Global.isConnected = false;
3287 syncRunner.enDisconnect();
3288 setupConnectMenuOptions();
3293 AESEncrypter aes = new AESEncrypter();
3295 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3296 } catch (FileNotFoundException e) {
3297 // File not found, so we'll just get empty strings anyway.
3300 if (Global.getProxyValue("url").equals("")) {
3301 System.setProperty("http.proxyHost","") ;
3302 System.setProperty("http.proxyPort", "") ;
3303 System.setProperty("https.proxyHost","") ;
3304 System.setProperty("https.proxyPort", "") ;
3307 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3308 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3309 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3310 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3312 if (Global.getProxyValue("userid").equals("")) {
3313 Authenticator.setDefault(new Authenticator() {
3315 protected PasswordAuthentication getPasswordAuthentication() {
3317 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3323 syncRunner.userStoreUrl = Global.userStoreUrl;
3324 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3325 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3327 String userid = aes.getUserid();
3328 String password = aes.getPassword();
3329 if (!userid.equals("") && !password.equals("")) {
3330 Global.username = userid;
3331 Global.password = password;
3332 syncRunner.username = Global.username;
3333 syncRunner.password = Global.password;
3334 syncRunner.enConnect();
3337 Global.isConnected = syncRunner.isConnected;
3339 if (!Global.isConnected) {
3340 // Show the login dialog box
3341 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3342 LoginDialog login = new LoginDialog();
3345 if (!login.okPressed()) {
3349 Global.username = login.getUserid();
3350 Global.password = login.getPassword();
3352 syncRunner.username = Global.username;
3353 syncRunner.password = Global.password;
3354 syncRunner.enConnect();
3355 Global.isConnected = syncRunner.isConnected;
3358 if (!Global.isConnected)
3361 setupConnectMenuOptions();
3362 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3364 private void setupConnectMenuOptions() {
3365 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3366 if (!Global.isConnected) {
3367 menuBar.connectAction.setText(tr("Connect"));
3368 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3369 menuBar.synchronizeAction.setEnabled(false);
3371 menuBar.connectAction.setText(tr("Disconnect"));
3372 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3373 menuBar.synchronizeAction.setEnabled(true);
3375 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3380 //***************************************************************
3381 //***************************************************************
3382 //** These functions deal with the GUI Attribute tree
3383 //***************************************************************
3384 //***************************************************************
3385 @SuppressWarnings("unused")
3386 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3388 // clearTagFilter();
3389 // clearNotebookFilter();
3391 // clearSavedSearchFilter();
3393 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3394 if (item.childCount() > 0) {
3395 item.setSelected(false);
3397 Global.createdBeforeFilter.reset();
3398 Global.createdSinceFilter.reset();
3399 Global.changedBeforeFilter.reset();
3400 Global.changedSinceFilter.reset();
3401 Global.containsFilter.reset();
3402 attributeTreeSelected = item;
3403 DateAttributeFilterTable f = null;
3404 f = findDateAttributeFilterTable(item.parent());
3406 f.select(item.parent().indexOfChild(item));
3408 Global.containsFilter.select(item.parent().indexOfChild(item));
3411 listManager.loadNotesIndex();
3412 noteIndexUpdated(false);
3415 attributeTreeSelected = null;
3416 item.setSelected(false);
3417 Global.createdBeforeFilter.reset();
3418 Global.createdSinceFilter.reset();
3419 Global.changedBeforeFilter.reset();
3420 Global.changedSinceFilter.reset();
3421 Global.containsFilter.reset();
3422 listManager.loadNotesIndex();
3423 noteIndexUpdated(false);
3425 // This determines what attribute filter we need, depending upon the selection
3426 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3427 if (w.parent() != null && w.childCount() > 0) {
3428 QTreeWidgetItem parent = w.parent();
3429 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3430 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3431 return Global.createdSinceFilter;
3432 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3433 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3434 return Global.createdBeforeFilter;
3435 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3436 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3437 return Global.changedSinceFilter;
3438 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3439 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3440 return Global.changedBeforeFilter;
3445 // Show/Hide attribute search window
3446 @SuppressWarnings("unused")
3447 private void toggleAttributesWindow() {
3448 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3449 if (attributeTree.isVisible())
3450 attributeTree.hide();
3452 attributeTree.show();
3453 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3455 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3456 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3458 private void clearAttributeFilter() {
3459 Global.createdBeforeFilter.reset();
3460 Global.createdSinceFilter.reset();
3461 Global.changedBeforeFilter.reset();
3462 Global.changedSinceFilter.reset();
3463 Global.containsFilter.reset();
3464 attributeTreeSelected = null;
3465 attributeTree.blockSignals(true);
3466 attributeTree.clearSelection();
3467 attributeTree.blockSignals(false);
3471 //***************************************************************
3472 //***************************************************************
3473 //** These functions deal with the GUI Note index table
3474 //***************************************************************
3475 //***************************************************************
3476 // Initialize the note list table
3477 private void initializeNoteTable() {
3478 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3479 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3480 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3481 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3483 // Show/Hide trash window
3484 @SuppressWarnings("unused")
3485 private void toggleNoteListWindow() {
3486 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3487 if (noteTableView.isVisible())
3488 noteTableView.hide();
3490 noteTableView.show();
3491 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3493 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3494 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3496 // Handle the event that a user selects a note from the table
3497 @SuppressWarnings("unused")
3498 private void noteTableSelection() {
3499 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3501 if (historyGuids.size() == 0) {
3502 historyGuids.add(currentNoteGuid);
3503 historyPosition = 1;
3505 noteTableView.showColumn(Global.noteTableGuidPosition);
3507 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3508 if (!Global.isColumnVisible("guid"))
3509 noteTableView.hideColumn(Global.noteTableGuidPosition);
3511 if (selections.size() > 0) {
3513 menuBar.noteDuplicateAction.setEnabled(true);
3514 menuBar.noteOnlineHistoryAction.setEnabled(true);
3515 menuBar.noteMergeAction.setEnabled(true);
3516 selectedNoteGUIDs.clear();
3517 if (selections.size() != 1 || Global.showDeleted) {
3518 menuBar.noteDuplicateAction.setEnabled(false);
3520 if (selections.size() != 1 || !Global.isConnected) {
3521 menuBar.noteOnlineHistoryAction.setEnabled(false);
3523 if (selections.size() == 1) {
3524 menuBar.noteMergeAction.setEnabled(false);
3526 for (int i=0; i<selections.size(); i++) {
3527 int row = selections.get(i).row();
3529 upButton.setEnabled(false);
3531 upButton.setEnabled(true);
3532 if (row < listManager.getNoteTableModel().rowCount()-1)
3533 downButton.setEnabled(true);
3535 downButton.setEnabled(false);
3536 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3537 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3538 currentNoteGuid = (String)ix.values().toArray()[0];
3539 selectedNoteGUIDs.add(currentNoteGuid);
3543 nextButton.setEnabled(true);
3544 prevButton.setEnabled(true);
3546 int endPosition = historyGuids.size()-1;
3547 for (int j=historyPosition; j<=endPosition; j++) {
3548 historyGuids.remove(historyGuids.size()-1);
3550 historyGuids.add(currentNoteGuid);
3551 historyPosition = historyGuids.size();
3553 if (historyPosition <= 1)
3554 prevButton.setEnabled(false);
3555 if (historyPosition == historyGuids.size())
3556 nextButton.setEnabled(false);
3558 fromHistory = false;
3559 scrollToGuid(currentNoteGuid);
3560 refreshEvernoteNote(true);
3561 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3563 // Trigger a refresh when the note db has been updated
3564 private void noteIndexUpdated(boolean reload) {
3565 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3567 refreshEvernoteNoteList();
3568 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3569 noteTableView.load(reload);
3570 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3572 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3573 pos = noteTableView.proxyModel.rowCount();
3576 if (noteTableView.proxyModel.rowCount() == 0)
3579 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3581 currentNoteGuid = (String)i.data();
3585 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3587 scrollToGuid(currentNoteGuid);
3588 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3590 // Called when the list of notes is updated
3591 private void refreshEvernoteNoteList() {
3592 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3593 browserWindow.setDisabled(false);
3594 if (selectedNoteGUIDs == null)
3595 selectedNoteGUIDs = new ArrayList<String>();
3596 selectedNoteGUIDs.clear(); // clear out old entries
3598 String saveCurrentNoteGuid = new String();
3599 String tempNoteGuid = new String();
3601 historyGuids.clear();
3602 historyPosition = 0;
3603 prevButton.setEnabled(false);
3604 nextButton.setEnabled(false);
3606 if (currentNoteGuid == null)
3607 currentNoteGuid = new String();
3609 //determine current note guid
3610 for (Note note : listManager.getNoteIndex()) {
3611 tempNoteGuid = note.getGuid();
3612 if (currentNoteGuid.equals(tempNoteGuid)) {
3613 saveCurrentNoteGuid = tempNoteGuid;
3617 if (listManager.getNoteIndex().size() == 0) {
3618 currentNoteGuid = "";
3620 browserWindow.clear();
3621 browserWindow.setDisabled(true);
3624 if (!saveCurrentNoteGuid.equals("")) {
3625 refreshEvernoteNote(false);
3627 currentNoteGuid = "";
3629 reloadTagTree(false);
3631 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3633 // Called when the previous arrow button is clicked
3634 @SuppressWarnings("unused")
3635 private void previousViewedAction() {
3636 if (!prevButton.isEnabled())
3638 if (historyPosition == 0)
3641 if (historyPosition <= 0)
3643 String historyGuid = historyGuids.get(historyPosition-1);
3645 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3646 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3647 if (modelIndex != null) {
3648 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3649 String tableGuid = (String)ix.values().toArray()[0];
3650 if (tableGuid.equals(historyGuid)) {
3651 noteTableView.selectRow(i);
3657 @SuppressWarnings("unused")
3658 private void nextViewedAction() {
3659 if (!nextButton.isEnabled())
3661 String historyGuid = historyGuids.get(historyPosition);
3664 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3665 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3666 if (modelIndex != null) {
3667 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3668 String tableGuid = (String)ix.values().toArray()[0];
3669 if (tableGuid.equals(historyGuid)) {
3670 noteTableView.selectRow(i);
3676 // Called when the up arrow is clicked
3677 @SuppressWarnings("unused")
3678 private void upAction() {
3679 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3680 int row = selections.get(0).row();
3682 noteTableView.selectRow(row-1);
3685 // Called when the down arrow is clicked
3686 @SuppressWarnings("unused")
3687 private void downAction() {
3688 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3689 int row = selections.get(0).row();
3690 int max = listManager.getNoteTableModel().rowCount();
3692 noteTableView.selectRow(row+1);
3695 // Update a tag string for a specific note in the list
3696 @SuppressWarnings("unused")
3697 private void updateListTags(String guid, List<String> tags) {
3698 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3699 StringBuffer tagBuffer = new StringBuffer();
3700 for (int i=0; i<tags.size(); i++) {
3701 tagBuffer.append(tags.get(i));
3702 if (i<tags.size()-1)
3703 tagBuffer.append(", ");
3706 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3707 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3708 if (modelIndex != null) {
3709 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3710 String tableGuid = (String)ix.values().toArray()[0];
3711 if (tableGuid.equals(guid)) {
3712 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3713 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3714 noteTableView.proxyModel.invalidate();
3719 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3721 // Update a title for a specific note in the list
3722 @SuppressWarnings("unused")
3723 private void updateListAuthor(String guid, String author) {
3724 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3726 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3727 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3728 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3729 if (modelIndex != null) {
3730 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3731 String tableGuid = (String)ix.values().toArray()[0];
3732 if (tableGuid.equals(guid)) {
3733 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3734 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3735 noteTableView.proxyModel.invalidate();
3741 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3743 private void updateListNoteNotebook(String guid, String notebook) {
3744 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3745 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3746 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3748 // Update a title for a specific note in the list
3749 @SuppressWarnings("unused")
3750 private void updateListSourceUrl(String guid, String url) {
3751 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3753 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3754 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3755 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3756 if (modelIndex != null) {
3757 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3758 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3759 String tableGuid = (String)ix.values().toArray()[0];
3760 if (tableGuid.equals(guid)) {
3761 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3762 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3763 noteTableView.proxyModel.invalidate();
3768 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3770 @SuppressWarnings("unused")
3771 private void updateListGuid(String oldGuid, String newGuid) {
3772 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3774 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3775 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3776 if (modelIndex != null) {
3777 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3778 String tableGuid = (String)ix.values().toArray()[0];
3779 if (tableGuid.equals(oldGuid)) {
3780 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3781 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3786 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3788 private void updateListTagName(String guid) {
3789 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3791 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3792 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3793 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3795 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3796 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3797 if (modelIndex != null) {
3798 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3799 String noteGuid = (String)ix.values().toArray()[0];
3800 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3801 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3802 i=listManager.getNoteTableModel().rowCount();
3808 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3810 private void removeListTagName(String guid) {
3811 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3813 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3814 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3815 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3816 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3817 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3820 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3821 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3822 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3823 if (modelIndex != null) {
3824 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3825 String noteGuid = (String)ix.values().toArray()[0];
3826 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3827 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3828 i=listManager.getNoteTableModel().rowCount();
3834 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3836 private void updateListNotebookName(String oldName, String newName) {
3837 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3839 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3840 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3841 if (modelIndex != null) {
3842 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3843 String tableName = (String)ix.values().toArray()[0];
3844 if (tableName.equalsIgnoreCase(oldName)) {
3845 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3849 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3851 @SuppressWarnings("unused")
3852 private void updateListDateCreated(String guid, QDateTime date) {
3853 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3855 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3856 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3857 if (modelIndex != null) {
3858 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3859 String tableGuid = (String)ix.values().toArray()[0];
3860 if (tableGuid.equals(guid)) {
3861 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3862 noteTableView.proxyModel.invalidate();
3867 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3869 @SuppressWarnings("unused")
3870 private void updateListDateSubject(String guid, QDateTime date) {
3871 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3873 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3874 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3875 if (modelIndex != null) {
3876 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3877 String tableGuid = (String)ix.values().toArray()[0];
3878 if (tableGuid.equals(guid)) {
3879 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3880 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3881 noteTableView.proxyModel.invalidate();
3886 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3888 private void updateListDateChanged(String guid, QDateTime date) {
3889 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3891 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3892 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3893 if (modelIndex != null) {
3894 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3895 String tableGuid = (String)ix.values().toArray()[0];
3896 if (tableGuid.equals(guid)) {
3897 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3898 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3903 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3905 private void updateListDateChanged() {
3906 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3907 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3908 updateListDateChanged(currentNoteGuid, date);
3909 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3912 private void scrollToCurrentGuid() {
3913 //scrollToGuid(currentNoteGuid);
3914 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3915 if (selections.size() == 0)
3917 QModelIndex index = selections.get(0);
3918 int row = selections.get(0).row();
3919 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3922 // Scroll to the current GUID in tthe list.
3923 // Scroll to a particular index item
3924 private void scrollToGuid(String guid) {
3925 if (currentNote == null || guid == null)
3927 if (currentNote.isActive() && Global.showDeleted) {
3928 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3929 if (!listManager.getNoteIndex().get(i).isActive()) {
3930 currentNote = listManager.getNoteIndex().get(i);
3931 currentNoteGuid = currentNote.getGuid();
3932 i = listManager.getNoteIndex().size();
3936 if (!currentNote.isActive() && !Global.showDeleted) {
3937 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3938 if (listManager.getNoteIndex().get(i).isActive()) {
3939 currentNote = listManager.getNoteIndex().get(i);
3940 currentNoteGuid = currentNote.getGuid();
3941 i = listManager.getNoteIndex().size();
3946 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3947 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3948 if (currentNoteGuid.equals(index.data())) {
3949 // noteTableView.selectionModel().blockSignals(true);
3950 noteTableView.selectRow(i);
3951 // noteTableView.selectionModel().blockSignals(false);
3952 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3953 i=listManager.getNoteTableModel().rowCount();
3956 noteTableView.repaint();
3958 // Show/Hide columns
3959 private void showColumns() {
3960 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3961 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3962 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3963 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3964 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3965 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3966 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3967 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3968 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3969 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3970 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3972 // Title color has changed
3973 @SuppressWarnings("unused")
3974 private void titleColorChanged(Integer color) {
3975 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3977 QColor backgroundColor = new QColor();
3978 QColor foregroundColor = new QColor(QColor.black);
3979 backgroundColor.setRgb(color);
3981 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3982 foregroundColor.setRgb(QColor.white.rgb());
3984 if (selectedNoteGUIDs.size() == 0)
3985 selectedNoteGUIDs.add(currentNoteGuid);
3987 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3988 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3989 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3990 if (modelIndex != null) {
3991 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3992 String tableGuid = (String)ix.values().toArray()[0];
3993 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3994 for (int k=0; k<Global.noteTableColumnCount; k++) {
3995 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3996 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3997 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3999 i=listManager.getNoteTableModel().rowCount();
4004 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
4006 // Wide list was chosen
4007 public void narrowListView() {
4008 saveNoteColumnPositions();
4009 saveNoteIndexWidth();
4011 int sortCol = noteTableView.proxyModel.sortColumn();
4012 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4013 Global.setSortColumn(sortCol);
4014 Global.setSortOrder(sortOrder);
4016 Global.setListView(Global.View_List_Narrow);
4018 menuBar.wideListView.blockSignals(true);
4019 menuBar.narrowListView.blockSignals(true);
4021 menuBar.wideListView.setChecked(false);
4022 menuBar.narrowListView.setChecked(true);
4024 menuBar.wideListView.blockSignals(false);
4025 menuBar.narrowListView.blockSignals(false);
4027 mainLeftRightSplitter.addWidget(noteTableView);
4028 mainLeftRightSplitter.addWidget(browserWindow);
4029 restoreWindowState(false);
4030 noteTableView.repositionColumns();
4031 noteTableView.resizeColumnWidths();
4032 noteTableView.resizeRowHeights();
4034 sortCol = Global.getSortColumn();
4035 sortOrder = Global.getSortOrder();
4036 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4039 noteTableView.load(false);
4040 refreshEvernoteNote(true);
4041 scrollToCurrentGuid();
4043 public void wideListView() {
4044 int sortCol = noteTableView.proxyModel.sortColumn();
4045 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4046 Global.setSortColumn(sortCol);
4047 Global.setSortOrder(sortOrder);
4050 saveNoteColumnPositions();
4051 saveNoteIndexWidth();
4052 Global.setListView(Global.View_List_Wide);
4054 menuBar.wideListView.blockSignals(true);
4055 menuBar.narrowListView.blockSignals(true);
4057 menuBar.wideListView.setChecked(true);
4058 menuBar.narrowListView.setChecked(false);
4060 menuBar.wideListView.blockSignals(false);
4061 menuBar.narrowListView.blockSignals(false);
4062 browserIndexSplitter.setVisible(true);
4063 browserIndexSplitter.addWidget(noteTableView);
4064 browserIndexSplitter.addWidget(browserWindow);
4065 restoreWindowState(false);
4066 noteTableView.repositionColumns();
4067 noteTableView.resizeColumnWidths();
4068 noteTableView.resizeRowHeights();
4070 sortCol = Global.getSortColumn();
4071 sortOrder = Global.getSortOrder();
4072 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4075 noteTableView.load(false);
4076 scrollToCurrentGuid();
4080 //***************************************************************
4081 //***************************************************************
4082 //** External editor window functions
4083 //***************************************************************
4084 //***************************************************************
4085 private void listDoubleClick() {
4087 if (externalWindows.containsKey(currentNoteGuid)) {
4088 externalWindows.get(currentNoteGuid).raise();
4091 // We have a new external editor to create
4092 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4093 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4094 newBrowser.setWindowIcon(appIcon);
4095 externalWindows.put(currentNoteGuid, newBrowser);
4096 showEditorButtons(newBrowser.getBrowserWindow());
4097 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
4098 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4099 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4100 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4101 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4102 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4103 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4104 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4106 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4107 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4108 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4112 @SuppressWarnings("unused")
4113 private void externalWindowTitleEdited(String guid, String text) {
4114 if (guid.equals(currentNoteGuid)) {
4115 browserWindow.setTitle(text);
4118 @SuppressWarnings({ "rawtypes", "unused" })
4119 private void externalWindowTagsEdited(String guid, List values) {
4120 StringBuffer line = new StringBuffer(100);
4121 for (int i=0; i<values.size(); i++) {
4123 line.append(Global.tagDelimeter+" ");
4124 line.append(values.get(i));
4126 if (guid.equals(currentNoteGuid)) {
4127 browserWindow.setTag(line.toString());
4130 @SuppressWarnings("unused")
4131 private void externalWindowClosing(String guid) {
4132 externalWindows.remove(guid);
4137 //***************************************************************
4138 //***************************************************************
4139 //** These functions deal with Note specific things
4140 //***************************************************************
4141 //***************************************************************
4142 @SuppressWarnings("unused")
4143 private void setNoteDirty() {
4144 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4146 // Find if the note is being edited externally. If it is, update it.
4147 if (externalWindows.containsKey(currentNoteGuid)) {
4148 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4149 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4150 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4151 window.getBrowserWindow().getBrowser().setContent(unicode);
4154 // If the note is dirty, then it is unsynchronized by default.
4158 // Set the note as dirty and check if its status is synchronized in the display table
4160 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4161 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4165 // If this wasn't already marked as unsynchronized, then we need to update the table
4166 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4167 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4168 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4169 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4170 if (modelIndex != null) {
4171 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4172 String tableGuid = (String)ix.values().toArray()[0];
4173 if (tableGuid.equals(currentNoteGuid)) {
4174 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4180 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4182 @SuppressWarnings("unused")
4183 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4184 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4185 QByteArray unicode = codec.fromUnicode(content);
4186 noteCache.remove(guid);
4187 noteCache.put(guid, unicode.toString());
4188 if (guid.equals(currentNoteGuid)) {
4190 browserWindow.getBrowser().setContent(unicode);
4193 thumbnailRunner.addWork("GENERATE "+ guid);
4194 saveNote(guid, browser);
4198 private void saveNote() {
4200 saveNote(currentNoteGuid, browserWindow);
4201 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4205 private void saveNote(String guid, BrowserWindow window) {
4206 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4207 logger.log(logger.EXTREME, "Note is dirty.");
4210 logger.log(logger.EXTREME, "Saving to cache");
4211 QTextCodec codec = QTextCodec.codecForLocale();
4212 // QTextDecoder decoder = codec.makeDecoder();
4213 codec = QTextCodec.codecForName("UTF-8");
4214 QByteArray unicode = codec.fromUnicode(window.getContent());
4215 noteCache.put(guid, unicode.toString());
4217 logger.log(logger.EXTREME, "updating list manager");
4218 listManager.updateNoteContent(guid, window.getContent());
4219 logger.log(logger.EXTREME, "Updating title");
4220 listManager.updateNoteTitle(guid, window.getTitle());
4221 updateListDateChanged();
4223 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4224 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4225 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4226 currentNote = listManager.getNoteIndex().get(i);
4227 i = listManager.getNoteIndex().size();
4232 // Get a note from Evernote (and put it in the browser)
4233 private void refreshEvernoteNote(boolean reload) {
4234 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4236 if (Global.disableViewing) {
4237 browserWindow.setEnabled(false);
4242 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4244 Global.cryptCounter =0;
4246 browserWindow.setReadOnly(true);
4254 browserWindow.loadingData(true);
4256 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4257 if (currentNote == null)
4259 loadNoteBrowserInformation(browserWindow);
4262 private void loadNoteBrowserInformation(BrowserWindow browser) {
4263 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4264 formatter.setNote(currentNote, Global.pdfPreview());
4265 formatter.setHighlight(listManager.getEnSearch());
4267 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4268 js = new QByteArray();
4269 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4270 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4271 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>");
4272 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4273 js.append("<style> img { max-width:100%; }</style>");
4274 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4275 js.append("</head>");
4276 formatter.setNote(currentNote, Global.pdfPreview());
4277 js.append(formatter.rebuildNoteHTML());
4278 js.append("</HTML>");
4279 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4280 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4281 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4282 browser.getBrowser().setContent(js);
4283 noteCache.put(currentNoteGuid, js.toString());
4285 if (formatter.resourceError)
4286 resourceErrorMessage();
4287 if (formatter.formatError) {
4289 QMessageBox.information(this, tr("Error"),
4290 tr("NeverNote had issues formatting this note." +
4291 " To protect your data this note is being marked as read-only."));
4294 readOnly = formatter.readOnly;
4295 inkNote = formatter.inkNote;
4297 readOnlyCache.put(currentNoteGuid, true);
4299 inkNoteCache.put(currentNoteGuid, true);
4301 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4302 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4303 js = new QByteArray(cachedContent);
4304 browser.getBrowser().setContent(js);
4305 if (readOnlyCache.containsKey(currentNoteGuid))
4307 if (inkNoteCache.containsKey(currentNoteGuid))
4310 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4311 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4313 if (readOnly || inkNote)
4314 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4316 browser.getBrowser().page().setContentEditable(true);
4317 browser.setReadOnly(readOnly);
4318 deleteButton.setEnabled(!readOnly);
4319 tagButton.setEnabled(!readOnly);
4320 menuBar.noteDelete.setEnabled(!readOnly);
4321 menuBar.noteTags.setEnabled(!readOnly);
4322 browser.setNote(currentNote);
4324 if (currentNote != null && currentNote.getNotebookGuid() != null &&
4325 conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4326 deleteButton.setEnabled(false);
4327 menuBar.notebookDeleteAction.setEnabled(false);
4329 deleteButton.setEnabled(true);
4330 menuBar.notebookDeleteAction.setEnabled(true);
4333 // Build a list of non-closed notebooks
4334 List<Notebook> nbooks = new ArrayList<Notebook>();
4335 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4336 boolean found=false;
4337 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4338 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4342 nbooks.add(listManager.getNotebookIndex().get(i));
4345 browser.setTitle(currentNote.getTitle());
4346 browser.setTag(getTagNamesForNote(currentNote));
4347 browser.setAuthor(currentNote.getAttributes().getAuthor());
4349 browser.setAltered(currentNote.getUpdated());
4350 browser.setCreation(currentNote.getCreated());
4351 if (currentNote.getAttributes().getSubjectDate() > 0)
4352 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4354 browser.setSubjectDate(currentNote.getCreated());
4355 browser.setUrl(currentNote.getAttributes().getSourceURL());
4357 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4358 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4359 browser.setAllTags(tagList);
4361 browser.setCurrentTags(currentNote.getTagNames());
4363 scrollToGuid(currentNoteGuid);
4365 browser.loadingData(false);
4366 if (thumbnailViewer.isActiveWindow())
4369 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4370 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4373 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4375 // Save a generated thumbnail
4376 private void toggleNoteInformation() {
4377 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4378 browserWindow.toggleInformation();
4379 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4380 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4381 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4383 // Listener triggered when a print button is pressed
4384 @SuppressWarnings("unused")
4385 private void printNote() {
4386 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4388 QPrintDialog dialog = new QPrintDialog();
4389 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4390 QPrinter printer = dialog.printer();
4391 browserWindow.getBrowser().print(printer);
4393 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4396 // Listener triggered when the email button is pressed
4397 @SuppressWarnings("unused")
4398 private void emailNote() {
4399 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4401 if (Desktop.isDesktopSupported()) {
4402 Desktop desktop = Desktop.getDesktop();
4404 String text2 = browserWindow.getContentsToEmail();
4405 QUrl url = new QUrl("mailto:");
4406 url.addQueryItem("subject", currentNote.getTitle());
4407 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4408 url.addQueryItem("body", text2);
4409 QDesktopServices.openUrl(url);
4413 if (desktop.isSupported(Desktop.Action.MAIL)) {
4414 URI uriMailTo = null;
4416 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4417 String text = browserWindow.getContentsToEmail();
4418 //text = "<b>" +text +"</b>";
4419 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4420 +"&BODY=" +text, null);
4421 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4422 +"&ATTACHMENT=d:/test.pdf", null);
4423 desktop.mail(uriMailTo);
4424 } catch (URISyntaxException e) {
4425 e.printStackTrace();
4426 } catch (IOException e) {
4427 e.printStackTrace();
4434 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4436 // Reindex all notes
4437 @SuppressWarnings("unused")
4438 private void fullReindex() {
4439 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4440 indexRunner.addWork("REINDEXALL");
4441 setMessage(tr("Database will be reindexed."));
4442 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4444 // Listener when a user wants to reindex a specific note
4445 @SuppressWarnings("unused")
4446 private void reindexNote() {
4447 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4448 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4449 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4451 if (selectedNotebookGUIDs.size() > 1)
4452 setMessage(tr("Notes will be reindexed."));
4454 setMessage(tr("Note will be reindexed."));
4455 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4458 @SuppressWarnings("unused")
4459 private void deleteNote() {
4460 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4461 if (currentNote == null)
4463 if (currentNoteGuid.equals(""))
4465 String title = null;
4466 if (selectedNoteGUIDs.size() == 1)
4467 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4469 // If we are deleting non-trash notes
4470 if (currentNote.isActive()) {
4471 if (Global.verifyDelete()) {
4473 if (selectedNoteGUIDs.size() > 1) {
4474 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4477 msg = new String(tr("Delete note \"") +title +"\"?");
4479 msg = new String(tr("Delete note selected note?"));
4481 if (QMessageBox.question(this, tr("Confirmation"), msg,
4482 QMessageBox.StandardButton.Yes,
4483 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4487 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4488 selectedNoteGUIDs.add(currentNoteGuid);
4489 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4490 listManager.deleteNote(selectedNoteGUIDs.get(i));
4493 // If we are deleting from the trash.
4494 if (Global.verifyDelete()) {
4496 if (selectedNoteGUIDs.size() > 1) {
4497 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4500 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4502 msg = new String(tr("Permanently delete note selected note?"));
4504 if (QMessageBox.question(this, "Confirmation", msg,
4505 QMessageBox.StandardButton.Yes,
4506 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4510 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4511 selectedNoteGUIDs.add(currentNoteGuid);
4512 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4513 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4514 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4515 if (modelIndex != null) {
4516 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4517 String tableGuid = (String)ix.values().toArray()[0];
4518 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4519 listManager.getNoteTableModel().removeRow(j);
4524 listManager.expungeNote(selectedNoteGUIDs.get(i));
4527 currentNoteGuid = "";
4528 listManager.loadNotesIndex();
4529 noteIndexUpdated(false);
4530 refreshEvernoteNote(true);
4531 scrollToGuid(currentNoteGuid);
4532 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4535 @SuppressWarnings("unused")
4536 private void addNote() {
4537 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4538 // browserWindow.setEnabled(true);
4539 browserWindow.setReadOnly(false);
4541 Calendar currentTime = new GregorianCalendar();
4542 StringBuffer noteString = new StringBuffer(100);
4543 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4544 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4547 if (Global.overrideDefaultFont()) {
4548 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4549 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4550 noteString.append("<br clear=\"none\" />\n");
4551 noteString.append("</span>\n</font>\n");
4553 noteString.append("<br clear=\"none\" />\n");
4554 noteString.append("</en-note>");
4556 Long l = new Long(currentTime.getTimeInMillis());
4557 String randint = new String(Long.toString(l));
4559 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4561 // for the first non-archived notebook. Finally, if nothing else we
4562 // pick the first notebook in the list.
4563 String notebook = null;
4564 listManager.getNotebookIndex().get(0).getGuid();
4565 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4566 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4567 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4568 notebook = currentSelectedNotebook.text(2);
4570 boolean found = false;
4571 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4572 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4573 boolean match = false;
4574 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4575 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4577 j = listManager.getArchiveNotebookIndex().size();
4581 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4582 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4584 // Now we have a list of good notebooks, so we can look for the default
4586 for (int i=0; i<goodNotebooks.size(); i++) {
4587 if (goodNotebooks.get(i).isDefaultNotebook()) {
4588 notebook = goodNotebooks.get(i).getGuid();
4590 i = goodNotebooks.size();
4594 if (goodNotebooks.size() > 0 && !found)
4595 notebook = goodNotebooks.get(0).getGuid();
4598 notebook = listManager.getNotebookIndex().get(0).getGuid();
4601 Note newNote = new Note();
4602 newNote.setUpdateSequenceNum(0);
4603 newNote.setGuid(randint);
4604 newNote.setNotebookGuid(notebook);
4605 newNote.setTitle("");
4606 newNote.setContent(noteString.toString());
4607 newNote.setDeleted(0);
4608 newNote.setCreated(System.currentTimeMillis());
4609 newNote.setUpdated(System.currentTimeMillis());
4610 newNote.setActive(true);
4611 NoteAttributes na = new NoteAttributes();
4612 na.setLatitude(0.0);
4613 na.setLongitude(0.0);
4614 na.setAltitude(0.0);
4615 newNote.setAttributes(new NoteAttributes());
4616 newNote.setTagGuids(new ArrayList<String>());
4617 newNote.setTagNames(new ArrayList<String>());
4619 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4620 if (Global.newNoteWithSelectedTags()) {
4621 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4622 QTreeWidgetItem currentSelection;
4623 for (int i=0; i<selections.size(); i++) {
4624 currentSelection = selections.get(i);
4625 newNote.getTagGuids().add(currentSelection.text(2));
4626 newNote.getTagNames().add(currentSelection.text(0));
4630 conn.getNoteTable().addNote(newNote, true);
4631 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4632 listManager.addNote(newNote);
4633 // noteTableView.insertRow(newNote, true, -1);
4635 currentNote = newNote;
4636 currentNoteGuid = currentNote.getGuid();
4637 noteTableView.clearSelection();
4638 refreshEvernoteNote(true);
4639 listManager.countNotebookResults(listManager.getNoteIndex());
4640 browserWindow.titleLabel.setFocus();
4641 browserWindow.titleLabel.selectAll();
4642 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4644 // If the window is hidden, then we want to popup this in an external window &
4647 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4649 // Restore a note from the trash;
4650 @SuppressWarnings("unused")
4651 private void restoreNote() {
4653 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4654 selectedNoteGUIDs.add(currentNoteGuid);
4655 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4656 listManager.restoreNote(selectedNoteGUIDs.get(i));
4658 currentNoteGuid = "";
4659 listManager.loadNotesIndex();
4660 noteIndexUpdated(false);
4663 // Search a note for specific txt
4664 @SuppressWarnings("unused")
4665 private void findText() {
4667 find.setFocusOnTextField();
4669 @SuppressWarnings("unused")
4670 private void doFindText() {
4671 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4674 @SuppressWarnings("unused")
4675 private void updateNoteTitle(String guid, String title) {
4676 listManager.setNoteSynchronized(guid, false);
4678 // Signal received that note content has changed. Normally we just need the guid to remove
4679 // it from the cache.
4680 @SuppressWarnings("unused")
4681 private void invalidateNoteCache(String guid, String content) {
4682 String v = noteCache.remove(guid);
4683 // if (guid.equals(currentNoteGuid) && !noteDirty)
4684 refreshEvernoteNote(true);
4686 // Signal received that a note guid has changed
4687 @SuppressWarnings("unused")
4688 private void noteGuidChanged(String oldGuid, String newGuid) {
4689 if (noteCache.containsKey(oldGuid)) {
4690 if (!oldGuid.equals(currentNoteGuid)) {
4691 String cache = noteCache.get(oldGuid);
4692 noteCache.put(newGuid, cache);
4693 noteCache.remove(oldGuid);
4695 noteCache.remove(oldGuid);
4696 noteCache.put(newGuid, browserWindow.getContent());
4700 listManager.updateNoteGuid(oldGuid, newGuid, false);
4701 if (currentNoteGuid.equals(oldGuid)) {
4702 if (currentNote != null)
4703 currentNote.setGuid(newGuid);
4704 currentNoteGuid = newGuid;
4707 if (externalWindows.containsKey(oldGuid)) {
4708 ExternalBrowse b = externalWindows.get(oldGuid);
4709 externalWindows.remove(oldGuid);
4710 b.getBrowserWindow().getNote().setGuid(newGuid);
4711 externalWindows.put(newGuid, b);
4714 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4715 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4716 noteTableView.proxyModel.addGuid(newGuid);
4717 i=listManager.getNoteIndex().size();
4721 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4722 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4723 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4724 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4728 // Toggle the note editor button bar
4729 private void toggleEditorButtonBar() {
4730 if (browserWindow.buttonsVisible) {
4731 browserWindow.hideButtons();
4732 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4733 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4735 browserWindow.buttonsVisible = true;
4736 showEditorButtons(browserWindow);
4738 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4740 // Show editor buttons
4741 private void showEditorButtons(BrowserWindow browser) {
4742 browser.buttonLayout.setVisible(true);
4743 browser.undoAction.setVisible(false);
4745 browser.undoButton.setVisible(false);
4747 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4748 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4749 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4750 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4751 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4752 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4753 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4754 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4755 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4756 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4757 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4758 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4759 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4760 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4761 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4762 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4763 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4764 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4765 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4766 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4767 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4768 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4769 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4771 private void duplicateNote(String guid) {
4773 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4774 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4775 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4776 oldNote.setResources(resList);
4777 duplicateNote(oldNote);
4779 private void duplicateNote(Note oldNote) {
4781 // Now that we have a good notebook guid, we need to move the conflicting note
4782 // to the local notebook
4783 Calendar currentTime = new GregorianCalendar();
4784 Long l = new Long(currentTime.getTimeInMillis());
4785 String newGuid = new String(Long.toString(l));
4787 // Note newNote = oldNote.deepCopy();
4788 Note newNote = (Note)Global.deepCopy(oldNote);
4789 newNote.setUpdateSequenceNum(0);
4790 newNote.setGuid(newGuid);
4791 newNote.setDeleted(0);
4792 newNote.setActive(true);
4795 List<String> tagNames = new ArrayList<String>();
4796 List<String> tagGuids = new ArrayList<String>();;
4797 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4798 tagNames.add(oldNote.getTagNames().get(i));
4799 tagGuids.add(oldNote.getTagGuids().get(i));
4802 // Sort note Tags to make them look nice
4803 for (int i=0; i<tagNames.size()-1; i++) {
4804 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4805 String n1 = tagNames.get(i);
4806 String n2 = tagNames.get(i+1);
4807 tagNames.set(i, n2);
4808 tagNames.set(i+1, n1);
4811 newNote.setTagGuids(tagGuids);
4812 newNote.setTagNames(tagNames);
4814 // Add tag guids to note
4817 // Duplicate resources
4818 List<Resource> resList = oldNote.getResources();
4819 if (resList == null)
4820 resList = new ArrayList<Resource>();
4822 for (int i=0; i<resList.size(); i++) {
4824 while (l == prevGuid) {
4825 currentTime = new GregorianCalendar();
4826 l = new Long(currentTime.getTimeInMillis());
4829 String newResGuid = new String(Long.toString(l));
4830 resList.get(i).setNoteGuid(newGuid);
4831 resList.get(i).setGuid(newResGuid);
4832 resList.get(i).setUpdateSequenceNum(0);
4833 resList.get(i).setActive(true);
4834 conn.getNoteTable().noteResourceTable.saveNoteResource(
4835 (Resource)Global.deepCopy(resList.get(i)), true);
4837 newNote.setResources(resList);
4839 // Add note to the database
4840 listManager.addNote(newNote);
4841 conn.getNoteTable().addNote(newNote, true);
4842 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4843 noteTableView.insertRow(newNote, true, -1);
4844 currentNoteGuid = newNote.getGuid();
4845 currentNote = newNote;
4846 refreshEvernoteNote(true);
4847 listManager.countNotebookResults(listManager.getNoteIndex());
4851 @SuppressWarnings("unused")
4852 private void allNotes() {
4853 clearAttributeFilter();
4854 clearNotebookFilter();
4855 clearSavedSearchFilter();
4858 searchField.clear();
4859 if (Global.mimicEvernoteInterface) {
4860 notebookTree.selectGuid("");
4862 notebookTreeSelection();
4863 refreshEvernoteNote(true);
4866 @SuppressWarnings("unused")
4867 private void mergeNotes() {
4868 logger.log(logger.HIGH, "Merging notes");
4871 String masterGuid = null;
4872 List<String> sources = new ArrayList<String>();
4874 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4875 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4876 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4877 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4879 masterGuid = (String)ix.values().toArray()[0];
4881 sources.add((String)ix.values().toArray()[0]);
4884 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4885 logger.log(logger.EXTREME, "Children count: "+sources.size());
4886 mergeNoteContents(masterGuid, sources);
4887 currentNoteGuid = masterGuid;
4888 noteIndexUpdated(false);
4889 refreshEvernoteNote(true);
4892 private void mergeNoteContents(String targetGuid, List<String> sources) {
4893 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4894 String newContent = target.getContent();
4895 newContent = newContent.replace("</en-note>", "<br></br>");
4897 for (int i=0; i<sources.size(); i++) {
4898 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4899 if (source.isSetTitle()) {
4900 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4902 String sourceContent = source.getContent();
4903 logger.log(logger.EXTREME, "Merging contents into note");
4904 logger.log(logger.EXTREME, sourceContent);
4905 logger.log(logger.EXTREME, "End of content");
4906 int startOfNote = sourceContent.indexOf("<en-note>");
4907 sourceContent = sourceContent.substring(startOfNote+9);
4908 int endOfNote = sourceContent.indexOf("</en-note>");
4909 sourceContent = sourceContent.substring(0,endOfNote);
4910 newContent = newContent + sourceContent;
4911 logger.log(logger.EXTREME, "New note content");
4912 logger.log(logger.EXTREME, newContent);
4913 logger.log(logger.EXTREME, "End of content");
4914 for (int j=0; j<source.getResourcesSize(); j++) {
4915 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4916 Resource r = source.getResources().get(j);
4917 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4919 Calendar currentTime = new GregorianCalendar();
4920 Long l = new Long(currentTime.getTimeInMillis());
4924 while (l == prevGuid) {
4925 currentTime = new GregorianCalendar();
4926 l = new Long(currentTime.getTimeInMillis());
4928 String newResGuid = new String(Long.toString(l));
4929 newRes.setNoteGuid(targetGuid);
4930 newRes.setGuid(newResGuid);
4931 newRes.setUpdateSequenceNum(0);
4932 newRes.setActive(true);
4933 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4936 logger.log(logger.EXTREME, "Updating note");
4937 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4938 for (int i=0; i<sources.size(); i++) {
4939 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4940 listManager.deleteNote(sources.get(i));
4942 logger.log(logger.EXTREME, "Exiting merge note");
4944 // A resource within a note has had a guid change
4945 @SuppressWarnings("unused")
4946 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4947 if (oldGuid != null && !oldGuid.equals(newGuid))
4948 Global.resourceMap.put(oldGuid, newGuid);
4950 // View a thumbnail of the note
4951 public void thumbnailView() {
4953 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4954 QFile thumbnail = new QFile(thumbnailName);
4955 if (!thumbnail.exists()) {
4957 QImage img = new QImage();
4958 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4959 thumbnailViewer.setThumbnail(img);
4961 thumbnailViewer.setThumbnail(thumbnailName);
4962 if (!thumbnailViewer.isVisible())
4963 thumbnailViewer.showFullScreen();
4965 // An error happened while saving a note. Inform the user
4966 @SuppressWarnings("unused")
4967 private void saveRunnerError(String guid, String msg) {
4969 String title = "*Unknown*";
4970 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4971 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4972 title = listManager.getMasterNoteIndex().get(i).getTitle();
4973 i=listManager.getMasterNoteIndex().size();
4976 msg = "An error has happened while saving the note \"" +title+
4977 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4978 "As a result, changes to the note may not be saved properly in the database."+
4979 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4980 "\nbe lost. Please review the note to recover any critical data before restarting.";
4982 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4985 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4986 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4987 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4988 // Find an idle preview object
4989 for (int i=0; i<thumbGenerators.size(); i++) {
4990 if (thumbGenerators.get(i).mutex.tryLock()) {
4991 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4992 thumbGenerators.get(i).loadContent(guid, html, zoom);
4996 if (thumbGenerators.size() >= 1) {
4997 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5001 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5002 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5003 thumbGenerators.add(preview);
5005 if (preview.mutex.tryLock()) {
5006 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5007 preview.loadContent(guid, html, zoom);
5009 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5014 //**********************************************************
5015 //**********************************************************
5016 //* Online user actions
5017 //**********************************************************
5018 //**********************************************************
5019 private void setupOnlineMenu() {
5020 if (!Global.isConnected) {
5021 menuBar.noteOnlineHistoryAction.setEnabled(false);
5022 menuBar.selectiveSyncAction.setEnabled(false);
5025 menuBar.noteOnlineHistoryAction.setEnabled(true);
5026 menuBar.selectiveSyncAction.setEnabled(true);
5029 @SuppressWarnings("unused")
5030 private void viewNoteHistory() {
5031 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5033 if (currentNote.getUpdateSequenceNum() == 0) {
5034 setMessage(tr("Note has never been synchronized."));
5035 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5039 setMessage(tr("Getting Note History"));
5041 Note currentOnlineNote = null;
5044 if (Global.isPremium())
5045 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5047 versions = new ArrayList<NoteVersionId>();
5048 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5049 } catch (EDAMUserException e) {
5050 setMessage("EDAMUserException: " +e.getMessage());
5052 } catch (EDAMSystemException e) {
5053 setMessage("EDAMSystemException: " +e.getMessage());
5055 } catch (EDAMNotFoundException e) {
5056 setMessage(tr("Note not found on server."));
5057 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
5059 } catch (TException e) {
5060 setMessage("EDAMTransactionException: " +e.getMessage());
5064 // If we've gotten this far, we have a good note.
5065 if (historyWindow == null) {
5066 historyWindow = new OnlineNoteHistory(logger, conn);
5067 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5068 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5069 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5071 historyWindow.historyCombo.clear();
5073 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5074 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5076 historyWindow.setCurrent(isDirty);
5078 loadHistoryWindowContent(currentOnlineNote);
5079 historyWindow.load(versions);
5080 setMessage(tr("History retrieved"));
5082 historyWindow.exec();
5084 private Note reloadHistoryWindow(String selection) {
5086 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5087 String dateTimeFormat = new String(fmt);
5088 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5092 for (int i=0; i<versions.size(); i++) {
5093 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5094 if (versionDate.toString().equals(selection))
5098 if (index > -1 || selection.indexOf("Current") > -1) {
5099 Note historyNote = null;
5102 usn = versions.get(index).getUpdateSequenceNum();
5103 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5105 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5106 } catch (EDAMUserException e) {
5107 setMessage("EDAMUserException: " +e.getMessage());
5110 } catch (EDAMSystemException e) {
5111 setMessage("EDAMSystemException: " +e.getMessage());
5114 } catch (EDAMNotFoundException e) {
5115 setMessage("EDAMNotFoundException: " +e.getMessage());
5118 } catch (TException e) {
5119 setMessage("EDAMTransactionException: " +e.getMessage());
5125 if (historyNote != null)
5126 historyWindow.setContent(historyNote);
5132 private void loadHistoryWindowContent(Note note) {
5133 note.setUpdateSequenceNum(0);
5134 historyWindow.setContent(note);
5136 @SuppressWarnings("unused")
5137 private void restoreHistoryNoteAsNew() {
5138 setMessage(tr("Restoring as new note."));
5139 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5140 setMessage(tr("Note has been restored as a new note."));
5142 @SuppressWarnings("unused")
5143 private void restoreHistoryNote() {
5144 setMessage(tr("Restoring note."));
5145 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5146 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5149 for (int i=0; i<n.getResourcesSize(); i++) {
5150 n.getResources().get(i).setActive(true);
5151 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5153 listManager.addNote(n);
5154 conn.getNoteTable().addNote(n, true);
5155 refreshEvernoteNote(true);
5156 setMessage(tr("Note has been restored."));
5158 @SuppressWarnings("unused")
5159 private void setupSelectiveSync() {
5161 // Get a list of valid notebooks
5162 List<Notebook> notebooks = null;
5163 List<Tag> tags = null;
5164 List<LinkedNotebook> linkedNotebooks = null;
5166 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5167 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5168 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5169 } catch (EDAMUserException e) {
5170 setMessage("EDAMUserException: " +e.getMessage());
5172 } catch (EDAMSystemException e) {
5173 setMessage("EDAMSystemException: " +e.getMessage());
5175 } catch (TException e) {
5176 setMessage("EDAMTransactionException: " +e.getMessage());
5178 } catch (EDAMNotFoundException e) {
5179 setMessage("EDAMNotFoundException: " +e.getMessage());
5183 // Split up notebooks into synchronized & non-synchronized
5184 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5185 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5187 for (int i=notebooks.size()-1; i>=0; i--) {
5188 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5189 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5190 ignoredBooks.add(notebooks.get(i));
5191 j=dbIgnoredNotebooks.size();
5196 // split up tags into synchronized & non-synchronized
5197 List<Tag> ignoredTags = new ArrayList<Tag>();
5198 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5200 for (int i=tags.size()-1; i>=0; i--) {
5201 for (int j=0; j<dbIgnoredTags.size(); j++) {
5202 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5203 ignoredTags.add(tags.get(i));
5204 j=dbIgnoredTags.size();
5209 // split up linked notebooks into synchronized & non-synchronized
5210 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5211 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5212 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5213 String notebookGuid = linkedNotebooks.get(i).getGuid();
5214 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5215 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5216 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5217 j=dbIgnoredLinkedNotebooks.size();
5222 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5224 if (!ignore.okClicked())
5229 // Clear out old notebooks & add the new ones
5230 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5231 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5232 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5235 List<String> newNotebooks = new ArrayList<String>();
5236 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5237 String text = ignore.getIgnoredBookList().takeItem(i).text();
5238 for (int j=0; j<notebooks.size(); j++) {
5239 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5240 Notebook n = notebooks.get(j);
5241 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5243 newNotebooks.add(n.getGuid());
5248 // Clear out old tags & add new ones
5249 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5250 for (int i=0; i<oldIgnoreTags.size(); i++) {
5251 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5254 List<String> newTags = new ArrayList<String>();
5255 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5256 String text = ignore.getIgnoredTagList().takeItem(i).text();
5257 for (int j=0; j<tags.size(); j++) {
5258 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5259 Tag t = tags.get(j);
5260 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5261 newTags.add(t.getGuid());
5267 // Clear out old tags & add new ones
5268 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5269 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5270 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5273 List<String> newLinked = new ArrayList<String>();
5274 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5275 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5276 for (int j=0; j<linkedNotebooks.size(); j++) {
5277 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5278 LinkedNotebook t = linkedNotebooks.get(j);
5279 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5280 newLinked.add(t.getGuid());
5281 j=linkedNotebooks.size();
5286 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5292 //**********************************************************
5293 //**********************************************************
5294 //* XML Modifying methods
5295 //**********************************************************
5296 //**********************************************************
5297 // An error has happended fetching a resource. let the user know
5298 private void resourceErrorMessage() {
5302 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5303 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5304 "In a perfect world this wouldn't happen, but it has.\n" +
5305 "It is embarasing when a program like me, designed to save all your\n"+
5306 "precious data, has a problem finding data.\n\n" +
5307 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5308 "In the mean time, I'm not going to let you make changes to this note.\n" +
5309 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5310 "this note on the Evernote servers. Sorry."+
5311 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5313 browserWindow.setReadOnly(true);
5320 //**********************************************************
5321 //**********************************************************
5323 //**********************************************************
5324 //**********************************************************
5325 // We should now do a sync with Evernote
5326 private void syncTimer() {
5327 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5328 syncRunner.syncNeeded = true;
5329 syncRunner.disableUploads = Global.disableUploads;
5331 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5333 private void syncStart() {
5334 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5336 if (!syncRunning && Global.isConnected) {
5337 syncRunner.setConnected(true);
5338 syncRunner.setKeepRunning(Global.keepRunning);
5339 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5341 if (syncThreadsReady > 0) {
5342 thumbnailRunner.interrupt = true;
5343 saveNoteIndexWidth();
5344 saveNoteColumnPositions();
5345 if (syncRunner.addWork("SYNC")) {
5347 syncRunner.syncNeeded = true;
5352 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5354 @SuppressWarnings("unused")
5355 private void syncThreadComplete(Boolean refreshNeeded) {
5356 setMessage(tr("Finalizing Synchronization"));
5358 syncRunning = false;
5359 syncRunner.syncNeeded = false;
5360 synchronizeAnimationTimer.stop();
5361 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5363 if (currentNote == null) {
5364 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5366 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5367 noteIndexUpdated(false);
5368 noteTableView.selectionModel().blockSignals(true);
5369 scrollToGuid(currentNoteGuid);
5370 noteTableView.selectionModel().blockSignals(false);
5371 refreshEvernoteNote(false);
5372 scrollToGuid(currentNoteGuid);
5374 if (!syncRunner.error)
5375 setMessage(tr("Synchronization Complete"));
5377 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5378 logger.log(logger.MEDIUM, "Sync complete.");
5380 public void saveUploadAmount(long t) {
5381 Global.saveUploadAmount(t);
5383 public void saveUserInformation(User user) {
5384 Global.saveUserInformation(user);
5386 public void saveEvernoteUpdateCount(int i) {
5387 Global.saveEvernoteUpdateCount(i);
5389 public void refreshLists() {
5390 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5392 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5393 tagIndexUpdated(true);
5394 notebookIndexUpdated();
5395 savedSearchIndexUpdated();
5396 listManager.loadNotesIndex();
5398 noteTableView.selectionModel().blockSignals(true);
5399 noteIndexUpdated(true);
5400 noteTableView.selectionModel().blockSignals(false);
5401 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5405 @SuppressWarnings("unused")
5406 private void authTimer() {
5407 Calendar cal = Calendar.getInstance();
5409 // If we are not connected let's get out of here
5410 if (!Global.isConnected)
5413 // If this is the first time through, then we need to set this
5414 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5415 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5417 // long now = new Date().getTime();
5418 // if (now > Global.authRefreshTime && Global.isConnected) {
5419 syncRunner.authRefreshNeeded = true;
5423 @SuppressWarnings("unused")
5424 private void authRefreshComplete(boolean goodSync) {
5425 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5426 Global.isConnected = syncRunner.isConnected;
5428 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5429 authTimer.start(1000*60*15);
5430 logger.log(logger.LOW, "Authentication token has been renewed");
5431 // setMessage("Authentication token has been renewed.");
5433 authTimer.start(1000*60*5);
5434 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5435 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5437 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5441 @SuppressWarnings("unused")
5442 private synchronized void indexTimer() {
5443 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5446 if (!indexDisabled && indexRunner.idle) {
5447 thumbnailRunner.interrupt = true;
5448 indexRunner.addWork("SCAN");
5450 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5453 @SuppressWarnings("unused")
5454 private void indexStarted() {
5455 setMessage(tr("Indexing notes"));
5457 @SuppressWarnings("unused")
5458 private void indexComplete() {
5459 setMessage(tr("Index complete"));
5461 @SuppressWarnings("unused")
5462 private synchronized void toggleNoteIndexing() {
5463 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5464 indexDisabled = !indexDisabled;
5466 setMessage(tr("Indexing is now enabled."));
5468 setMessage(tr("Indexing is now disabled."));
5469 menuBar.disableIndexing.setChecked(indexDisabled);
5470 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5473 @SuppressWarnings("unused")
5474 private void threadMonitorCheck() {
5479 alive = listManager.threadCheck(Global.tagCounterThreadId);
5482 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5483 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5484 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5485 disableTagThreadCheck = true;
5490 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5492 notebookThreadDeadCount++;
5493 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5494 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5495 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5496 disableNotebookThreadCheck=true;
5499 notebookThreadDeadCount=0;
5501 alive = listManager.threadCheck(Global.trashCounterThreadId);
5504 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5505 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5506 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5507 disableTrashThreadCheck = true;
5512 alive = listManager.threadCheck(Global.saveThreadId);
5514 saveThreadDeadCount++;
5515 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5516 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5517 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5518 disableSaveThreadCheck = true;
5521 saveThreadDeadCount=0;
5523 if (!syncThread.isAlive()) {
5524 syncThreadDeadCount++;
5525 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5526 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5527 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5528 disableSyncThreadCheck = true;
5531 syncThreadDeadCount=0;
5533 if (!indexThread.isAlive()) {
5534 indexThreadDeadCount++;
5535 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5536 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5537 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5538 disableIndexThreadCheck = true;
5541 indexThreadDeadCount=0;
5546 private void thumbnailTimer() {
5547 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5548 thumbnailRunner.addWork("SCAN");
5552 //**************************************************
5553 //* Backup & Restore
5554 //**************************************************
5555 @SuppressWarnings("unused")
5556 private void databaseBackup() {
5557 QFileDialog fd = new QFileDialog(this);
5558 fd.setFileMode(FileMode.AnyFile);
5559 fd.setConfirmOverwrite(true);
5560 fd.setWindowTitle(tr("Backup Database"));
5561 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5562 fd.setAcceptMode(AcceptMode.AcceptSave);
5563 if (saveLastPath == null || saveLastPath.equals(""))
5564 fd.setDirectory(System.getProperty("user.home"));
5566 fd.setDirectory(saveLastPath);
5567 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5573 saveLastPath = fd.selectedFiles().get(0);
5574 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5575 setMessage(tr("Backing up database"));
5577 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5579 ExportData noteWriter = new ExportData(conn, true);
5580 String fileName = fd.selectedFiles().get(0);
5582 if (!fileName.endsWith(".nnex"))
5583 fileName = fileName +".nnex";
5584 noteWriter.exportData(fileName);
5585 setMessage(tr("Database backup completed."));
5590 @SuppressWarnings("unused")
5591 private void databaseRestore() {
5592 if (QMessageBox.question(this, tr("Confirmation"),
5593 tr("This is used to restore a database from backups.\n" +
5594 "It is HIGHLY recommened that this only be used to populate\n" +
5595 "an empty database. Restoring into a database that\n already has data" +
5596 " can cause problems.\n\nAre you sure you want to continue?"),
5597 QMessageBox.StandardButton.Yes,
5598 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5603 QFileDialog fd = new QFileDialog(this);
5604 fd.setFileMode(FileMode.ExistingFile);
5605 fd.setConfirmOverwrite(true);
5606 fd.setWindowTitle(tr("Restore Database"));
5607 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5608 fd.setAcceptMode(AcceptMode.AcceptOpen);
5609 if (saveLastPath == null || saveLastPath.equals(""))
5610 fd.setDirectory(System.getProperty("user.home"));
5612 fd.setDirectory(saveLastPath);
5613 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5619 saveLastPath = fd.selectedFiles().get(0);
5620 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5622 setMessage(tr("Restoring database"));
5623 ImportData noteReader = new ImportData(conn, true);
5624 noteReader.importData(fd.selectedFiles().get(0));
5626 if (noteReader.lastError != 0) {
5627 setMessage(noteReader.getErrorMessage());
5628 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5633 listManager.loadNoteTitleColors();
5635 refreshEvernoteNote(true);
5636 setMessage(tr("Database has been restored."));
5639 @SuppressWarnings("unused")
5640 private void exportNotes() {
5641 QFileDialog fd = new QFileDialog(this);
5642 fd.setFileMode(FileMode.AnyFile);
5643 fd.setConfirmOverwrite(true);
5644 fd.setWindowTitle(tr("Backup Database"));
5645 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5646 fd.setAcceptMode(AcceptMode.AcceptSave);
5647 fd.setDirectory(System.getProperty("user.home"));
5648 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5654 setMessage(tr("Exporting Notes"));
5657 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5658 selectedNoteGUIDs.add(currentNoteGuid);
5660 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5661 String fileName = fd.selectedFiles().get(0);
5663 if (!fileName.endsWith(".nnex"))
5664 fileName = fileName +".nnex";
5665 noteWriter.exportData(fileName);
5666 setMessage(tr("Export completed."));
5672 @SuppressWarnings("unused")
5673 private void importNotes() {
5674 QFileDialog fd = new QFileDialog(this);
5675 fd.setFileMode(FileMode.ExistingFile);
5676 fd.setConfirmOverwrite(true);
5677 fd.setWindowTitle(tr("Import Notes"));
5678 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5679 fd.setAcceptMode(AcceptMode.AcceptOpen);
5680 if (saveLastPath == null || saveLastPath.equals(""))
5681 fd.setDirectory(System.getProperty("user.home"));
5683 fd.setDirectory(saveLastPath);
5684 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5690 setMessage("Importing Notes");
5693 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5694 selectedNoteGUIDs.add(currentNoteGuid);
5696 ImportData noteReader = new ImportData(conn, false);
5697 String fileName = fd.selectedFiles().get(0);
5698 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5700 if (!fileName.endsWith(".nnex"))
5701 fileName = fileName +".nnex";
5702 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5703 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5705 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5707 noteReader.importData(fileName);
5709 if (noteReader.lastError != 0) {
5710 setMessage(noteReader.getErrorMessage());
5711 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5716 listManager.loadNoteTitleColors();
5718 refreshEvernoteNote(false);
5719 setMessage(tr("Notes have been imported."));
5722 setMessage("Import completed.");
5729 //**************************************************
5730 //* Duplicate a note
5731 //**************************************************
5732 @SuppressWarnings("unused")
5733 private void duplicateNote() {
5735 duplicateNote(currentNoteGuid);
5740 //**************************************************
5742 //**************************************************
5743 public void setupFolderImports() {
5744 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5746 if (importKeepWatcher == null)
5747 importKeepWatcher = new QFileSystemWatcher();
5748 if (importDeleteWatcher == null) {
5749 importDeleteWatcher = new QFileSystemWatcher();
5750 for (int i=0; i<records.size(); i++) {
5751 if (!records.get(i).keep)
5752 folderImportDelete(records.get(i).folder);
5758 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5759 for (int i=0; i<records.size(); i++) {
5760 if (records.get(i).keep)
5761 importKeepWatcher.addPath(records.get(i).folder);
5763 importDeleteWatcher.addPath(records.get(i).folder);
5766 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5767 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5769 // Look at the files already there so we don't import them again if a new file is created
5770 if (importedFiles == null) {
5771 importedFiles = new ArrayList<String>();
5772 for (int j=0; j<records.size(); j++) {
5773 QDir dir = new QDir(records.get(j).folder);
5774 List<QFileInfo> list = dir.entryInfoList();
5775 for (int k=0; k<list.size(); k++) {
5776 if (list.get(k).isFile())
5777 importedFiles.add(list.get(k).absoluteFilePath());
5782 public void folderImport() {
5783 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5784 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5786 if (!dialog.okClicked())
5789 // We have some sort of update.
5790 if (importKeepWatcher.directories().size() > 0)
5791 importKeepWatcher.removePaths(importKeepWatcher.directories());
5792 if (importDeleteWatcher.directories().size() > 0)
5793 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5795 conn.getWatchFolderTable().expungeAll();
5796 // Start building from the table
5797 for (int i=0; i<dialog.table.rowCount(); i++) {
5798 QTableWidgetItem item = dialog.table.item(i, 0);
5799 String dir = item.text();
5800 item = dialog.table.item(i, 1);
5801 String notebook = item.text();
5802 item = dialog.table.item(i, 2);
5804 if (item.text().equalsIgnoreCase("Keep"))
5809 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5810 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5812 setupFolderImports();
5815 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5817 String whichOS = System.getProperty("os.name");
5818 if (whichOS.contains("Windows"))
5819 dirName = dirName.replace('/','\\');
5821 FileImporter importer = new FileImporter(logger, conn);
5823 QDir dir = new QDir(dirName);
5824 List<QFileInfo> list = dir.entryInfoList();
5825 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5827 for (int i=0; i<list.size(); i++){
5829 boolean redundant = false;
5830 // Check if we've already imported this one or if it existed before
5831 for (int j=0; j<importedFiles.size(); j++) {
5832 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5837 importer.setFileInfo(list.get(i));
5838 importer.setFileName(list.get(i).absoluteFilePath());
5841 if (list.get(i).isFile() && importer.isValidType()) {
5843 if (!importer.importFile()) {
5844 // If we can't get to the file, it is probably locked. We'll try again later.
5845 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5846 importFilesKeep.add(list.get(i).absoluteFilePath());
5850 Note newNote = importer.getNote();
5851 newNote.setNotebookGuid(notebook);
5852 newNote.setTitle(dir.at(i));
5853 listManager.addNote(newNote);
5854 conn.getNoteTable().addNote(newNote, true);
5855 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5856 noteTableView.insertRow(newNote, true, -1);
5857 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5858 listManager.countNotebookResults(listManager.getNoteIndex());
5859 importedFiles.add(list.get(i).absoluteFilePath());
5867 public void folderImportDelete(String dirName) {
5869 String whichOS = System.getProperty("os.name");
5870 if (whichOS.contains("Windows"))
5871 dirName = dirName.replace('/','\\');
5873 FileImporter importer = new FileImporter(logger, conn);
5874 QDir dir = new QDir(dirName);
5875 List<QFileInfo> list = dir.entryInfoList();
5876 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5878 for (int i=0; i<list.size(); i++){
5879 importer.setFileInfo(list.get(i));
5880 importer.setFileName(list.get(i).absoluteFilePath());
5882 if (list.get(i).isFile() && importer.isValidType()) {
5884 if (!importer.importFile()) {
5885 // If we can't get to the file, it is probably locked. We'll try again later.
5886 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5887 importFilesKeep.add(list.get(i).absoluteFilePath());
5891 Note newNote = importer.getNote();
5892 newNote.setNotebookGuid(notebook);
5893 newNote.setTitle(dir.at(i));
5894 listManager.addNote(newNote);
5895 conn.getNoteTable().addNote(newNote, true);
5896 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5897 noteTableView.insertRow(newNote, true, -1);
5898 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5899 listManager.countNotebookResults(listManager.getNoteIndex());
5900 dir.remove(dir.at(i));
5906 //**************************************************
5908 //**************************************************
5909 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5910 logger.log(logger.HIGH, "Entering exernalFileEdited");
5912 // Strip URL prefix and base dir path
5913 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5914 String name = fileName.replace(dPath, "");
5915 int pos = name.lastIndexOf('.');
5918 guid = guid.substring(0,pos);
5920 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5922 guid = name.substring(0, pos);
5925 QFile file = new QFile(fileName);
5926 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5927 // If we can't get to the file, it is probably locked. We'll try again later.
5928 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5929 externalFiles.add(fileName);
5932 QByteArray binData = file.readAll();
5934 if (binData.size() == 0) {
5935 // If we can't get to the file, it is probably locked. We'll try again later.
5936 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5937 externalFiles.add(fileName);
5941 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5943 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5944 if (r == null || r.getData() == null || r.getData().getBody() == null)
5946 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5947 MessageDigest md = MessageDigest.getInstance("MD5");
5948 md.update(binData.toByteArray());
5949 byte[] hash = md.digest();
5950 String newHash = Global.byteArrayToHexString(hash);
5951 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5952 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5954 if (externalWindows.containsKey(r.getNoteGuid())) {
5955 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5956 r.getGuid(), oldHash, newHash);
5958 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5959 Data data = r.getData();
5960 data.setBody(binData.toByteArray());
5961 data.setBodyHash(hash);
5962 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5964 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5966 if (r.getNoteGuid().equals(currentNoteGuid)) {
5967 QWebSettings.setMaximumPagesInCache(0);
5968 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5969 refreshEvernoteNote(true);
5970 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5973 if (externalWindows.containsKey(r.getNoteGuid())) {
5974 QWebSettings.setMaximumPagesInCache(0);
5975 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5976 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5980 logger.log(logger.HIGH, "Exiting externalFielEdited");
5982 // This is a timer event that tries to save any external files that were edited. This
5983 // is only needed if we couldn't save a file earlier.
5984 public void externalFileEditedSaver() {
5985 for (int i=externalFiles.size()-1; i>=0; i--) {
5987 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5988 externalFileEdited(externalFiles.get(i));
5989 externalFiles.remove(i);
5990 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5992 for (int i=0; i<importFilesKeep.size(); i++) {
5994 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5995 folderImportKeep(importFilesKeep.get(i));
5996 importFilesKeep.remove(i);
5997 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5999 for (int i=0; i<importFilesDelete.size(); i++) {
6000 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6001 folderImportDelete(importFilesDelete.get(i));
6002 importFilesDelete.remove(i);
6009 // If an attachment on the current note was edited, we need to update the current notes's hash
6010 // Update a note content's hash. This happens if a resource is edited outside of NN
6011 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6012 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6014 for (;position>-1;) {
6015 endPos = browser.getContent().indexOf(">", position+1);
6016 String oldSegment = browser.getContent().substring(position,endPos);
6017 int hashPos = oldSegment.indexOf("hash=\"");
6018 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6019 String hash = oldSegment.substring(hashPos+6, hashEnd);
6020 if (hash.equalsIgnoreCase(oldHash)) {
6021 String newSegment = oldSegment.replace(oldHash, newHash);
6022 String content = browser.getContent().substring(0,position) +
6024 browser.getContent().substring(endPos);
6025 browser.getBrowser().setContent(new QByteArray(content));;
6028 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6033 //*************************************************
6034 //* Minimize to tray
6035 //*************************************************
6037 public void changeEvent(QEvent e) {
6038 if (e.type() == QEvent.Type.WindowStateChange) {
6039 if (isMinimized() && Global.showTrayIcon()) {
6041 QTimer.singleShot(10, this, "hide()");
6045 windowMaximized = true;
6047 windowMaximized = false;
6051 //*************************************************
6052 //* Check database userid & passwords
6053 //*************************************************
6054 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6055 Connection connection;
6058 Class.forName("org.h2.Driver");
6059 } catch (ClassNotFoundException e1) {
6060 e1.printStackTrace();
6065 String passwordString = null;
6066 if (cypherPassword==null || cypherPassword.trim().equals(""))
6067 passwordString = userPassword;
6069 passwordString = cypherPassword+" "+userPassword;
6070 connection = DriverManager.getConnection(url,userid,passwordString);
6071 } catch (SQLException e) {
6076 } catch (SQLException e) {
6077 e.printStackTrace();
6083 //*************************************************
6084 // Block the program. This is used for things
6085 // like async web calls.
6086 //*************************************************
6087 @SuppressWarnings("unused")
6088 private void blockApplication(BrowserWindow b) {
6089 // Block all signals
6093 blockTimer = new QTimer();
6094 blockTimer.setSingleShot(true);
6095 blockTimer.setInterval(15000);
6096 blockTimer.timeout.connect(this, "unblockApplication()");
6101 @SuppressWarnings("unused")
6102 private void unblockApplication() {
6104 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6105 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6106 blockingWindow.unblockTime = -1;
6107 blockingWindow.awaitingHttpResponse = false;
6109 blockingWindow = null;
6110 blockSignals(false);