2 * This file is part of NeverNote
3 * Copyright 2009 Randy Baumgarte
5 * This file may be licensed under the terms of of the
6 * GNU General Public License Version 2 (the ``GPL'').
8 * Software distributed under the License is distributed
9 * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either
10 * express or implied. See the GPL for the specific language
11 * governing rights and limitations.
13 * You should have received a copy of the GPL along with this
14 * program. If not, go to http://www.gnu.org/licenses/gpl.html
15 * or write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 package cx.fbn.nevernote;
20 import java.awt.Desktop;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.net.Authenticator;
25 import java.net.PasswordAuthentication;
26 import java.security.MessageDigest;
27 import java.security.NoSuchAlgorithmException;
28 import java.sql.Connection;
29 import java.sql.DriverManager;
30 import java.sql.SQLException;
31 import java.sql.Statement;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Collection;
36 import java.util.Collections;
37 import java.util.Comparator;
38 import java.util.Date;
39 import java.util.GregorianCalendar;
40 import java.util.HashMap;
41 import java.util.Iterator;
42 import java.util.List;
43 import java.util.SortedMap;
44 import java.util.Vector;
46 import org.apache.log4j.Level;
47 import org.apache.log4j.Logger;
48 import org.apache.thrift.TException;
49 import org.h2.tools.ChangeFileEncryption;
51 import com.evernote.edam.error.EDAMNotFoundException;
52 import com.evernote.edam.error.EDAMSystemException;
53 import com.evernote.edam.error.EDAMUserException;
54 import com.evernote.edam.notestore.NoteFilter;
55 import com.evernote.edam.notestore.NoteVersionId;
56 import com.evernote.edam.type.Data;
57 import com.evernote.edam.type.LinkedNotebook;
58 import com.evernote.edam.type.Note;
59 import com.evernote.edam.type.NoteAttributes;
60 import com.evernote.edam.type.Notebook;
61 import com.evernote.edam.type.Publishing;
62 import com.evernote.edam.type.QueryFormat;
63 import com.evernote.edam.type.Resource;
64 import com.evernote.edam.type.SavedSearch;
65 import com.evernote.edam.type.Tag;
66 import com.evernote.edam.type.User;
67 import com.trolltech.qt.QThread;
68 import com.trolltech.qt.core.QByteArray;
69 import com.trolltech.qt.core.QDateTime;
70 import com.trolltech.qt.core.QDir;
71 import com.trolltech.qt.core.QEvent;
72 import com.trolltech.qt.core.QFile;
73 import com.trolltech.qt.core.QFileInfo;
74 import com.trolltech.qt.core.QFileSystemWatcher;
75 import com.trolltech.qt.core.QIODevice;
76 import com.trolltech.qt.core.QIODevice.OpenModeFlag;
77 import com.trolltech.qt.core.QLocale;
78 import com.trolltech.qt.core.QModelIndex;
79 import com.trolltech.qt.core.QSize;
80 import com.trolltech.qt.core.QTemporaryFile;
81 import com.trolltech.qt.core.QTextCodec;
82 import com.trolltech.qt.core.QThreadPool;
83 import com.trolltech.qt.core.QTimer;
84 import com.trolltech.qt.core.QTranslator;
85 import com.trolltech.qt.core.QUrl;
86 import com.trolltech.qt.core.Qt;
87 import com.trolltech.qt.core.Qt.BGMode;
88 import com.trolltech.qt.core.Qt.ItemDataRole;
89 import com.trolltech.qt.core.Qt.SortOrder;
90 import com.trolltech.qt.core.Qt.WidgetAttribute;
91 import com.trolltech.qt.gui.QAbstractItemView;
92 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
93 import com.trolltech.qt.gui.QAction;
94 import com.trolltech.qt.gui.QApplication;
95 import com.trolltech.qt.gui.QCloseEvent;
96 import com.trolltech.qt.gui.QColor;
97 import com.trolltech.qt.gui.QComboBox;
98 import com.trolltech.qt.gui.QComboBox.InsertPolicy;
99 import com.trolltech.qt.gui.QCursor;
100 import com.trolltech.qt.gui.QDesktopServices;
101 import com.trolltech.qt.gui.QDialog;
102 import com.trolltech.qt.gui.QFileDialog;
103 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
104 import com.trolltech.qt.gui.QFileDialog.FileMode;
105 import com.trolltech.qt.gui.QGridLayout;
106 import com.trolltech.qt.gui.QHBoxLayout;
107 import com.trolltech.qt.gui.QIcon;
108 import com.trolltech.qt.gui.QImage;
109 import com.trolltech.qt.gui.QKeySequence;
110 import com.trolltech.qt.gui.QLabel;
111 import com.trolltech.qt.gui.QMainWindow;
112 import com.trolltech.qt.gui.QMenu;
113 import com.trolltech.qt.gui.QMessageBox;
114 import com.trolltech.qt.gui.QMessageBox.StandardButton;
115 import com.trolltech.qt.gui.QPainter;
116 import com.trolltech.qt.gui.QPalette.ColorRole;
117 import com.trolltech.qt.gui.QPixmap;
118 import com.trolltech.qt.gui.QPrintDialog;
119 import com.trolltech.qt.gui.QPrinter;
120 import com.trolltech.qt.gui.QShortcut;
121 import com.trolltech.qt.gui.QSizePolicy;
122 import com.trolltech.qt.gui.QSizePolicy.Policy;
123 import com.trolltech.qt.gui.QSpinBox;
124 import com.trolltech.qt.gui.QSplashScreen;
125 import com.trolltech.qt.gui.QSplitter;
126 import com.trolltech.qt.gui.QStatusBar;
127 import com.trolltech.qt.gui.QSystemTrayIcon;
128 import com.trolltech.qt.gui.QTableWidgetItem;
129 import com.trolltech.qt.gui.QTextEdit;
130 import com.trolltech.qt.gui.QToolBar;
131 import com.trolltech.qt.gui.QTreeWidgetItem;
132 import com.trolltech.qt.network.QNetworkAccessManager;
133 import com.trolltech.qt.network.QNetworkReply;
134 import com.trolltech.qt.network.QNetworkRequest;
135 import com.trolltech.qt.webkit.QWebPage.WebAction;
136 import com.trolltech.qt.webkit.QWebSettings;
138 import cx.fbn.nevernote.config.InitializationException;
139 import cx.fbn.nevernote.config.StartupConfig;
140 import cx.fbn.nevernote.dialog.AccountDialog;
141 import cx.fbn.nevernote.dialog.ConfigDialog;
142 import cx.fbn.nevernote.dialog.DBEncryptDialog;
143 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
144 import cx.fbn.nevernote.dialog.DatabaseStatus;
145 import cx.fbn.nevernote.dialog.FindDialog;
146 import cx.fbn.nevernote.dialog.IgnoreSync;
147 import cx.fbn.nevernote.dialog.LogFileDialog;
148 import cx.fbn.nevernote.dialog.LoginDialog;
149 import cx.fbn.nevernote.dialog.NotebookArchive;
150 import cx.fbn.nevernote.dialog.NotebookEdit;
151 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
152 import cx.fbn.nevernote.dialog.PublishNotebook;
153 import cx.fbn.nevernote.dialog.SavedSearchEdit;
154 import cx.fbn.nevernote.dialog.SetIcon;
155 import cx.fbn.nevernote.dialog.ShareNotebook;
156 import cx.fbn.nevernote.dialog.StackNotebook;
157 import cx.fbn.nevernote.dialog.TagEdit;
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.TableView;
171 import cx.fbn.nevernote.gui.TagTreeWidget;
172 import cx.fbn.nevernote.gui.Thumbnailer;
173 import cx.fbn.nevernote.gui.TrashTreeWidget;
174 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
175 import cx.fbn.nevernote.sql.DatabaseConnection;
176 import cx.fbn.nevernote.sql.WatchFolderRecord;
177 import cx.fbn.nevernote.threads.IndexRunner;
178 import cx.fbn.nevernote.threads.SyncRunner;
179 import cx.fbn.nevernote.threads.ThumbnailRunner;
180 import cx.fbn.nevernote.utilities.AESEncrypter;
181 import cx.fbn.nevernote.utilities.ApplicationLogger;
182 import cx.fbn.nevernote.utilities.FileImporter;
183 import cx.fbn.nevernote.utilities.FileUtils;
184 import cx.fbn.nevernote.utilities.ListManager;
185 import cx.fbn.nevernote.utilities.SyncTimes;
186 import cx.fbn.nevernote.xml.ExportData;
187 import cx.fbn.nevernote.xml.ImportData;
188 import cx.fbn.nevernote.xml.NoteFormatter;
191 public class NeverNote extends QMainWindow{
193 QStatusBar statusBar; // Application status bar
195 DatabaseConnection conn;
197 MainMenuBar menuBar; // Main menu bar
198 FindDialog find; // Text search in note dialog
199 List<String> emitLog; // Messages displayed in the status bar;
200 QSystemTrayIcon trayIcon; // little tray icon
201 QMenu trayMenu; // System tray menu
202 QAction trayExitAction; // Exit the application
203 QAction trayShowAction; // toggle the show/hide action
204 QAction trayAddNoteAction; // Add a note from the system tray
205 QNetworkAccessManager versionChecker; // Used when checking for new versions
207 NotebookTreeWidget notebookTree; // List of notebooks
208 AttributeTreeWidget attributeTree; // List of note attributes
209 TagTreeWidget tagTree; // list of user created tags
210 SavedSearchTreeWidget savedSearchTree; // list of saved searches
211 TrashTreeWidget trashTree; // Trashcan
212 TableView noteTableView; // List of notes (the widget).
214 public BrowserWindow browserWindow; // Window containing browser & labels
215 public QToolBar toolBar; // The tool bar under the menu
216 QComboBox searchField; // search filter bar on the toolbar;
217 QShortcut searchShortcut; // Shortcut to search bar
218 boolean searchPerformed = false; // Search was done?
219 QuotaProgressBar quotaBar; // The current quota usage
221 ApplicationLogger logger;
222 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
223 List<String> selectedTagGUIDs; // List of selected tag GUIDs
224 List<String> selectedNoteGUIDs; // List of selected notes
225 String selectedSavedSearchGUID; // Currently selected saved searches
226 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
228 NoteFilter filter; // Note filter
229 String currentNoteGuid; // GUID of the current note
230 Note currentNote; // The currently viewed note
231 boolean noteDirty; // Has the note been changed?
232 boolean inkNote; // if this is an ink note, it is read only
233 boolean readOnly; // Is this note read-only?
236 ListManager listManager; // DB runnable task
238 List<QTemporaryFile> tempFiles; // Array of temporary files;
240 QTimer indexTimer; // timer to start the index thread
241 IndexRunner indexRunner; // thread to index notes
244 QTimer syncTimer; // Sync on an interval
245 QTimer syncDelayTimer; // Sync delay to free up database
246 SyncRunner syncRunner; // thread to do a sync.
247 QThread syncThread; // Thread which talks to evernote
248 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
249 QThread thumbnailThread; // Thread that generates pretty pictures
250 QTimer saveTimer; // Timer to save note contents
252 QTimer authTimer; // Refresh authentication
253 QTimer externalFileSaveTimer; // Save files altered externally
254 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
255 List<String> externalFiles; // External files to save later
256 List<String> importFilesKeep; // Auto-import files to save later
257 List<String> importFilesDelete; // Auto-import files to save later
259 int indexTime; // how often to try and index
260 boolean indexRunning; // Is indexing running?
261 boolean indexDisabled; // Is indexing disabled?
263 int syncThreadsReady; // number of sync threads that are free
264 int syncTime; // Sync interval
265 boolean syncRunning; // Is sync running?
266 boolean automaticSync; // do sync automatically?
267 QTreeWidgetItem attributeTreeSelected;
269 QAction prevButton; // Go to the previous item viewed
270 QAction nextButton; // Go to the next item in the history
271 QAction downButton; // Go to the next item in the list
272 QAction upButton; // Go to the prev. item in the list;
273 QAction synchronizeButton; // Synchronize with Evernote
274 QAction allNotesButton; // Reset & view all notes
275 QTimer synchronizeAnimationTimer; // Timer to change animation button
276 int synchronizeIconAngle; // Used to rotate sync icon
277 QAction printButton; // Print Button
278 QAction tagButton; // Tag edit button
279 QAction attributeButton; // Attribute information button
280 QAction emailButton; // Email button
281 QAction deleteButton; // Delete button
282 QAction newButton; // new Note Button;
283 QSpinBox zoomSpinner; // Zoom zoom
284 QAction searchClearButton; // Clear the search field
286 QSplitter mainLeftRightSplitter; // main splitter for left/right side
287 QSplitter leftSplitter1; // first left hand splitter
288 QSplitter browserIndexSplitter; // splitter between note index & note text
290 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
291 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
292 List<String> importedFiles; // History of imported files (so we don't import twice)
294 OnlineNoteHistory historyWindow; // online history window
295 List<NoteVersionId> versions; // history versions
297 QTimer threadMonitorTimer; // Timer to watch threads.
298 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
299 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
300 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
301 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
302 int tagDeadCount=0; // number of consecutive dead times for the tag thread
303 int trashDeadCount=0; // number of consecutive dead times for the trash thread
304 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
305 boolean disableTagThreadCheck=false;
306 boolean disableNotebookThreadCheck=false;
307 boolean disableTrashThreadCheck=false;
308 boolean disableSaveThreadCheck=false;
309 boolean disableSyncThreadCheck=false;
310 boolean disableIndexThreadCheck=false;
312 HashMap<String, String> noteCache; // Cash of note content
313 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
314 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
315 List<String> historyGuids; // GUIDs of previously viewed items
316 int historyPosition; // Position within the viewed items
317 boolean fromHistory; // Is this from the history queue?
318 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
319 List<Thumbnailer> thumbGenerators; // generate preview image
320 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
321 boolean encryptOnShutdown; // should I encrypt when I close?
322 boolean decryptOnShutdown; // should I decrypt on shutdown;
323 String encryptCipher; // What cipher should I use?
324 Signal0 minimizeToTray;
325 boolean windowMaximized = false; // Keep track of the window state for restores
326 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
327 List<QPixmap> syncIcons; // Array of icons used in sync animation
328 private boolean closeAction = false; // Used to say when to close or when to minimize
329 private static Logger log = Logger.getLogger(NeverNote.class);
330 private String saveLastPath; // last path we used
331 private final QTimer messageTimer; // Timer to clear the status message.
334 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
337 //***************************************************************
338 //***************************************************************
339 //** Constructor & main entry point
340 //***************************************************************
341 //***************************************************************
342 // Application Constructor
343 @SuppressWarnings("static-access")
344 public NeverNote(DatabaseConnection dbConn) {
346 if (conn.getConnection() == null) {
347 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
348 "is accessing the database or NeverNote is already running.\n\n" +
349 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
351 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
355 // thread().setPriority(Thread.MAX_PRIORITY);
357 logger = new ApplicationLogger("nevernote.log");
358 logger.log(logger.HIGH, "Starting Application");
360 decryptOnShutdown = false;
361 encryptOnShutdown = false;
362 conn.checkDatabaseVersion();
366 // Start building the invalid XML tables
367 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
368 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
370 for (int i=0; i<elements.size(); i++) {
371 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
374 logger.log(logger.EXTREME, "Starting GUI build");
376 QTranslator nevernoteTranslator = new QTranslator();
377 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
378 QApplication.instance().installTranslator(nevernoteTranslator);
380 Global.originalPalette = QApplication.palette();
381 QApplication.setStyle(Global.getStyle());
382 if (Global.useStandardPalette())
383 QApplication.setPalette(QApplication.style().standardPalette());
384 setWindowTitle("NeverNote");
386 mainLeftRightSplitter = new QSplitter();
387 setCentralWidget(mainLeftRightSplitter);
388 leftSplitter1 = new QSplitter();
389 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
391 browserIndexSplitter = new QSplitter();
392 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
394 //* Setup threads & thread timers
395 int indexRunnerCount = Global.getIndexThreads();
396 indexRunnerCount = 1;
397 QThreadPool.globalInstance().setMaxThreadCount(indexRunnerCount+5); // increase max thread count
399 logger.log(logger.EXTREME, "Building list manager");
400 listManager = new ListManager(conn, logger);
402 logger.log(logger.EXTREME, "Building index runners & timers");
403 indexRunner = new IndexRunner("indexRunner.log",
404 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
405 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
406 indexThread = new QThread(indexRunner, "Index Thread");
407 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
410 synchronizeAnimationTimer = new QTimer();
411 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
413 indexTimer = new QTimer();
414 indexTime = 1000*Global.getIndexThreadSleepInterval();
415 indexTimer.start(indexTime); // Start indexing timer
416 indexTimer.timeout.connect(this, "indexTimer()");
417 indexDisabled = false;
418 indexRunning = false;
420 logger.log(logger.EXTREME, "Setting sync thread & timers");
422 syncRunner = new SyncRunner("syncRunner.log",
423 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
424 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
425 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
426 syncTimer = new QTimer();
427 syncTimer.timeout.connect(this, "syncTimer()");
428 syncRunner.status.message.connect(this, "setMessage(String)");
429 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
430 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
433 automaticSync = true;
434 syncTimer.start(syncTime*60*1000);
436 automaticSync = false;
439 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
440 syncThread = new QThread(syncRunner, "Synchronization Thread");
444 logger.log(logger.EXTREME, "Starting thumnail thread");
445 pdfReadyQueue = new ArrayList<String>();
446 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
447 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
448 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
449 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
450 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
451 thumbnailThread.start();
452 thumbGenerators = new ArrayList<Thumbnailer>();
453 thumbnailTimer = new QTimer();
454 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
456 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
457 thumbnailTimer.start();
459 logger.log(logger.EXTREME, "Starting authentication timer");
460 authTimer = new QTimer();
461 authTimer.timeout.connect(this, "authTimer()");
462 authTimer.start(1000*60*15);
463 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
465 logger.log(logger.EXTREME, "Setting save note timer");
466 saveTimer = new QTimer();
467 saveTimer.timeout.connect(this, "saveNote()");
468 if (Global.getAutoSaveInterval() > 0) {
469 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
472 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
474 logger.log(logger.EXTREME, "Starting external file monitor timer");
475 externalFileSaveTimer = new QTimer();
476 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
477 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
478 externalFiles = new ArrayList<String>();
479 importFilesDelete = new ArrayList<String>();
480 importFilesKeep = new ArrayList<String>();
481 externalFileSaveTimer.start();
483 notebookTree = new NotebookTreeWidget(conn);
484 attributeTree = new AttributeTreeWidget();
485 tagTree = new TagTreeWidget(conn);
486 savedSearchTree = new SavedSearchTreeWidget();
487 trashTree = new TrashTreeWidget();
488 noteTableView = new TableView(logger, listManager);
490 QGridLayout leftGrid = new QGridLayout();
491 leftSplitter1.setLayout(leftGrid);
492 leftGrid.addWidget(notebookTree, 1, 1);
493 leftGrid.addWidget(tagTree,2,1);
494 leftGrid.addWidget(attributeTree,3,1);
495 leftGrid.addWidget(savedSearchTree,4,1);
496 leftGrid.addWidget(trashTree, 5, 1);
498 // Setup the browser window
499 noteCache = new HashMap<String,String>();
500 readOnlyCache = new HashMap<String, Boolean>();
501 inkNoteCache = new HashMap<String, Boolean>();
502 browserWindow = new BrowserWindow(conn);
504 mainLeftRightSplitter.addWidget(leftSplitter1);
505 mainLeftRightSplitter.addWidget(browserIndexSplitter);
507 if (Global.getListView() == Global.View_List_Wide) {
508 browserIndexSplitter.addWidget(noteTableView);
509 browserIndexSplitter.addWidget(browserWindow);
511 mainLeftRightSplitter.addWidget(noteTableView);
512 mainLeftRightSplitter.addWidget(browserWindow);
515 searchField = new QComboBox();
516 searchField.setEditable(true);
517 searchField.activatedIndex.connect(this, "searchFieldChanged()");
518 searchField.setDuplicatesEnabled(false);
519 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
520 searchShortcut = new QShortcut(this);
521 setupShortcut(searchShortcut, "Focus_Search");
522 searchShortcut.activated.connect(this, "focusSearch()");
524 quotaBar = new QuotaProgressBar();
526 // Setup the thumbnail viewer
527 thumbnailViewer = new ThumbnailViewer();
528 thumbnailViewer.upArrow.connect(this, "upAction()");
529 thumbnailViewer.downArrow.connect(this, "downAction()");
530 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
531 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
533 //Setup external browser manager
534 externalWindows = new HashMap<String, ExternalBrowse>();
536 listManager.loadNotesIndex();
537 initializeNotebookTree();
539 initializeSavedSearchTree();
540 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
541 attributeTreeSelected = null;
542 initializeNoteTable();
544 selectedNoteGUIDs = new ArrayList<String>();
545 statusBar = new QStatusBar();
546 setStatusBar(statusBar);
547 menuBar = new MainMenuBar(this);
548 emitLog = new ArrayList<String>();
550 tagTree.setDeleteAction(menuBar.tagDeleteAction);
551 tagTree.setEditAction(menuBar.tagEditAction);
552 tagTree.setAddAction(menuBar.tagAddAction);
553 tagTree.setIconAction(menuBar.tagIconAction);
554 tagTree.setVisible(Global.isWindowVisible("tagTree"));
555 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
556 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
557 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
559 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
560 notebookTree.setEditAction(menuBar.notebookEditAction);
561 notebookTree.setAddAction(menuBar.notebookAddAction);
562 notebookTree.setIconAction(menuBar.notebookIconAction);
563 notebookTree.setStackAction(menuBar.notebookStackAction);
564 notebookTree.setPublishAction(menuBar.notebookPublishAction);
565 notebookTree.setShareAction(menuBar.notebookShareAction);
566 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
567 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
568 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
569 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
570 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
572 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
573 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
574 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
575 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
576 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
577 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
578 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
580 noteTableView.setAddAction(menuBar.noteAdd);
581 noteTableView.setDeleteAction(menuBar.noteDelete);
582 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
583 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
584 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
585 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
586 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
587 noteTableView.rowChanged.connect(this, "scrollToGuid(String)");
588 noteTableView.resetViewport.connect(this, "scrollToCurrentGuid()");
589 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
590 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
592 quotaBar.setMouseClickAction(menuBar.accountAction);
595 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
596 trashTree.setEmptyAction(menuBar.emptyTrashAction);
597 trashTree.setVisible(Global.isWindowVisible("trashTree"));
598 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
599 trashTree.updateCounts(listManager.getTrashCount());
600 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
601 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
603 noteTableView.setVisible(Global.isWindowVisible("noteList"));
604 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
606 if (!Global.isWindowVisible("editorButtonBar"))
607 toggleEditorButtonBar();
608 if (!Global.isWindowVisible("leftPanel"))
609 menuBar.hideLeftSide.setChecked(true);
610 if (Global.isWindowVisible("noteInformation"))
611 toggleNoteInformation();
615 find = new FindDialog();
616 find.getOkButton().clicked.connect(this, "doFindText()");
618 // Setup the tray icon menu bar
619 trayShowAction = new QAction("Show/Hide", this);
620 trayExitAction = new QAction("Exit", this);
621 trayAddNoteAction = new QAction("Add Note", this);
623 trayExitAction.triggered.connect(this, "closeNeverNote()");
624 trayAddNoteAction.triggered.connect(this, "addNote()");
625 trayShowAction.triggered.connect(this, "trayToggleVisible()");
627 trayMenu = new QMenu(this);
628 trayMenu.addAction(trayAddNoteAction);
629 trayMenu.addAction(trayShowAction);
630 trayMenu.addAction(trayExitAction);
633 trayIcon = new QSystemTrayIcon(this);
634 trayIcon.setToolTip("NeverNote");
635 trayIcon.setContextMenu(trayMenu);
636 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
639 currentNoteGuid = Global.getLastViewedNoteGuid();
640 historyGuids = new ArrayList<String>();
644 if (!currentNoteGuid.trim().equals("")) {
645 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
648 noteIndexUpdated(true);
650 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
651 if (menuBar.showEditorBar.isChecked())
652 showEditorButtons(browserWindow);
653 tagIndexUpdated(true);
654 savedSearchIndexUpdated();
655 notebookIndexUpdated();
657 setupSyncSignalListeners();
658 setupBrowserSignalListeners();
659 setupIndexListeners();
662 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
663 tagTree.showAllTags(true);
665 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
666 setWindowIcon(appIcon);
667 trayIcon.setIcon(appIcon);
668 if (Global.showTrayIcon())
673 scrollToGuid(currentNoteGuid);
674 if (Global.automaticLogin()) {
676 if (Global.isConnected)
679 setupFolderImports();
682 restoreWindowState(true);
684 if (Global.mimicEvernoteInterface) {
685 notebookTree.selectGuid("");
688 threadMonitorTimer = new QTimer();
689 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
690 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
692 historyGuids.add(currentNoteGuid);
695 menuBar.blockSignals(true);
696 menuBar.narrowListView.blockSignals(true);
697 menuBar.wideListView.blockSignals(true);
698 if (Global.getListView() == Global.View_List_Narrow) {
699 menuBar.narrowListView.setChecked(true);
702 menuBar.wideListView.setChecked(true);
704 menuBar.blockSignals(false);
705 menuBar.narrowListView.blockSignals(false);
706 menuBar.wideListView.blockSignals(false);
708 if (Global.getListView() == Global.View_List_Wide) {
709 browserIndexSplitter.addWidget(noteTableView);
710 browserIndexSplitter.addWidget(browserWindow);
712 mainLeftRightSplitter.addWidget(noteTableView);
713 mainLeftRightSplitter.addWidget(browserWindow);
716 messageTimer = new QTimer();
717 messageTimer.timeout.connect(this, "clearMessage()");
718 messageTimer.setInterval(1000*15);
721 int sortCol = Global.getSortColumn();
722 int sortOrder = Global.getSortOrder();
723 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
724 if (Global.checkVersionUpgrade())
729 public static void main(String[] args) {
730 log.setLevel(Level.FATAL);
731 QApplication.initialize(args);
732 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
733 QSplashScreen splash = new QSplashScreen(pixmap);
736 DatabaseConnection dbConn;
739 initializeGlobalSettings(args);
741 showSplash = Global.isWindowVisible("SplashScreen");
745 dbConn = setupDatabaseConnection();
747 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
748 Global.getFileManager().purgeResDirectory(true);
750 } catch (InitializationException e) {
753 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
757 NeverNote application = new NeverNote(dbConn);
759 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
760 if (Global.startMinimized())
761 application.showMinimized();
763 if (Global.wasWindowMaximized())
764 application.showMaximized();
770 splash.finish(application);
772 System.out.println("Goodbye.");
777 * Open the internal database, or create if not present
779 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
781 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
782 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
784 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
785 boolean dbExists = f.exists();
787 Global.setDatabaseUrl("");
789 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
790 boolean goodCheck = false;
792 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
794 if (!dialog.okPressed())
796 Global.cipherPassword = dialog.getPassword();
797 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
798 Global.getDatabaseUserPassword(), Global.cipherPassword);
801 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
802 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
803 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
807 // Encrypt the database upon shutdown
808 private void encryptOnShutdown() {
809 String dbPath= Global.getFileManager().getDbDirPath("");
810 String dbName = "NeverNote";
812 Statement st = conn.getConnection().createStatement();
813 st.execute("shutdown");
814 if (QMessageBox.question(this, tr("Are you sure"),
815 tr("Are you sure you wish to encrypt the database?"),
816 QMessageBox.StandardButton.Yes,
817 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
818 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
819 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
820 QMessageBox.information(this, "Encryption Complete", "Encryption is complete");
822 } catch (SQLException e) {
827 // Decrypt the database upon shutdown
828 private void decryptOnShutdown() {
829 String dbPath= Global.getFileManager().getDbDirPath("");
830 String dbName = "NeverNote";
832 Statement st = conn.getConnection().createStatement();
833 st.execute("shutdown");
834 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
835 encryptCipher = "AES";
837 encryptCipher = "XTEA";
838 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
839 "Are you sure you wish to decrypt the database?"),
840 QMessageBox.StandardButton.Yes,
841 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
843 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
844 Global.setDatabaseUrl("");
845 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
847 } catch (SQLException e) {
852 * Encrypt/Decrypt the local database
854 public void doDatabaseEncrypt() {
855 // The database is not currently encrypted
856 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
857 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
858 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
859 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
860 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
861 "Do you wish to proceed?"),
862 QMessageBox.StandardButton.Yes,
863 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
866 DBEncryptDialog dialog = new DBEncryptDialog();
868 if (dialog.okPressed()) {
869 Global.cipherPassword = dialog.getPassword();
870 encryptOnShutdown = true;
871 encryptCipher = dialog.getEncryptionMethod();
874 DBEncryptDialog dialog = new DBEncryptDialog();
875 dialog.setWindowTitle("Database Decryption");
876 dialog.hideEncryption();
878 if (dialog.okPressed()) {
879 if (!dialog.getPassword().equals(Global.cipherPassword)) {
880 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
883 decryptOnShutdown = true;
890 private static void initializeGlobalSettings(String[] args) throws InitializationException {
891 StartupConfig startupConfig = new StartupConfig();
893 for (String arg : args) {
894 String lower = arg.toLowerCase();
895 if (lower.startsWith("--name="))
896 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
897 if (lower.startsWith("--home="))
898 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
899 if (lower.startsWith("--disable-viewing"))
900 startupConfig.setDisableViewing(true);
902 Global.setup(startupConfig);
907 public void closeEvent(QCloseEvent event) {
908 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
913 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
916 if (currentNote!= null & browserWindow!=null) {
917 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
918 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
921 setMessage(tr("Beginning shutdown."));
923 // Close down external windows
924 Collection<ExternalBrowse> windows = externalWindows.values();
925 Iterator<ExternalBrowse> iterator = windows.iterator();
926 while (iterator.hasNext()) {
927 ExternalBrowse browser = iterator.next();
928 browser.windowClosing.disconnect();
933 externalFileEditedSaver();
934 if (Global.isConnected && Global.synchronizeOnClose()) {
935 setMessage(tr("Performing synchronization before closing."));
936 syncRunner.syncNeeded = true;
937 syncRunner.addWork("SYNC");
938 syncRunner.addWork("STOP");
940 syncRunner.addWork("STOP");
941 syncRunner.keepRunning = false;
943 setMessage("Closing Program.");
944 threadMonitorTimer.stop();
946 thumbnailRunner.addWork("STOP");
947 indexRunner.addWork("STOP");
952 if (tempFiles != null)
955 browserWindow.noteSignal.tagsChanged.disconnect();
956 browserWindow.noteSignal.titleChanged.disconnect();
957 browserWindow.noteSignal.noteChanged.disconnect();
958 browserWindow.noteSignal.notebookChanged.disconnect();
959 browserWindow.noteSignal.createdDateChanged.disconnect();
960 browserWindow.noteSignal.alteredDateChanged.disconnect();
961 syncRunner.searchSignal.listChanged.disconnect();
962 syncRunner.tagSignal.listChanged.disconnect();
963 syncRunner.notebookSignal.listChanged.disconnect();
964 syncRunner.noteIndexSignal.listChanged.disconnect();
967 Global.saveWindowVisible("toolBar", toolBar.isVisible());
968 saveNoteColumnPositions();
969 saveNoteIndexWidth();
971 int width = notebookTree.columnWidth(0);
972 Global.setColumnWidth("notebookTreeName", width);
973 width = tagTree.columnWidth(0);
974 Global.setColumnWidth("tagTreeName", width);
976 Global.saveWindowMaximized(isMaximized());
977 Global.saveCurrentNoteGuid(currentNoteGuid);
979 int sortCol = noteTableView.proxyModel.sortColumn();
980 int sortOrder = noteTableView.proxyModel.sortOrder().value();
981 Global.setSortColumn(sortCol);
982 Global.setSortOrder(sortOrder);
986 Global.keepRunning = false;
988 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
989 if (indexRunner.thread().isAlive())
990 indexRunner.thread().join(50);
991 if (!indexRunner.thread().isAlive())
992 logger.log(logger.MEDIUM, "Index thread has stopped");
994 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
995 indexRunner.thread().interrupt();
997 } catch (InterruptedException e1) {
998 e1.printStackTrace();
1001 syncRunner.addWork("STOP");
1002 if (!syncRunner.isIdle()) {
1004 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1005 System.out.println(tr("Synchronizing. Please be patient."));
1006 for(;syncRunner.thread().isAlive();) {
1009 } catch (InterruptedException e) {
1010 e.printStackTrace();
1013 logger.log(logger.MEDIUM, "Sync thread has stopped");
1014 //} catch (InterruptedException e1) {
1015 // e1.printStackTrace();
1019 if (encryptOnShutdown) {
1020 encryptOnShutdown();
1022 if (decryptOnShutdown) {
1023 decryptOnShutdown();
1026 Global.getFileManager().purgeResDirectory(false);
1027 } catch (InitializationException e) {
1028 System.out.println(tr("Empty res directory purge failed"));
1029 e.printStackTrace();
1031 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1034 @SuppressWarnings("unused")
1035 private void closeNeverNote() {
1039 public void setMessage(String s) {
1040 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1043 logger.log(logger.HIGH, "Message: " +s);
1044 statusBar.showMessage(s);
1048 messageTimer.stop();
1049 messageTimer.setSingleShot(true);
1050 messageTimer.start();
1053 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1056 private void clearMessage() {
1057 statusBar.clearMessage();
1061 private void waitCursor(boolean wait) {
1063 if (QApplication.overrideCursor() == null)
1064 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1067 while (QApplication.overrideCursor() != null)
1068 QApplication.restoreOverrideCursor();
1072 private void setupIndexListeners() {
1073 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1074 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1075 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1076 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1078 private void setupSyncSignalListeners() {
1079 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1080 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1081 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1082 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1083 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1085 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1086 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1087 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1089 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1090 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1091 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1092 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1093 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1095 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1098 private void setupBrowserSignalListeners() {
1099 setupBrowserWindowListeners(browserWindow, true);
1102 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1103 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1104 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1105 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1106 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1107 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1108 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1109 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1110 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1111 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1112 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1113 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1114 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1115 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1116 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1117 if (master) browser.focusLost.connect(this, "saveNote()");
1118 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1121 //**************************************************
1123 //**************************************************
1124 private void setupShortcut(QShortcut action, String text) {
1125 if (!Global.shortcutKeys.containsAction(text))
1127 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1130 //***************************************************************
1131 //***************************************************************
1132 //* Settings and look & feel
1133 //***************************************************************
1134 //***************************************************************
1135 @SuppressWarnings("unused")
1136 private void settings() {
1137 logger.log(logger.HIGH, "Entering NeverNote.settings");
1138 saveNoteColumnPositions();
1139 saveNoteIndexWidth();
1141 ConfigDialog settings = new ConfigDialog(this);
1142 String dateFormat = Global.getDateFormat();
1143 String timeFormat = Global.getTimeFormat();
1145 indexTime = 1000*Global.getIndexThreadSleepInterval();
1146 indexTimer.start(indexTime); // reset indexing timer
1149 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1150 if (Global.showTrayIcon())
1155 if (menuBar.showEditorBar.isChecked())
1156 showEditorButtons(browserWindow);
1158 // Reset the save timer
1159 if (Global.getAutoSaveInterval() > 0)
1160 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1164 // This is a hack to force a reload of the index in case the date or time changed.
1165 // if (!dateFormat.equals(Global.getDateFormat()) ||
1166 // !timeFormat.equals(Global.getTimeFormat())) {
1168 readOnlyCache.clear();
1169 inkNoteCache.clear();
1170 noteIndexUpdated(true);
1173 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1175 // Restore things to the way they were
1176 private void restoreWindowState(boolean mainWindow) {
1177 // We need to name things or this doesn't work.
1178 setObjectName("NeverNote");
1179 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1180 browserIndexSplitter.setObjectName("browserIndexSplitter");
1181 leftSplitter1.setObjectName("leftSplitter1");
1183 // Restore the actual positions.
1185 restoreGeometry(Global.restoreGeometry(objectName()));
1186 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1187 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1188 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1191 // Save window positions for the next start
1192 private void saveWindowState() {
1193 Global.saveGeometry(objectName(), saveGeometry());
1194 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1195 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1196 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1198 // Load the style sheet
1199 private void loadStyleSheet() {
1200 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1201 fileName = Global.getFileManager().getQssDirPath("default.qss");
1202 QFile file = new QFile(fileName);
1204 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1205 if (!file.exists()) {
1206 fileName = Global.getFileManager().getQssDirPath("default.qss");
1207 file = new QFile(fileName);
1209 file.open(OpenModeFlag.ReadOnly);
1210 String styleSheet = file.readAll().toString();
1212 setStyleSheet(styleSheet);
1214 // Save column positions for the next time
1215 private void saveNoteColumnPositions() {
1216 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1217 Global.setColumnPosition("noteTableCreationPosition", position);
1218 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1219 Global.setColumnPosition("noteTableTagPosition", position);
1220 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1221 Global.setColumnPosition("noteTableNotebookPosition", position);
1222 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1223 Global.setColumnPosition("noteTableChangedPosition", position);
1224 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1225 Global.setColumnPosition("noteTableAuthorPosition", position);
1226 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1227 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1228 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1229 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1230 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1231 Global.setColumnPosition("noteTableTitlePosition", position);
1232 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1233 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1234 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1235 Global.setColumnPosition("noteTableGuidPosition", position);
1236 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1237 Global.setColumnPosition("noteTableThumbnailPosition", position);
1240 // Save column widths for the next time
1241 private void saveNoteIndexWidth() {
1243 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1244 Global.setColumnWidth("noteTableCreationPosition", width);
1245 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1246 Global.setColumnWidth("noteTableChangedPosition", width);
1247 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1248 Global.setColumnWidth("noteTableGuidPosition", width);
1249 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1250 Global.setColumnWidth("noteTableNotebookPosition", width);
1251 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1252 Global.setColumnWidth("noteTableTagPosition", width);
1253 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1254 Global.setColumnWidth("noteTableTitlePosition", width);
1255 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1256 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1257 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1258 Global.setColumnWidth("noteTableAuthorPosition", width);
1259 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1260 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1261 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1262 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1263 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1264 Global.setColumnWidth("noteTableThumbnailPosition", width);
1265 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1266 Global.setColumnWidth("noteTableGuidPosition", width);
1270 //***************************************************************
1271 //***************************************************************
1272 //** These functions deal with Notebook menu items
1273 //***************************************************************
1274 //***************************************************************
1275 // Setup the tree containing the user's notebooks.
1276 private void initializeNotebookTree() {
1277 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1278 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1279 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1280 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1281 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1283 // Listener when a notebook is selected
1284 private void notebookTreeSelection() {
1285 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1288 clearAttributeFilter();
1289 clearSavedSearchFilter();
1290 if (Global.mimicEvernoteInterface) {
1292 searchField.clear();
1294 menuBar.noteRestoreAction.setVisible(false);
1295 menuBar.notebookEditAction.setEnabled(true);
1296 menuBar.notebookDeleteAction.setEnabled(true);
1297 menuBar.notebookPublishAction.setEnabled(true);
1298 menuBar.notebookShareAction.setEnabled(true);
1299 menuBar.notebookIconAction.setEnabled(true);
1300 menuBar.notebookStackAction.setEnabled(true);
1301 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1302 selectedNotebookGUIDs.clear();
1304 String stackName = "";
1305 if (selections.size() > 0) {
1306 guid = (selections.get(0).text(2));
1307 stackName = selections.get(0).text(0);
1309 if (!Global.mimicEvernoteInterface) {
1310 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1311 if (selections.size()==0) {
1312 selectedNotebookGUIDs.clear();
1313 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1314 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1316 menuBar.notebookEditAction.setEnabled(false);
1317 menuBar.notebookDeleteAction.setEnabled(false);
1318 menuBar.notebookStackAction.setEnabled(false);
1319 menuBar.notebookIconAction.setEnabled(false);
1322 if (!guid.equals("") && !guid.equals("STACK")) {
1323 selectedNotebookGUIDs.add(guid);
1324 menuBar.notebookIconAction.setEnabled(true);
1326 menuBar.notebookIconAction.setEnabled(true);
1327 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1328 Notebook book = listManager.getNotebookIndex().get(j);
1329 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1330 selectedNotebookGUIDs.add(book.getGuid());
1333 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1334 listManager.loadNotesIndex();
1335 noteIndexUpdated(false);
1336 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1339 private void clearNotebookFilter() {
1340 notebookTree.blockSignals(true);
1341 notebookTree.clearSelection();
1342 menuBar.noteRestoreAction.setVisible(false);
1343 menuBar.notebookEditAction.setEnabled(false);
1344 menuBar.notebookDeleteAction.setEnabled(false);
1345 selectedNotebookGUIDs.clear();
1346 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1347 notebookTree.blockSignals(false);
1349 // Triggered when the notebook DB has been updated
1350 private void notebookIndexUpdated() {
1351 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1353 // Get the possible icons
1354 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1355 notebookTree.setIcons(icons);
1357 if (selectedNotebookGUIDs == null)
1358 selectedNotebookGUIDs = new ArrayList<String>();
1359 List<Notebook> books = conn.getNotebookTable().getAll();
1360 for (int i=books.size()-1; i>=0; i--) {
1361 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1362 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1364 j=listManager.getArchiveNotebookIndex().size();
1370 listManager.countNotebookResults(listManager.getNoteIndex());
1371 notebookTree.blockSignals(true);
1372 notebookTree.load(books, listManager.getLocalNotebooks());
1373 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1374 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1376 selectedNotebookGUIDs.remove(i);
1378 notebookTree.blockSignals(false);
1380 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1382 // Show/Hide note information
1383 private void toggleNotebookWindow() {
1384 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1385 if (notebookTree.isVisible())
1386 notebookTree.hide();
1388 notebookTree.show();
1389 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1390 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1391 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1393 // Add a new notebook
1394 @SuppressWarnings("unused")
1395 private void addNotebook() {
1396 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1397 NotebookEdit edit = new NotebookEdit();
1398 edit.setNotebooks(listManager.getNotebookIndex());
1401 if (!edit.okPressed())
1404 Calendar currentTime = new GregorianCalendar();
1405 Long l = new Long(currentTime.getTimeInMillis());
1406 String randint = new String(Long.toString(l));
1408 Notebook newBook = new Notebook();
1409 newBook.setUpdateSequenceNum(0);
1410 newBook.setGuid(randint);
1411 newBook.setName(edit.getNotebook());
1412 newBook.setServiceCreated(new Date().getTime());
1413 newBook.setServiceUpdated(new Date().getTime());
1414 newBook.setDefaultNotebook(false);
1415 newBook.setPublished(false);
1417 listManager.getNotebookIndex().add(newBook);
1419 listManager.getLocalNotebooks().add(newBook.getGuid());
1420 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1421 notebookIndexUpdated();
1422 listManager.countNotebookResults(listManager.getNoteIndex());
1423 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1424 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1426 // Edit an existing notebook
1427 @SuppressWarnings("unused")
1428 private void stackNotebook() {
1429 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1430 StackNotebook edit = new StackNotebook();
1432 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1433 QTreeWidgetItem currentSelection;
1434 for (int i=0; i<selections.size(); i++) {
1435 currentSelection = selections.get(0);
1436 String guid = currentSelection.text(2);
1437 if (guid.equalsIgnoreCase("")) {
1438 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1441 if (guid.equalsIgnoreCase("STACK")) {
1442 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1447 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1452 if (!edit.okPressed())
1455 String stack = edit.getStackName();
1457 for (int i=0; i<selections.size(); i++) {
1458 currentSelection = selections.get(i);
1459 String guid = currentSelection.text(2);
1460 listManager.updateNotebookStack(guid, stack);
1462 notebookIndexUpdated();
1463 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1465 // Edit an existing notebook
1466 @SuppressWarnings("unused")
1467 private void editNotebook() {
1468 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1469 NotebookEdit edit = new NotebookEdit();
1471 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1472 QTreeWidgetItem currentSelection;
1473 currentSelection = selections.get(0);
1474 edit.setNotebook(currentSelection.text(0));
1476 String guid = currentSelection.text(2);
1477 if (!guid.equalsIgnoreCase("STACK")) {
1478 edit.setTitle(tr("Edit Notebook"));
1479 edit.setNotebooks(listManager.getNotebookIndex());
1480 edit.setLocalCheckboxEnabled(false);
1481 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1482 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1483 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1484 i=listManager.getNotebookIndex().size();
1488 edit.setTitle(tr("Edit Stack"));
1489 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1490 edit.hideLocalCheckbox();
1491 edit.hideDefaultCheckbox();
1496 if (!edit.okPressed())
1500 if (guid.equalsIgnoreCase("STACK")) {
1501 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1502 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1503 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1504 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1505 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1507 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1508 currentSelection.setText(0, edit.getNotebook());
1512 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1513 currentSelection.setText(0, edit.getNotebook());
1515 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1516 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1517 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1518 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1519 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1520 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1521 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1522 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1524 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1525 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1526 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1527 linkedNotebook.setShareName(edit.getNotebook());
1528 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1530 i=listManager.getNotebookIndex().size();
1534 // Build a list of non-closed notebooks
1535 List<Notebook> nbooks = new ArrayList<Notebook>();
1536 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1537 boolean found=false;
1538 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1539 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1543 nbooks.add(listManager.getNotebookIndex().get(i));
1547 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1548 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1549 browserWindow.setNotebookList(filteredBooks);
1550 Iterator<String> set = externalWindows.keySet().iterator();
1551 while(set.hasNext())
1552 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1553 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1555 // Publish a notebook
1556 @SuppressWarnings("unused")
1557 private void publishNotebook() {
1558 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1559 QTreeWidgetItem currentSelection;
1560 currentSelection = selections.get(0);
1561 String guid = currentSelection.text(2);
1563 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1568 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1569 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1570 n = listManager.getNotebookIndex().get(i);
1572 i = listManager.getNotebookIndex().size();
1578 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1581 if (!publish.okClicked())
1584 Publishing p = publish.getPublishing();
1585 boolean isPublished = !publish.isStopPressed();
1586 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1587 n.setPublished(isPublished);
1589 listManager.getNotebookIndex().set(position, n);
1590 notebookIndexUpdated();
1592 // Publish a notebook
1593 @SuppressWarnings("unused")
1594 private void shareNotebook() {
1595 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1596 QTreeWidgetItem currentSelection;
1597 currentSelection = selections.get(0);
1598 String guid = currentSelection.text(2);
1600 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1604 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1605 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1606 n = listManager.getNotebookIndex().get(i);
1607 i = listManager.getNotebookIndex().size();
1611 String authToken = null;
1612 if (syncRunner.isConnected)
1613 authToken = syncRunner.authToken;
1614 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1619 // Delete an existing notebook
1620 @SuppressWarnings("unused")
1621 private void deleteNotebook() {
1622 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1623 boolean stacksFound = false;
1624 boolean notebooksFound = false;
1625 boolean assigned = false;
1626 // Check if any notes have this notebook
1627 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1628 for (int i=0; i<selections.size(); i++) {
1629 QTreeWidgetItem currentSelection;
1630 currentSelection = selections.get(i);
1631 String guid = currentSelection.text(2);
1632 if (!guid.equalsIgnoreCase("STACK")) {
1633 notebooksFound = true;
1634 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1635 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1636 if (noteGuid.equals(guid)) {
1638 j=listManager.getNoteIndex().size();
1639 i=selections.size();
1647 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1648 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1652 if (conn.getNotebookTable().getAll().size() == 1) {
1653 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1657 // If all notebooks are clear, verify the delete
1658 String msg1 = new String(tr("Delete selected notebooks?"));
1659 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1660 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1661 " not deleted unless selected?"));
1663 if (stacksFound && notebooksFound)
1665 if (!stacksFound && notebooksFound)
1667 if (stacksFound && !notebooksFound)
1669 if (QMessageBox.question(this, tr("Confirmation"), msg,
1670 QMessageBox.StandardButton.Yes,
1671 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1675 // If confirmed, delete the notebook
1676 for (int i=selections.size()-1; i>=0; i--) {
1677 QTreeWidgetItem currentSelection;
1678 currentSelection = selections.get(i);
1679 String guid = currentSelection.text(2);
1680 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1681 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1682 listManager.renameStack(currentSelection.text(0), "");
1684 conn.getNotebookTable().expungeNotebook(guid, true);
1685 listManager.deleteNotebook(guid);
1689 notebookIndexUpdated();
1690 // notebookTreeSelection();
1691 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1692 // listManager.countNotebookResults(listManager.getNoteIndex());
1693 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1695 // A note's notebook has been updated
1696 @SuppressWarnings("unused")
1697 private void updateNoteNotebook(String guid, String notebookGuid) {
1699 // Update the list manager
1700 listManager.updateNoteNotebook(guid, notebookGuid);
1701 listManager.countNotebookResults(listManager.getNoteIndex());
1702 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1704 // Find the name of the notebook
1705 String notebookName = null;
1706 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1707 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1708 notebookName = listManager.getNotebookIndex().get(i).getName();
1713 // If we found the name, update the browser window
1714 if (notebookName != null) {
1715 updateListNoteNotebook(guid, notebookName);
1716 if (guid.equals(currentNoteGuid)) {
1717 int pos = browserWindow.notebookBox.findText(notebookName);
1719 browserWindow.notebookBox.setCurrentIndex(pos);
1723 // If we're dealing with the current note, then we need to be sure and update the notebook there
1724 if (guid.equals(currentNoteGuid)) {
1725 if (currentNote != null) {
1726 currentNote.setNotebookGuid(notebookGuid);
1730 // Open/close notebooks
1731 @SuppressWarnings("unused")
1732 private void closeNotebooks() {
1733 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1735 if (!na.okClicked())
1739 listManager.getArchiveNotebookIndex().clear();
1741 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1742 String text = na.getClosedBookList().takeItem(i).text();
1743 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1744 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1745 Notebook n = listManager.getNotebookIndex().get(j);
1746 conn.getNotebookTable().setArchived(n.getGuid(),true);
1747 listManager.getArchiveNotebookIndex().add(n);
1748 j=listManager.getNotebookIndex().size();
1753 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1754 String text = na.getOpenBookList().takeItem(i).text();
1755 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1756 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1757 Notebook n = listManager.getNotebookIndex().get(j);
1758 conn.getNotebookTable().setArchived(n.getGuid(),false);
1759 j=listManager.getNotebookIndex().size();
1763 notebookTreeSelection();
1764 listManager.loadNotesIndex();
1765 notebookIndexUpdated();
1766 noteIndexUpdated(false);
1767 reloadTagTree(true);
1768 // noteIndexUpdated(false);
1770 // Build a list of non-closed notebooks
1771 List<Notebook> nbooks = new ArrayList<Notebook>();
1772 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1773 boolean found=false;
1774 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1775 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1779 nbooks.add(listManager.getNotebookIndex().get(i));
1782 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1783 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1784 browserWindow.setNotebookList(filteredBooks);
1786 // Update any external windows
1787 Iterator<String> set = externalWindows.keySet().iterator();
1788 while(set.hasNext())
1789 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1793 // Change the notebook's icon
1794 @SuppressWarnings("unused")
1795 private void setNotebookIcon() {
1796 boolean stackSelected = false;
1797 boolean allNotebookSelected = false;
1799 QTreeWidgetItem currentSelection;
1800 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1801 if (selections.size() == 0)
1804 currentSelection = selections.get(0);
1805 String guid = currentSelection.text(2);
1806 if (guid.equalsIgnoreCase(""))
1807 allNotebookSelected = true;
1808 if (guid.equalsIgnoreCase("STACK"))
1809 stackSelected = true;
1811 QIcon currentIcon = currentSelection.icon(0);
1815 if (!stackSelected && !allNotebookSelected) {
1816 icon = conn.getNotebookTable().getIcon(guid);
1818 dialog = new SetIcon(currentIcon, saveLastPath);
1819 dialog.setUseDefaultIcon(true);
1821 dialog = new SetIcon(icon, saveLastPath);
1822 dialog.setUseDefaultIcon(false);
1825 if (stackSelected) {
1826 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1828 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1831 dialog = new SetIcon(currentIcon, saveLastPath);
1832 dialog.setUseDefaultIcon(true);
1834 dialog = new SetIcon(icon, saveLastPath);
1835 dialog.setUseDefaultIcon(false);
1839 if (dialog.okPressed()) {
1840 saveLastPath = dialog.getPath();
1842 QIcon newIcon = dialog.getIcon();
1843 if (stackSelected) {
1844 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1845 if (newIcon == null) {
1846 newIcon = new QIcon(iconPath+"books2.png");
1848 currentSelection.setIcon(0,newIcon);
1851 if (allNotebookSelected) {
1852 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1853 if (newIcon == null) {
1854 newIcon = new QIcon(iconPath+"notebook-green.png");
1856 currentSelection.setIcon(0,newIcon);
1859 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1860 if (newIcon == null) {
1861 boolean isPublished = false;;
1862 boolean found = false;
1863 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1864 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1865 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1869 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1871 currentSelection.setIcon(0, newIcon);
1877 //***************************************************************
1878 //***************************************************************
1879 //** These functions deal with Tag menu items
1880 //***************************************************************
1881 //***************************************************************
1882 // Add a new notebook
1883 @SuppressWarnings("unused")
1884 private void addTag() {
1885 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1886 TagEdit edit = new TagEdit();
1887 edit.setTagList(listManager.getTagIndex());
1890 if (!edit.okPressed())
1893 Calendar currentTime = new GregorianCalendar();
1894 Long l = new Long(currentTime.getTimeInMillis());
1895 String randint = new String(Long.toString(l));
1897 Tag newTag = new Tag();
1898 newTag.setUpdateSequenceNum(0);
1899 newTag.setGuid(randint);
1900 newTag.setName(edit.getTag());
1901 conn.getTagTable().addTag(newTag, true);
1902 listManager.getTagIndex().add(newTag);
1903 reloadTagTree(true);
1905 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
1907 @SuppressWarnings("unused")
1908 private void reloadTagTree() {
1909 reloadTagTree(false);
1911 private void reloadTagTree(boolean reload) {
1912 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
1913 tagIndexUpdated(reload);
1914 boolean filter = false;
1916 listManager.countTagResults(listManager.getNoteIndex());
1917 if (notebookTree.selectedItems().size() > 0
1918 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
1920 if (tagTree.selectedItems().size() > 0)
1922 tagTree.showAllTags(!filter);
1923 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
1925 // Edit an existing tag
1926 @SuppressWarnings("unused")
1927 private void editTag() {
1928 logger.log(logger.HIGH, "Entering NeverNote.editTag");
1929 TagEdit edit = new TagEdit();
1930 edit.setTitle("Edit Tag");
1931 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1932 QTreeWidgetItem currentSelection;
1933 currentSelection = selections.get(0);
1934 edit.setTag(currentSelection.text(0));
1935 edit.setTagList(listManager.getTagIndex());
1938 if (!edit.okPressed())
1941 String guid = currentSelection.text(2);
1942 currentSelection.setText(0,edit.getTag());
1944 for (int i=0; i<listManager.getTagIndex().size(); i++) {
1945 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
1946 listManager.getTagIndex().get(i).setName(edit.getTag());
1947 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
1948 updateListTagName(guid);
1949 if (currentNote != null && currentNote.getTagGuids().contains(guid))
1950 browserWindow.setTag(getTagNamesForNote(currentNote));
1951 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
1955 browserWindow.setTag(getTagNamesForNote(currentNote));
1956 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
1958 // Delete an existing tag
1959 @SuppressWarnings("unused")
1960 private void deleteTag() {
1961 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
1963 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
1964 QMessageBox.StandardButton.Yes,
1965 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1969 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1970 for (int i=selections.size()-1; i>=0; i--) {
1971 QTreeWidgetItem currentSelection;
1972 currentSelection = selections.get(i);
1973 removeTagItem(currentSelection.text(2));
1975 tagIndexUpdated(true);
1977 listManager.countTagResults(listManager.getNoteIndex());
1978 // tagTree.updateCounts(listManager.getTagCounter());
1979 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
1981 // Remove a tag tree item. Go recursively down & remove the children too
1982 private void removeTagItem(String guid) {
1983 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
1984 String parent = listManager.getTagIndex().get(j).getParentGuid();
1985 if (parent != null && parent.equals(guid)) {
1986 //Remove this tag's children
1987 removeTagItem(listManager.getTagIndex().get(j).getGuid());
1990 //Now, remove this tag
1991 removeListTagName(guid);
1992 conn.getTagTable().expungeTag(guid, true);
1993 for (int a=0; a<listManager.getTagIndex().size(); a++) {
1994 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
1995 listManager.getTagIndex().remove(a);
2000 // Setup the tree containing the user's tags
2001 private void initializeTagTree() {
2002 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2003 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2004 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2005 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2006 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2007 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2009 // Listener when a tag is selected
2010 private void tagTreeSelection() {
2011 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2014 clearAttributeFilter();
2015 clearSavedSearchFilter();
2017 menuBar.noteRestoreAction.setVisible(false);
2019 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2020 QTreeWidgetItem currentSelection;
2021 selectedTagGUIDs.clear();
2022 for (int i=0; i<selections.size(); i++) {
2023 currentSelection = selections.get(i);
2024 selectedTagGUIDs.add(currentSelection.text(2));
2026 if (selections.size() > 0) {
2027 menuBar.tagEditAction.setEnabled(true);
2028 menuBar.tagDeleteAction.setEnabled(true);
2029 menuBar.tagIconAction.setEnabled(true);
2032 menuBar.tagEditAction.setEnabled(false);
2033 menuBar.tagDeleteAction.setEnabled(false);
2034 menuBar.tagIconAction.setEnabled(true);
2036 listManager.setSelectedTags(selectedTagGUIDs);
2037 listManager.loadNotesIndex();
2038 noteIndexUpdated(false);
2039 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2041 // trigger the tag index to be refreshed
2042 @SuppressWarnings("unused")
2043 private void tagIndexUpdated() {
2044 tagIndexUpdated(true);
2046 private void tagIndexUpdated(boolean reload) {
2047 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2048 if (selectedTagGUIDs == null)
2049 selectedTagGUIDs = new ArrayList<String>();
2051 listManager.reloadTagIndex();
2053 tagTree.blockSignals(true);
2055 tagTree.setIcons(conn.getTagTable().getAllIcons());
2056 tagTree.load(listManager.getTagIndex());
2058 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2059 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2061 selectedTagGUIDs.remove(i);
2063 tagTree.blockSignals(false);
2065 browserWindow.setTag(getTagNamesForNote(currentNote));
2066 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2068 // Show/Hide note information
2069 private void toggleTagWindow() {
2070 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2071 if (tagTree.isVisible())
2075 menuBar.hideTags.setChecked(tagTree.isVisible());
2076 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2077 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2079 // A note's tags have been updated
2080 @SuppressWarnings("unused")
2081 private void updateNoteTags(String guid, List<String> tags) {
2082 // Save any new tags. We'll need them later.
2083 List<String> newTags = new ArrayList<String>();
2084 for (int i=0; i<tags.size(); i++) {
2085 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2086 newTags.add(tags.get(i));
2089 listManager.saveNoteTags(guid, tags);
2090 listManager.countTagResults(listManager.getNoteIndex());
2091 StringBuffer names = new StringBuffer("");
2092 for (int i=0; i<tags.size(); i++) {
2093 names = names.append(tags.get(i));
2094 if (i<tags.size()-1) {
2095 names.append(Global.tagDelimeter + " ");
2098 browserWindow.setTag(names.toString());
2101 // Now, we need to add any new tags to the tag tree
2102 for (int i=0; i<newTags.size(); i++)
2103 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2105 // Get a string containing all tag names for a note
2106 private String getTagNamesForNote(Note n) {
2107 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2108 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2110 StringBuffer buffer = new StringBuffer(100);
2111 Vector<String> v = new Vector<String>();
2112 List<String> guids = n.getTagGuids();
2117 for (int i=0; i<guids.size(); i++) {
2118 v.add(listManager.getTagNameByGuid(guids.get(i)));
2120 Comparator<String> comparator = Collections.reverseOrder();
2121 Collections.sort(v,comparator);
2122 Collections.reverse(v);
2124 for (int i = 0; i<v.size(); i++) {
2126 buffer.append(", ");
2127 buffer.append(v.get(i));
2130 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2131 return buffer.toString();
2133 // Tags were added via dropping notes from the note list
2134 @SuppressWarnings("unused")
2135 private void tagsAdded(String noteGuid, String tagGuid) {
2136 String tagName = null;
2137 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2138 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2139 tagName = listManager.getTagIndex().get(i).getName();
2140 i=listManager.getTagIndex().size();
2143 if (tagName == null)
2146 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2147 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2148 List<String> tagNames = new ArrayList<String>();
2149 tagNames.add(new String(tagName));
2150 Note n = listManager.getMasterNoteIndex().get(i);
2151 for (int j=0; j<n.getTagNames().size(); j++) {
2152 tagNames.add(new String(n.getTagNames().get(j)));
2154 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2155 if (n.getGuid().equals(currentNoteGuid)) {
2156 Collections.sort(tagNames);
2157 String display = "";
2158 for (int j=0; j<tagNames.size(); j++) {
2159 display = display+tagNames.get(j);
2160 if (j+2<tagNames.size())
2161 display = display+Global.tagDelimeter+" ";
2163 browserWindow.setTag(display);
2165 i=listManager.getMasterNoteIndex().size();
2170 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2172 private void clearTagFilter() {
2173 tagTree.blockSignals(true);
2174 tagTree.clearSelection();
2175 menuBar.noteRestoreAction.setVisible(false);
2176 menuBar.tagEditAction.setEnabled(false);
2177 menuBar.tagDeleteAction.setEnabled(false);
2178 menuBar.tagIconAction.setEnabled(false);
2179 selectedTagGUIDs.clear();
2180 listManager.setSelectedTags(selectedTagGUIDs);
2181 tagTree.blockSignals(false);
2183 // Change the icon for a tag
2184 @SuppressWarnings("unused")
2185 private void setTagIcon() {
2186 QTreeWidgetItem currentSelection;
2187 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2188 if (selections.size() == 0)
2191 currentSelection = selections.get(0);
2192 String guid = currentSelection.text(2);
2194 QIcon currentIcon = currentSelection.icon(0);
2195 QIcon icon = conn.getTagTable().getIcon(guid);
2198 dialog = new SetIcon(currentIcon, saveLastPath);
2199 dialog.setUseDefaultIcon(true);
2201 dialog = new SetIcon(icon, saveLastPath);
2202 dialog.setUseDefaultIcon(false);
2205 if (dialog.okPressed()) {
2206 saveLastPath = dialog.getPath();
2207 QIcon newIcon = dialog.getIcon();
2208 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2209 if (newIcon == null)
2210 newIcon = new QIcon(iconPath+"tag.png");
2211 currentSelection.setIcon(0, newIcon);
2217 //***************************************************************
2218 //***************************************************************
2219 //** These functions deal with Saved Search menu items
2220 //***************************************************************
2221 //***************************************************************
2222 // Add a new notebook
2223 @SuppressWarnings("unused")
2224 private void addSavedSearch() {
2225 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2226 SavedSearchEdit edit = new SavedSearchEdit();
2227 edit.setSearchList(listManager.getSavedSearchIndex());
2230 if (!edit.okPressed())
2233 Calendar currentTime = new GregorianCalendar();
2234 Long l = new Long(currentTime.getTimeInMillis());
2235 String randint = new String(Long.toString(l));
2237 SavedSearch search = new SavedSearch();
2238 search.setUpdateSequenceNum(0);
2239 search.setGuid(randint);
2240 search.setName(edit.getName());
2241 search.setQuery(edit.getQuery());
2242 search.setFormat(QueryFormat.USER);
2243 listManager.getSavedSearchIndex().add(search);
2244 conn.getSavedSearchTable().addSavedSearch(search, true);
2245 savedSearchIndexUpdated();
2246 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2248 // Edit an existing tag
2249 @SuppressWarnings("unused")
2250 private void editSavedSearch() {
2251 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2252 SavedSearchEdit edit = new SavedSearchEdit();
2253 edit.setTitle(tr("Edit Search"));
2254 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2255 QTreeWidgetItem currentSelection;
2256 currentSelection = selections.get(0);
2257 String guid = currentSelection.text(1);
2258 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2259 edit.setName(currentSelection.text(0));
2260 edit.setQuery(s.getQuery());
2261 edit.setSearchList(listManager.getSavedSearchIndex());
2264 if (!edit.okPressed())
2267 List<SavedSearch> list = listManager.getSavedSearchIndex();
2268 SavedSearch search = null;
2269 boolean found = false;
2270 for (int i=0; i<list.size(); i++) {
2271 search = list.get(i);
2272 if (search.getGuid().equals(guid)) {
2279 search.setName(edit.getName());
2280 search.setQuery(edit.getQuery());
2281 conn.getSavedSearchTable().updateSavedSearch(search, true);
2282 savedSearchIndexUpdated();
2283 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2285 // Delete an existing tag
2286 @SuppressWarnings("unused")
2287 private void deleteSavedSearch() {
2288 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2290 if (QMessageBox.question(this, "Confirmation", "Delete the selected search?",
2291 QMessageBox.StandardButton.Yes,
2292 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2296 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2297 for (int i=selections.size()-1; i>=0; i--) {
2298 QTreeWidgetItem currentSelection;
2299 currentSelection = selections.get(i);
2300 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2301 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2302 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2303 listManager.getSavedSearchIndex().remove(j);
2304 j=listManager.getSavedSearchIndex().size()+1;
2307 selections.remove(i);
2309 savedSearchIndexUpdated();
2310 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2312 // Setup the tree containing the user's tags
2313 private void initializeSavedSearchTree() {
2314 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2315 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2316 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2318 // Listener when a tag is selected
2319 @SuppressWarnings("unused")
2320 private void savedSearchTreeSelection() {
2321 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2323 clearNotebookFilter();
2326 clearAttributeFilter();
2328 String currentGuid = selectedSavedSearchGUID;
2329 menuBar.savedSearchEditAction.setEnabled(true);
2330 menuBar.savedSearchDeleteAction.setEnabled(true);
2331 menuBar.savedSearchIconAction.setEnabled(true);
2332 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2333 QTreeWidgetItem currentSelection;
2334 selectedSavedSearchGUID = "";
2335 for (int i=0; i<selections.size(); i++) {
2336 currentSelection = selections.get(i);
2337 if (currentSelection.text(1).equals(currentGuid)) {
2338 currentSelection.setSelected(false);
2340 selectedSavedSearchGUID = currentSelection.text(1);
2342 // i = selections.size() +1;
2345 // There is the potential for no notebooks to be selected if this
2346 // happens then we make it look like all notebooks were selecetd.
2347 // If that happens, just select the "all notebooks"
2348 if (selections.size()==0) {
2349 clearSavedSearchFilter();
2351 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2353 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2355 private void clearSavedSearchFilter() {
2356 menuBar.savedSearchEditAction.setEnabled(false);
2357 menuBar.savedSearchDeleteAction.setEnabled(false);
2358 menuBar.savedSearchIconAction.setEnabled(false);
2359 savedSearchTree.blockSignals(true);
2360 savedSearchTree.clearSelection();
2361 savedSearchTree.blockSignals(false);
2362 selectedSavedSearchGUID = "";
2363 searchField.setEditText("");
2364 searchPerformed = false;
2365 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2367 // trigger the tag index to be refreshed
2368 private void savedSearchIndexUpdated() {
2369 if (selectedSavedSearchGUID == null)
2370 selectedSavedSearchGUID = new String();
2371 savedSearchTree.blockSignals(true);
2372 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2373 savedSearchTree.load(listManager.getSavedSearchIndex());
2374 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2375 savedSearchTree.blockSignals(false);
2377 // trigger when the saved search selection changes
2378 @SuppressWarnings("unused")
2379 private void updateSavedSearchSelection() {
2380 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2382 menuBar.savedSearchEditAction.setEnabled(true);
2383 menuBar.savedSearchDeleteAction.setEnabled(true);
2384 menuBar.savedSearchIconAction.setEnabled(true);
2385 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2387 if (selections.size() > 0) {
2388 menuBar.savedSearchEditAction.setEnabled(true);
2389 menuBar.savedSearchDeleteAction.setEnabled(true);
2390 menuBar.savedSearchIconAction.setEnabled(true);
2391 selectedSavedSearchGUID = selections.get(0).text(1);
2392 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2393 searchField.setEditText(s.getQuery());
2395 menuBar.savedSearchEditAction.setEnabled(false);
2396 menuBar.savedSearchDeleteAction.setEnabled(false);
2397 menuBar.savedSearchIconAction.setEnabled(false);
2398 selectedSavedSearchGUID = "";
2399 searchField.setEditText("");
2401 searchFieldChanged();
2403 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2407 // Show/Hide note information
2408 private void toggleSavedSearchWindow() {
2409 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2410 if (savedSearchTree.isVisible())
2411 savedSearchTree.hide();
2413 savedSearchTree.show();
2414 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2416 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2417 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2419 // Change the icon for a saved search
2420 @SuppressWarnings("unused")
2421 private void setSavedSearchIcon() {
2422 QTreeWidgetItem currentSelection;
2423 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2424 if (selections.size() == 0)
2427 currentSelection = selections.get(0);
2428 String guid = currentSelection.text(1);
2430 QIcon currentIcon = currentSelection.icon(0);
2431 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2434 dialog = new SetIcon(currentIcon, saveLastPath);
2435 dialog.setUseDefaultIcon(true);
2437 dialog = new SetIcon(icon, saveLastPath);
2438 dialog.setUseDefaultIcon(false);
2441 if (dialog.okPressed()) {
2442 saveLastPath = dialog.getPath();
2443 QIcon newIcon = dialog.getIcon();
2444 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2445 if (newIcon == null)
2446 newIcon = new QIcon(iconPath+"search.png");
2447 currentSelection.setIcon(0, newIcon);
2455 //***************************************************************
2456 //***************************************************************
2457 //** These functions deal with Help menu & tool menu items
2458 //***************************************************************
2459 //***************************************************************
2460 // Show database status
2461 @SuppressWarnings("unused")
2462 private void databaseStatus() {
2464 indexRunner.interrupt = true;
2465 int dirty = conn.getNoteTable().getDirtyCount();
2466 int unindexed = conn.getNoteTable().getUnindexedCount();
2467 DatabaseStatus status = new DatabaseStatus();
2468 status.setUnsynchronized(dirty);
2469 status.setUnindexed(unindexed);
2470 status.setNoteCount(conn.getNoteTable().getNoteCount());
2471 status.setNotebookCount(listManager.getNotebookIndex().size());
2472 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2473 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2474 status.setTagCount(listManager.getTagIndex().size());
2475 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2476 status.setWordCount(conn.getWordsTable().getWordCount());
2480 // Compact the database
2481 @SuppressWarnings("unused")
2482 private void compactDatabase() {
2483 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2484 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2485 "but please be aware that depending upon the size of your database this can be time consuming " +
2486 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2487 QMessageBox.StandardButton.Yes,
2488 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2491 setMessage("Compacting database.");
2493 listManager.compactDatabase();
2495 setMessage("Database compact is complete.");
2496 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2498 @SuppressWarnings("unused")
2499 private void accountInformation() {
2500 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2501 AccountDialog dialog = new AccountDialog();
2503 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2505 @SuppressWarnings("unused")
2506 private void releaseNotes() {
2507 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2508 QDialog dialog = new QDialog(this);
2509 QHBoxLayout layout = new QHBoxLayout();
2510 QTextEdit textBox = new QTextEdit();
2511 layout.addWidget(textBox);
2512 textBox.setReadOnly(true);
2513 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2514 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2515 QIODevice.OpenModeFlag.Text)))
2517 textBox.setText(file.readAll().toString());
2519 dialog.setWindowTitle(tr("Release Notes"));
2520 dialog.setLayout(layout);
2522 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2524 // Called when user picks Log from the help menu
2525 @SuppressWarnings("unused")
2526 private void logger() {
2527 logger.log(logger.HIGH, "Entering NeverNote.logger");
2528 LogFileDialog dialog = new LogFileDialog(emitLog);
2530 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2532 // Menu option "help/about" was selected
2533 @SuppressWarnings("unused")
2534 private void about() {
2535 logger.log(logger.HIGH, "Entering NeverNote.about");
2536 QMessageBox.about(this,
2537 tr("About NeverNote"),
2538 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2540 +tr("<hr></center>Evernote"
2541 +"An Open Source Evernote Client.<br><br>"
2542 +"Licensed under GPL v2. <br><hr><br>"
2543 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2544 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2545 +"PDFRenderer is licened under the LGPL<br>"
2546 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2547 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2548 +"Jazzy is licened under the LGPL<br>"
2549 +"Java is a registered trademark of Oracle Corporation.<br><hr>"));
2550 logger.log(logger.HIGH, "Leaving NeverNote.about");
2552 // Hide the entire left hand side
2553 @SuppressWarnings("unused")
2554 private void toggleLeftSide() {
2557 hidden = !menuBar.hideLeftSide.isChecked();
2558 menuBar.hideLeftSide.setChecked(!hidden);
2560 if (notebookTree.isVisible() != hidden)
2561 toggleNotebookWindow();
2562 if (savedSearchTree.isVisible() != hidden)
2563 toggleSavedSearchWindow();
2564 if (tagTree.isVisible() != hidden)
2566 if (attributeTree.isVisible() != hidden)
2567 toggleAttributesWindow();
2568 if (trashTree.isVisible() != hidden)
2569 toggleTrashWindow();
2571 Global.saveWindowVisible("leftPanel", hidden);
2574 public void checkForUpdates() {
2575 // Send off thread to check for a new version
2576 versionChecker = new QNetworkAccessManager(this);
2577 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2578 QNetworkRequest request = new QNetworkRequest();
2579 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2580 versionChecker.get(request);
2582 @SuppressWarnings("unused")
2583 private void upgradeFileRead(QNetworkReply reply) {
2584 if (!reply.isReadable())
2587 String winVersion = Global.version;
2588 String osxVersion = Global.version;
2589 String linuxVersion = Global.version;
2590 String linux64Version = Global.version;
2591 String version = Global.version;
2593 // Determine the versions available
2594 QByteArray data = reply.readLine();
2595 while (data != null && !reply.atEnd()) {
2596 String line = data.toString();
2598 if (line.contains(":"))
2599 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2602 if (line.toLowerCase().contains("windows"))
2603 winVersion = lineVersion;
2604 else if (line.toLowerCase().contains("os-x"))
2605 osxVersion = lineVersion;
2606 else if (line.toLowerCase().contains("linux amd64"))
2607 linux64Version = lineVersion;
2608 else if (line.toLowerCase().contains("linux i386"))
2609 linuxVersion = lineVersion;
2610 else if (line.toLowerCase().contains("default"))
2611 version = lineVersion;
2613 // Read the next line
2614 data = reply.readLine();
2617 // Now we need to determine what system we are on.
2618 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2619 version = winVersion;
2620 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2621 version = osxVersion;
2622 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2623 if (System.getProperty("os.arch").contains("amd64") ||
2624 System.getProperty("os.arch").contains("x86_64"))
2625 version = linux64Version;
2627 version = linuxVersion;
2631 for (String validVersion : Global.validVersions) {
2632 if (version.equals(validVersion))
2636 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2638 if (dialog.remindMe())
2639 Global.setCheckVersionUpgrade(true);
2641 Global.setCheckVersionUpgrade(false);
2645 //***************************************************************
2646 //***************************************************************
2647 //** These functions deal with the Toolbar
2648 //***************************************************************
2649 //***************************************************************
2650 @SuppressWarnings("unused")
2651 private void focusSearch() {
2652 searchField.setFocus();
2655 // Text in the search bar has been cleared
2656 private void searchFieldCleared() {
2659 // This is done because we want to force a reload of
2660 // images. Some images we may want to highlight the text.
2661 readOnlyCache.clear();
2662 inkNoteCache.clear();
2664 QWebSettings.setMaximumPagesInCache(0);
2665 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2667 searchField.setEditText("");
2668 saveNoteColumnPositions();
2669 saveNoteIndexWidth();
2670 noteIndexUpdated(true);
2671 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2672 currentNote = listManager.getNoteIndex().get(0);
2673 currentNoteGuid = currentNote.getGuid();
2675 if (currentNote != null)
2676 loadNoteBrowserInformation(browserWindow);
2678 // text in the search bar changed. We only use this to tell if it was cleared,
2679 // otherwise we trigger off searchFieldChanged.
2680 @SuppressWarnings("unused")
2681 private void searchFieldTextChanged(String text) {
2682 QWebSettings.setMaximumPagesInCache(0);
2683 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2685 if (text.trim().equals("")) {
2686 searchFieldCleared();
2687 if (searchPerformed) {
2689 // This is done because we want to force a reload of
2690 // images. Some images we may want to highlight the text.
2692 readOnlyCache.clear();
2693 inkNoteCache.clear();
2695 listManager.setEnSearch("");
2696 listManager.loadNotesIndex();
2697 refreshEvernoteNote(true);
2698 noteIndexUpdated(false);
2700 searchPerformed = false;
2703 // Text in the toolbar has changed
2704 private void searchFieldChanged() {
2705 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2707 readOnlyCache.clear();
2708 inkNoteCache.clear();
2709 saveNoteColumnPositions();
2710 saveNoteIndexWidth();
2711 String text = searchField.currentText();
2712 listManager.setEnSearch(text.trim());
2713 listManager.loadNotesIndex();
2714 //--->>> noteIndexUpdated(true);
2715 noteIndexUpdated(false);
2716 refreshEvernoteNote(true);
2717 searchPerformed = true;
2718 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2721 // Build the window tool bar
2722 private void setupToolBar() {
2723 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2724 toolBar = addToolBar(tr("Tool Bar"));
2725 menuBar.setupToolBarVisible();
2726 if (!Global.isWindowVisible("toolBar"))
2727 toolBar.setVisible(false);
2729 toolBar.setVisible(true);
2731 prevButton = toolBar.addAction("Previous");
2732 QIcon prevIcon = new QIcon(iconPath+"back.png");
2733 prevButton.setIcon(prevIcon);
2734 prevButton.triggered.connect(this, "previousViewedAction()");
2735 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2737 nextButton = toolBar.addAction("Next");
2738 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2739 nextButton.setIcon(nextIcon);
2740 nextButton.triggered.connect(this, "nextViewedAction()");
2741 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2743 upButton = toolBar.addAction("Up");
2744 QIcon upIcon = new QIcon(iconPath+"up.png");
2745 upButton.setIcon(upIcon);
2746 upButton.triggered.connect(this, "upAction()");
2747 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2750 downButton = toolBar.addAction("Down");
2751 QIcon downIcon = new QIcon(iconPath+"down.png");
2752 downButton.setIcon(downIcon);
2753 downButton.triggered.connect(this, "downAction()");
2754 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2756 synchronizeButton = toolBar.addAction("Synchronize");
2757 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2758 synchronizeIconAngle = 0;
2759 synchronizeButton.triggered.connect(this, "evernoteSync()");
2760 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2762 printButton = toolBar.addAction("Print");
2763 QIcon printIcon = new QIcon(iconPath+"print.png");
2764 printButton.setIcon(printIcon);
2765 printButton.triggered.connect(this, "printNote()");
2766 togglePrintButton(Global.isToolbarButtonVisible("print"));
2768 tagButton = toolBar.addAction("Tag");
2769 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2770 tagButton.setIcon(tagIcon);
2771 tagButton.triggered.connect(browserWindow, "modifyTags()");
2772 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2774 attributeButton = toolBar.addAction("Attributes");
2775 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2776 attributeButton.setIcon(attributeIcon);
2777 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2778 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2780 emailButton = toolBar.addAction("Email");
2781 QIcon emailIcon = new QIcon(iconPath+"email.png");
2782 emailButton.setIcon(emailIcon);
2783 emailButton.triggered.connect(this, "emailNote()");
2784 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2786 deleteButton = toolBar.addAction("Delete");
2787 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2788 deleteButton.setIcon(deleteIcon);
2789 deleteButton.triggered.connect(this, "deleteNote()");
2790 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2792 newButton = toolBar.addAction("New");
2793 QIcon newIcon = new QIcon(iconPath+"new.png");
2794 newButton.triggered.connect(this, "addNote()");
2795 newButton.setIcon(newIcon);
2796 toggleNewButton(Global.isToolbarButtonVisible("new"));
2798 allNotesButton = toolBar.addAction("All Notes");
2799 QIcon allIcon = new QIcon(iconPath+"books.png");
2800 allNotesButton.triggered.connect(this, "allNotes()");
2801 allNotesButton.setIcon(allIcon);
2802 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2804 toolBar.addSeparator();
2805 toolBar.addWidget(new QLabel(tr("Quota:")));
2806 toolBar.addWidget(quotaBar);
2807 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2809 toolBar.addSeparator();
2812 zoomSpinner = new QSpinBox();
2813 zoomSpinner.setMinimum(10);
2814 zoomSpinner.setMaximum(1000);
2815 zoomSpinner.setAccelerated(true);
2816 zoomSpinner.setSingleStep(10);
2817 zoomSpinner.setValue(100);
2818 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
2819 toolBar.addWidget(new QLabel(tr("Zoom")));
2820 toolBar.addWidget(zoomSpinner);
2822 //toolBar.addWidget(new QLabel(" "));
2823 toolBar.addSeparator();
2824 toolBar.addWidget(new QLabel(tr(" Search:")));
2825 toolBar.addWidget(searchField);
2826 QSizePolicy sizePolicy = new QSizePolicy();
2827 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2828 searchField.setSizePolicy(sizePolicy);
2829 searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2831 searchClearButton = toolBar.addAction("Search Clear");
2832 QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2833 searchClearButton.setIcon(searchClearIcon);
2834 searchClearButton.triggered.connect(this, "searchFieldCleared()");
2835 toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2837 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2839 // Update the sychronize button picture
2841 public QMenu createPopupMenu() {
2842 QMenu contextMenu = super.createPopupMenu();
2844 contextMenu.addSeparator();
2845 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2846 contextMenu.addAction(prevAction);
2847 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2849 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2850 contextMenu.addAction(nextAction);
2851 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2853 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2854 contextMenu.addAction(upAction);
2855 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2857 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2858 contextMenu.addAction(downAction);
2859 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2861 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2862 contextMenu.addAction(synchronizeAction);
2863 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
2865 QAction printAction = addContextAction("print", tr("Print"));
2866 contextMenu.addAction(printAction);
2867 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
2869 QAction tagAction = addContextAction("tag", tr("Tag"));
2870 contextMenu.addAction(tagAction);
2871 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
2873 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
2874 contextMenu.addAction(attributeAction);
2875 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
2877 QAction emailAction = addContextAction("email", tr("Email"));
2878 contextMenu.addAction(emailAction);
2879 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
2881 QAction deleteAction = addContextAction("delete", tr("Delete"));
2882 contextMenu.addAction(deleteAction);
2883 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
2885 QAction newAction = addContextAction("new", tr("Add"));
2886 contextMenu.addAction(newAction);
2887 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
2889 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
2890 contextMenu.addAction(allNotesAction);
2891 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
2893 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
2894 contextMenu.addAction(searchClearAction);
2895 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
2900 private QAction addContextAction(String config, String name) {
2901 QAction newAction = new QAction(this);
2902 newAction.setText(name);
2903 newAction.setCheckable(true);
2904 newAction.setChecked(Global.isToolbarButtonVisible(config));
2907 private void togglePrevArrowButton(Boolean toggle) {
2908 prevButton.setVisible(toggle);
2909 Global.saveToolbarButtonsVisible("prevArrow", toggle);
2911 private void toggleNextArrowButton(Boolean toggle) {
2912 nextButton.setVisible(toggle);
2913 Global.saveToolbarButtonsVisible("nextArrow", toggle);
2915 private void toggleUpArrowButton(Boolean toggle) {
2916 upButton.setVisible(toggle);
2917 Global.saveToolbarButtonsVisible("upArrow", toggle);
2919 private void toggleDownArrowButton(Boolean toggle) {
2920 downButton.setVisible(toggle);
2921 Global.saveToolbarButtonsVisible("downArrow", toggle);
2923 private void toggleSynchronizeButton(Boolean toggle) {
2924 synchronizeButton.setVisible(toggle);
2925 Global.saveToolbarButtonsVisible("synchronize", toggle);
2927 private void togglePrintButton(Boolean toggle) {
2928 printButton.setVisible(toggle);
2929 Global.saveToolbarButtonsVisible("print", toggle);
2931 private void toggleTagButton(Boolean toggle) {
2932 tagButton.setVisible(toggle);
2933 Global.saveToolbarButtonsVisible("tag", toggle);
2935 private void toggleAttributeButton(Boolean toggle) {
2936 attributeButton.setVisible(toggle);
2937 Global.saveToolbarButtonsVisible("attribute", toggle);
2939 private void toggleEmailButton(Boolean toggle) {
2940 emailButton.setVisible(toggle);
2941 Global.saveToolbarButtonsVisible("email", toggle);
2943 private void toggleDeleteButton(Boolean toggle) {
2944 deleteButton.setVisible(toggle);
2945 Global.saveToolbarButtonsVisible("delete", toggle);
2947 private void toggleNewButton(Boolean toggle) {
2948 newButton.setVisible(toggle);
2949 Global.saveToolbarButtonsVisible("new", toggle);
2951 private void toggleAllNotesButton(Boolean toggle) {
2952 allNotesButton.setVisible(toggle);
2953 Global.saveToolbarButtonsVisible("allNotes", toggle);
2955 private void toggleSearchClearButton(Boolean toggle) {
2956 searchClearButton.setVisible(toggle);
2957 Global.saveToolbarButtonsVisible("searchClear", toggle);
2964 @SuppressWarnings("unused")
2965 private void updateSyncButton() {
2967 if (syncIcons == null) {
2968 syncIcons = new ArrayList<QPixmap>();
2970 synchronizeIconAngle = 0;
2971 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
2973 for (int i=0; i<=360; i++) {
2974 QPixmap rotatedPix = new QPixmap(pix.size());
2975 QPainter p = new QPainter(rotatedPix);
2976 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
2977 QSize size = pix.size();
2978 p.translate(size.width()/2, size.height()/2);
2981 p.setBackgroundMode(BGMode.OpaqueMode);
2982 p.translate(-size.width()/2, -size.height()/2);
2983 p.drawPixmap(0,0, pix);
2985 syncIcons.add(rotatedPix);
2989 synchronizeIconAngle++;
2990 if (synchronizeIconAngle > 359)
2991 synchronizeIconAngle=0;
2992 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
2995 // Synchronize with Evernote
2996 @SuppressWarnings("unused")
2997 private void evernoteSync() {
2998 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
2999 if (!Global.isConnected)
3001 if (Global.isConnected)
3002 synchronizeAnimationTimer.start(5);
3003 // synchronizeAnimationTimer.start(200);
3005 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3007 private void updateQuotaBar() {
3008 long limit = Global.getUploadLimit();
3009 long amount = Global.getUploadAmount();
3010 if (amount>0 && limit>0) {
3011 int percent =(int)(amount*100/limit);
3012 quotaBar.setValue(percent);
3014 quotaBar.setValue(0);
3017 @SuppressWarnings("unused")
3018 private void zoomChanged() {
3019 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3022 //****************************************************************
3023 //****************************************************************
3024 //* System Tray functions
3025 //****************************************************************
3026 //****************************************************************
3027 private void trayToggleVisible() {
3032 if (windowMaximized)
3039 @SuppressWarnings("unused")
3040 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3041 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3042 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3043 trayToggleVisible();
3048 //***************************************************************
3049 //***************************************************************
3050 //** These functions deal with the trash tree
3051 //***************************************************************
3052 //***************************************************************
3053 // Setup the tree containing the trash.
3054 @SuppressWarnings("unused")
3055 private void trashTreeSelection() {
3056 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3058 clearNotebookFilter();
3060 clearAttributeFilter();
3061 clearSavedSearchFilter();
3063 String tempGuid = currentNoteGuid;
3065 // currentNoteGuid = "";
3066 currentNote = new Note();
3067 selectedNoteGUIDs.clear();
3068 listManager.getSelectedNotebooks().clear();
3069 listManager.getSelectedTags().clear();
3070 listManager.setSelectedSavedSearch("");
3071 browserWindow.clear();
3073 // toggle the add buttons
3074 newButton.setEnabled(!newButton.isEnabled());
3075 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3076 menuBar.noteAdd.setVisible(true);
3078 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3079 if (selections.size() == 0) {
3080 currentNoteGuid = trashNoteGuid;
3081 trashNoteGuid = tempGuid;
3082 Global.showDeleted = false;
3083 menuBar.noteRestoreAction.setEnabled(false);
3084 menuBar.noteRestoreAction.setVisible(false);
3087 currentNoteGuid = trashNoteGuid;
3088 trashNoteGuid = tempGuid;
3089 menuBar.noteRestoreAction.setEnabled(true);
3090 menuBar.noteRestoreAction.setVisible(true);
3091 Global.showDeleted = true;
3093 listManager.loadNotesIndex();
3094 noteIndexUpdated(false);
3095 //// browserWindow.setEnabled(newButton.isEnabled());
3096 browserWindow.setReadOnly(!newButton.isEnabled());
3097 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3099 // Empty the trash file
3100 @SuppressWarnings("unused")
3101 private void emptyTrash() {
3102 // browserWindow.clear();
3103 listManager.emptyTrash();
3104 if (trashTree.selectedItems().size() > 0) {
3105 listManager.getSelectedNotebooks().clear();
3106 listManager.getSelectedTags().clear();
3107 listManager.setSelectedSavedSearch("");
3108 newButton.setEnabled(!newButton.isEnabled());
3109 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3110 menuBar.noteAdd.setVisible(true);
3111 browserWindow.clear();
3114 clearNotebookFilter();
3115 clearSavedSearchFilter();
3116 clearAttributeFilter();
3118 Global.showDeleted = false;
3119 menuBar.noteRestoreAction.setEnabled(false);
3120 menuBar.noteRestoreAction.setVisible(false);
3122 listManager.loadNotesIndex();
3123 //--->>> noteIndexUpdated(true);
3124 noteIndexUpdated(false);
3127 // Show/Hide trash window
3128 private void toggleTrashWindow() {
3129 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3130 if (trashTree.isVisible())
3134 menuBar.hideTrash.setChecked(trashTree.isVisible());
3136 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3137 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3139 private void clearTrashFilter() {
3140 Global.showDeleted = false;
3141 newButton.setEnabled(true);
3142 menuBar.noteAdd.setEnabled(true);
3143 menuBar.noteAdd.setVisible(true);
3144 trashTree.blockSignals(true);
3145 trashTree.clearSelection();
3146 trashTree.blockSignals(false);
3151 //***************************************************************
3152 //***************************************************************
3153 //** These functions deal with connection settings
3154 //***************************************************************
3155 //***************************************************************
3156 // SyncRunner had a problem and things are disconnected
3157 @SuppressWarnings("unused")
3158 private void remoteErrorDisconnect() {
3159 menuBar.connectAction.setText(tr("Connect"));
3160 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3161 menuBar.synchronizeAction.setEnabled(false);
3162 Global.isConnected = false;
3163 synchronizeAnimationTimer.stop();
3166 // Do a manual connect/disconnect
3167 private void remoteConnect() {
3168 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3170 if (Global.isConnected) {
3171 Global.isConnected = false;
3172 syncRunner.enDisconnect();
3173 setupConnectMenuOptions();
3178 AESEncrypter aes = new AESEncrypter();
3180 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3181 } catch (FileNotFoundException e) {
3182 // File not found, so we'll just get empty strings anyway.
3185 if (Global.getProxyValue("url").equals("")) {
3186 System.setProperty("http.proxyHost","") ;
3187 System.setProperty("http.proxyPort", "") ;
3188 System.setProperty("https.proxyHost","") ;
3189 System.setProperty("https.proxyPort", "") ;
3192 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3193 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3194 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3195 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3197 if (Global.getProxyValue("userid").equals("")) {
3198 Authenticator.setDefault(new Authenticator() {
3200 protected PasswordAuthentication getPasswordAuthentication() {
3202 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3208 syncRunner.userStoreUrl = Global.userStoreUrl;
3209 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3210 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3212 String userid = aes.getUserid();
3213 String password = aes.getPassword();
3214 if (!userid.equals("") && !password.equals("")) {
3215 Global.username = userid;
3216 Global.password = password;
3217 syncRunner.username = Global.username;
3218 syncRunner.password = Global.password;
3219 syncRunner.enConnect();
3222 Global.isConnected = syncRunner.isConnected;
3224 if (!Global.isConnected) {
3225 // Show the login dialog box
3226 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3227 LoginDialog login = new LoginDialog();
3230 if (!login.okPressed()) {
3234 Global.username = login.getUserid();
3235 Global.password = login.getPassword();
3237 syncRunner.username = Global.username;
3238 syncRunner.password = Global.password;
3239 syncRunner.enConnect();
3240 Global.isConnected = syncRunner.isConnected;
3243 if (!Global.isConnected)
3246 setupConnectMenuOptions();
3247 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3249 private void setupConnectMenuOptions() {
3250 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3251 if (!Global.isConnected) {
3252 menuBar.connectAction.setText(tr("Connect"));
3253 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3254 menuBar.synchronizeAction.setEnabled(false);
3256 menuBar.connectAction.setText(tr("Disconnect"));
3257 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3258 menuBar.synchronizeAction.setEnabled(true);
3260 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3265 //***************************************************************
3266 //***************************************************************
3267 //** These functions deal with the GUI Attribute tree
3268 //***************************************************************
3269 //***************************************************************
3270 @SuppressWarnings("unused")
3271 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3273 // clearTagFilter();
3274 // clearNotebookFilter();
3276 // clearSavedSearchFilter();
3278 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3279 if (item.childCount() > 0) {
3280 item.setSelected(false);
3282 Global.createdBeforeFilter.reset();
3283 Global.createdSinceFilter.reset();
3284 Global.changedBeforeFilter.reset();
3285 Global.changedSinceFilter.reset();
3286 Global.containsFilter.reset();
3287 attributeTreeSelected = item;
3288 DateAttributeFilterTable f = null;
3289 f = findDateAttributeFilterTable(item.parent());
3291 f.select(item.parent().indexOfChild(item));
3293 Global.containsFilter.select(item.parent().indexOfChild(item));
3296 listManager.loadNotesIndex();
3297 noteIndexUpdated(false);
3300 attributeTreeSelected = null;
3301 item.setSelected(false);
3302 Global.createdBeforeFilter.reset();
3303 Global.createdSinceFilter.reset();
3304 Global.changedBeforeFilter.reset();
3305 Global.changedSinceFilter.reset();
3306 Global.containsFilter.reset();
3307 listManager.loadNotesIndex();
3308 noteIndexUpdated(false);
3310 // This determines what attribute filter we need, depending upon the selection
3311 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3312 if (w.parent() != null && w.childCount() > 0) {
3313 QTreeWidgetItem parent = w.parent();
3314 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3315 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3316 return Global.createdSinceFilter;
3317 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3318 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3319 return Global.createdBeforeFilter;
3320 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3321 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3322 return Global.changedSinceFilter;
3323 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3324 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3325 return Global.changedBeforeFilter;
3330 // Show/Hide attribute search window
3331 private void toggleAttributesWindow() {
3332 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3333 if (attributeTree.isVisible())
3334 attributeTree.hide();
3336 attributeTree.show();
3337 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3339 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3340 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3342 private void clearAttributeFilter() {
3343 Global.createdBeforeFilter.reset();
3344 Global.createdSinceFilter.reset();
3345 Global.changedBeforeFilter.reset();
3346 Global.changedSinceFilter.reset();
3347 Global.containsFilter.reset();
3348 attributeTreeSelected = null;
3349 attributeTree.blockSignals(true);
3350 attributeTree.clearSelection();
3351 attributeTree.blockSignals(false);
3355 //***************************************************************
3356 //***************************************************************
3357 //** These functions deal with the GUI Note index table
3358 //***************************************************************
3359 //***************************************************************
3360 // Initialize the note list table
3361 private void initializeNoteTable() {
3362 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3363 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3364 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3365 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3367 // Show/Hide trash window
3368 @SuppressWarnings("unused")
3369 private void toggleNoteListWindow() {
3370 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3371 if (noteTableView.isVisible())
3372 noteTableView.hide();
3374 noteTableView.show();
3375 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3377 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3378 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3380 // Handle the event that a user selects a note from the table
3381 @SuppressWarnings("unused")
3382 private void noteTableSelection() {
3383 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3385 if (historyGuids.size() == 0) {
3386 historyGuids.add(currentNoteGuid);
3387 historyPosition = 1;
3389 noteTableView.showColumn(Global.noteTableGuidPosition);
3391 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3392 if (!Global.isColumnVisible("guid"))
3393 noteTableView.hideColumn(Global.noteTableGuidPosition);
3395 if (selections.size() > 0) {
3397 menuBar.noteDuplicateAction.setEnabled(true);
3398 menuBar.noteOnlineHistoryAction.setEnabled(true);
3399 menuBar.noteMergeAction.setEnabled(true);
3400 selectedNoteGUIDs.clear();
3401 if (selections.size() != 1 || Global.showDeleted) {
3402 menuBar.noteDuplicateAction.setEnabled(false);
3404 if (selections.size() != 1 || !Global.isConnected) {
3405 menuBar.noteOnlineHistoryAction.setEnabled(false);
3407 if (selections.size() == 1) {
3408 menuBar.noteMergeAction.setEnabled(false);
3410 for (int i=0; i<selections.size(); i++) {
3411 int row = selections.get(i).row();
3413 upButton.setEnabled(false);
3415 upButton.setEnabled(true);
3416 if (row < listManager.getNoteTableModel().rowCount()-1)
3417 downButton.setEnabled(true);
3419 downButton.setEnabled(false);
3420 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3421 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3422 currentNoteGuid = (String)ix.values().toArray()[0];
3423 selectedNoteGUIDs.add(currentNoteGuid);
3427 nextButton.setEnabled(true);
3428 prevButton.setEnabled(true);
3430 int endPosition = historyGuids.size()-1;
3431 for (int j=historyPosition; j<=endPosition; j++) {
3432 historyGuids.remove(historyGuids.size()-1);
3434 historyGuids.add(currentNoteGuid);
3435 historyPosition = historyGuids.size();
3437 if (historyPosition <= 1)
3438 prevButton.setEnabled(false);
3439 if (historyPosition == historyGuids.size())
3440 nextButton.setEnabled(false);
3442 fromHistory = false;
3443 scrollToGuid(currentNoteGuid);
3444 refreshEvernoteNote(true);
3445 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3447 // Trigger a refresh when the note db has been updated
3448 private void noteIndexUpdated(boolean reload) {
3449 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3451 refreshEvernoteNoteList();
3452 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3453 noteTableView.load(reload);
3454 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3456 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3457 pos = noteTableView.proxyModel.rowCount();
3460 if (noteTableView.proxyModel.rowCount() == 0)
3463 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3465 currentNoteGuid = (String)i.data();
3466 noteTableView.selectRow(pos-1);
3471 scrollToGuid(currentNoteGuid);
3472 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3474 // Called when the list of notes is updated
3475 private void refreshEvernoteNoteList() {
3476 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3477 browserWindow.setDisabled(false);
3478 if (selectedNoteGUIDs == null)
3479 selectedNoteGUIDs = new ArrayList<String>();
3480 selectedNoteGUIDs.clear(); // clear out old entries
3482 String saveCurrentNoteGuid = new String();
3483 String tempNoteGuid = new String();
3485 historyGuids.clear();
3486 historyPosition = 0;
3487 prevButton.setEnabled(false);
3488 nextButton.setEnabled(false);
3490 if (currentNoteGuid == null)
3491 currentNoteGuid = new String();
3493 //determine current note guid
3494 for (Note note : listManager.getNoteIndex()) {
3495 tempNoteGuid = note.getGuid();
3496 if (currentNoteGuid.equals(tempNoteGuid)) {
3497 saveCurrentNoteGuid = tempNoteGuid;
3501 if (listManager.getNoteIndex().size() == 0) {
3502 currentNoteGuid = "";
3504 browserWindow.clear();
3505 browserWindow.setDisabled(true);
3508 if (!saveCurrentNoteGuid.equals("")) {
3509 refreshEvernoteNote(false);
3511 currentNoteGuid = "";
3513 reloadTagTree(false);
3515 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3517 // Called when the previous arrow button is clicked
3518 @SuppressWarnings("unused")
3519 private void previousViewedAction() {
3520 if (!prevButton.isEnabled())
3522 if (historyPosition == 0)
3525 if (historyPosition <= 0)
3527 String historyGuid = historyGuids.get(historyPosition-1);
3529 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3530 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3531 if (modelIndex != null) {
3532 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3533 String tableGuid = (String)ix.values().toArray()[0];
3534 if (tableGuid.equals(historyGuid)) {
3535 noteTableView.selectRow(i);
3541 @SuppressWarnings("unused")
3542 private void nextViewedAction() {
3543 if (!nextButton.isEnabled())
3545 String historyGuid = historyGuids.get(historyPosition);
3548 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3549 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3550 if (modelIndex != null) {
3551 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3552 String tableGuid = (String)ix.values().toArray()[0];
3553 if (tableGuid.equals(historyGuid)) {
3554 noteTableView.selectRow(i);
3560 // Called when the up arrow is clicked
3561 @SuppressWarnings("unused")
3562 private void upAction() {
3563 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3564 int row = selections.get(0).row();
3566 noteTableView.selectRow(row-1);
3569 // Called when the down arrow is clicked
3570 @SuppressWarnings("unused")
3571 private void downAction() {
3572 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3573 int row = selections.get(0).row();
3574 int max = listManager.getNoteTableModel().rowCount();
3576 noteTableView.selectRow(row+1);
3579 // Update a tag string for a specific note in the list
3580 @SuppressWarnings("unused")
3581 private void updateListTags(String guid, List<String> tags) {
3582 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3583 StringBuffer tagBuffer = new StringBuffer();
3584 for (int i=0; i<tags.size(); i++) {
3585 tagBuffer.append(tags.get(i));
3586 if (i<tags.size()-1)
3587 tagBuffer.append(", ");
3590 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3591 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3592 if (modelIndex != null) {
3593 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3594 String tableGuid = (String)ix.values().toArray()[0];
3595 if (tableGuid.equals(guid)) {
3596 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3597 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3598 noteTableView.proxyModel.invalidate();
3603 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3605 // Update a title for a specific note in the list
3606 @SuppressWarnings("unused")
3607 private void updateListAuthor(String guid, String author) {
3608 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3610 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3611 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3612 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3613 if (modelIndex != null) {
3614 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3615 String tableGuid = (String)ix.values().toArray()[0];
3616 if (tableGuid.equals(guid)) {
3617 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3618 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3619 noteTableView.proxyModel.invalidate();
3625 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3627 private void updateListNoteNotebook(String guid, String notebook) {
3628 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3629 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3630 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3632 // Update a title for a specific note in the list
3633 @SuppressWarnings("unused")
3634 private void updateListSourceUrl(String guid, String url) {
3635 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3637 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3638 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3639 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3640 if (modelIndex != null) {
3641 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3642 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3643 String tableGuid = (String)ix.values().toArray()[0];
3644 if (tableGuid.equals(guid)) {
3645 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3646 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3647 noteTableView.proxyModel.invalidate();
3652 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3654 @SuppressWarnings("unused")
3655 private void updateListGuid(String oldGuid, String newGuid) {
3656 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3658 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3659 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3660 if (modelIndex != null) {
3661 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3662 String tableGuid = (String)ix.values().toArray()[0];
3663 if (tableGuid.equals(oldGuid)) {
3664 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3665 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3670 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3672 private void updateListTagName(String guid) {
3673 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3675 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3676 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3677 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3679 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3680 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3681 if (modelIndex != null) {
3682 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3683 String noteGuid = (String)ix.values().toArray()[0];
3684 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3685 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3686 i=listManager.getNoteTableModel().rowCount();
3692 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3694 private void removeListTagName(String guid) {
3695 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3697 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3698 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3699 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3700 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3701 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3704 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3705 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3706 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3707 if (modelIndex != null) {
3708 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3709 String noteGuid = (String)ix.values().toArray()[0];
3710 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3711 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3712 i=listManager.getNoteTableModel().rowCount();
3718 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3720 private void updateListNotebookName(String oldName, String newName) {
3721 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3723 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3724 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3725 if (modelIndex != null) {
3726 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3727 String tableName = (String)ix.values().toArray()[0];
3728 if (tableName.equalsIgnoreCase(oldName)) {
3729 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3733 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3735 @SuppressWarnings("unused")
3736 private void updateListDateCreated(String guid, QDateTime date) {
3737 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3739 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3740 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3741 if (modelIndex != null) {
3742 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3743 String tableGuid = (String)ix.values().toArray()[0];
3744 if (tableGuid.equals(guid)) {
3745 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3746 noteTableView.proxyModel.invalidate();
3751 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3753 @SuppressWarnings("unused")
3754 private void updateListDateSubject(String guid, QDateTime date) {
3755 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3757 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3758 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3759 if (modelIndex != null) {
3760 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3761 String tableGuid = (String)ix.values().toArray()[0];
3762 if (tableGuid.equals(guid)) {
3763 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3764 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3765 noteTableView.proxyModel.invalidate();
3770 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3772 private void updateListDateChanged(String guid, QDateTime date) {
3773 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3775 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3776 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3777 if (modelIndex != null) {
3778 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3779 String tableGuid = (String)ix.values().toArray()[0];
3780 if (tableGuid.equals(guid)) {
3781 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3782 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3787 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3789 private void updateListDateChanged() {
3790 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3791 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3792 updateListDateChanged(currentNoteGuid, date);
3793 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3796 private void scrollToCurrentGuid() {
3797 //scrollToGuid(currentNoteGuid);
3798 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3799 if (selections.size() == 0)
3801 QModelIndex index = selections.get(0);
3802 int row = selections.get(0).row();
3803 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3806 // Scroll to a particular index item
3807 private void scrollToGuid(String guid) {
3808 if (currentNote == null || guid == null)
3810 if (currentNote.isActive() && Global.showDeleted) {
3811 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3812 if (!listManager.getNoteIndex().get(i).isActive()) {
3813 currentNote = listManager.getNoteIndex().get(i);
3814 currentNoteGuid = currentNote.getGuid();
3815 i = listManager.getNoteIndex().size();
3820 if (!currentNote.isActive() && !Global.showDeleted) {
3821 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3822 if (listManager.getNoteIndex().get(i).isActive()) {
3823 currentNote = listManager.getNoteIndex().get(i);
3824 currentNoteGuid = currentNote.getGuid();
3825 i = listManager.getNoteIndex().size();
3831 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3832 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3833 if (currentNoteGuid.equals(index.data())) {
3834 // noteTableView.setCurrentIndex(index);
3835 noteTableView.selectRow(i);
3836 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3837 i=listManager.getNoteTableModel().rowCount();
3840 noteTableView.repaint();
3842 // Show/Hide columns
3843 private void showColumns() {
3844 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3845 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3846 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3847 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3848 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3849 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3850 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
3851 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
3852 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
3853 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
3854 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
3856 // Title color has changed
3857 @SuppressWarnings("unused")
3858 private void titleColorChanged(Integer color) {
3859 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3861 QColor backgroundColor = new QColor();
3862 QColor foregroundColor = new QColor(QColor.black);
3863 backgroundColor.setRgb(color);
3865 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
3866 foregroundColor.setRgb(QColor.white.rgb());
3868 if (selectedNoteGUIDs.size() == 0)
3869 selectedNoteGUIDs.add(currentNoteGuid);
3871 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
3872 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3873 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3874 if (modelIndex != null) {
3875 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3876 String tableGuid = (String)ix.values().toArray()[0];
3877 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
3878 for (int k=0; k<Global.noteTableColumnCount; k++) {
3879 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
3880 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
3881 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
3883 i=listManager.getNoteTableModel().rowCount();
3888 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3890 // Wide list was chosen
3891 public void narrowListView() {
3892 saveNoteColumnPositions();
3893 saveNoteIndexWidth();
3895 int sortCol = noteTableView.proxyModel.sortColumn();
3896 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3897 Global.setSortColumn(sortCol);
3898 Global.setSortOrder(sortOrder);
3900 Global.setListView(Global.View_List_Narrow);
3902 menuBar.wideListView.blockSignals(true);
3903 menuBar.narrowListView.blockSignals(true);
3905 menuBar.wideListView.setChecked(false);
3906 menuBar.narrowListView.setChecked(true);
3908 menuBar.wideListView.blockSignals(false);
3909 menuBar.narrowListView.blockSignals(false);
3911 mainLeftRightSplitter.addWidget(noteTableView);
3912 mainLeftRightSplitter.addWidget(browserWindow);
3913 restoreWindowState(false);
3914 noteTableView.repositionColumns();
3915 noteTableView.resizeColumnWidths();
3916 noteTableView.resizeRowHeights();
3918 sortCol = Global.getSortColumn();
3919 sortOrder = Global.getSortOrder();
3920 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3923 noteTableView.load(false);
3924 scrollToCurrentGuid();
3926 public void wideListView() {
3927 int sortCol = noteTableView.proxyModel.sortColumn();
3928 int sortOrder = noteTableView.proxyModel.sortOrder().value();
3929 Global.setSortColumn(sortCol);
3930 Global.setSortOrder(sortOrder);
3933 saveNoteColumnPositions();
3934 saveNoteIndexWidth();
3935 Global.setListView(Global.View_List_Wide);
3937 menuBar.wideListView.blockSignals(true);
3938 menuBar.narrowListView.blockSignals(true);
3940 menuBar.wideListView.setChecked(true);
3941 menuBar.narrowListView.setChecked(false);
3943 menuBar.wideListView.blockSignals(false);
3944 menuBar.narrowListView.blockSignals(false);
3945 browserIndexSplitter.setVisible(true);
3946 browserIndexSplitter.addWidget(noteTableView);
3947 browserIndexSplitter.addWidget(browserWindow);
3948 restoreWindowState(false);
3949 noteTableView.repositionColumns();
3950 noteTableView.resizeColumnWidths();
3951 noteTableView.resizeRowHeights();
3953 sortCol = Global.getSortColumn();
3954 sortOrder = Global.getSortOrder();
3955 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
3958 noteTableView.load(false);
3959 scrollToCurrentGuid();
3963 //***************************************************************
3964 //***************************************************************
3965 //** External editor window functions
3966 //***************************************************************
3967 //***************************************************************
3968 private void listDoubleClick() {
3970 if (externalWindows.containsKey(currentNoteGuid)) {
3971 externalWindows.get(currentNoteGuid).raise();
3974 // We have a new external editor to create
3975 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
3976 ExternalBrowse newBrowser = new ExternalBrowse(conn);
3977 newBrowser.setWindowIcon(appIcon);
3978 externalWindows.put(currentNoteGuid, newBrowser);
3979 showEditorButtons(newBrowser.getBrowserWindow());
3980 loadNoteBrowserInformation(newBrowser.getBrowserWindow());
3981 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
3982 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
3983 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
3984 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
3985 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
3987 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
3988 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
3989 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
3993 @SuppressWarnings("unused")
3994 private void externalWindowTitleEdited(String guid, String text) {
3995 if (guid.equals(currentNoteGuid)) {
3996 browserWindow.setTitle(text);
3999 @SuppressWarnings({ "rawtypes", "unused" })
4000 private void externalWindowTagsEdited(String guid, List values) {
4001 StringBuffer line = new StringBuffer(100);
4002 for (int i=0; i<values.size(); i++) {
4004 line.append(Global.tagDelimeter+" ");
4005 line.append(values.get(i));
4007 if (guid.equals(currentNoteGuid)) {
4008 browserWindow.setTag(line.toString());
4011 @SuppressWarnings("unused")
4012 private void externalWindowClosing(String guid) {
4013 externalWindows.remove(guid);
4018 //***************************************************************
4019 //***************************************************************
4020 //** These functions deal with Note specific things
4021 //***************************************************************
4022 //***************************************************************
4023 @SuppressWarnings("unused")
4024 private void setNoteDirty() {
4025 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4027 // Find if the note is being edited externally. If it is, update it.
4028 if (externalWindows.containsKey(currentNoteGuid)) {
4029 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4030 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4031 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4032 window.getBrowserWindow().getBrowser().setContent(unicode);
4035 // If the note is dirty, then it is unsynchronized by default.
4039 // Set the note as dirty and check if its status is synchronized in the display table
4041 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4042 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4046 // If this wasn't already marked as unsynchronized, then we need to update the table
4047 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4048 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4049 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4050 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4051 if (modelIndex != null) {
4052 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4053 String tableGuid = (String)ix.values().toArray()[0];
4054 if (tableGuid.equals(currentNoteGuid)) {
4055 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4061 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4063 @SuppressWarnings("unused")
4064 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4065 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4066 QByteArray unicode = codec.fromUnicode(content);
4067 noteCache.remove(guid);
4068 noteCache.put(guid, unicode.toString());
4069 if (guid.equals(currentNoteGuid)) {
4071 browserWindow.getBrowser().setContent(unicode);
4074 thumbnailRunner.addWork("GENERATE "+ guid);
4075 saveNote(guid, browser);
4079 private void saveNote() {
4081 saveNote(currentNoteGuid, browserWindow);
4082 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4086 private void saveNote(String guid, BrowserWindow window) {
4087 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4088 logger.log(logger.EXTREME, "Note is dirty.");
4091 logger.log(logger.EXTREME, "Saving to cache");
4092 QTextCodec codec = QTextCodec.codecForLocale();
4093 // QTextDecoder decoder = codec.makeDecoder();
4094 codec = QTextCodec.codecForName("UTF-8");
4095 QByteArray unicode = codec.fromUnicode(window.getContent());
4096 noteCache.put(guid, unicode.toString());
4098 logger.log(logger.EXTREME, "updating list manager");
4099 listManager.updateNoteContent(guid, window.getContent());
4100 logger.log(logger.EXTREME, "Updating title");
4101 listManager.updateNoteTitle(guid, window.getTitle());
4102 updateListDateChanged();
4104 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4105 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4106 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4107 currentNote = listManager.getNoteIndex().get(i);
4108 i = listManager.getNoteIndex().size();
4113 // Get a note from Evernote (and put it in the browser)
4114 private void refreshEvernoteNote(boolean reload) {
4115 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4117 if (Global.disableViewing) {
4118 browserWindow.setEnabled(false);
4123 if (Global.showDeleted)
4125 Global.cryptCounter =0;
4126 if (currentNoteGuid.equals("")) {
4127 browserWindow.setReadOnly(true);
4135 browserWindow.loadingData(true);
4137 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4138 if (currentNote == null)
4141 loadNoteBrowserInformation(browserWindow);
4144 private void loadNoteBrowserInformation(BrowserWindow browser) {
4145 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4146 formatter.setNote(currentNote, Global.pdfPreview());
4147 formatter.setHighlight(listManager.getEnSearch());
4149 if (!noteCache.containsKey(currentNoteGuid) || conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4150 js = new QByteArray();
4151 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4152 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4153 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>");
4154 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4155 js.append("<style> img { max-width:100%; }</style>");
4156 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4157 js.append("</head>");
4158 formatter.setNote(currentNote, Global.pdfPreview());
4159 js.append(formatter.rebuildNoteHTML());
4160 js.append("</HTML>");
4161 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4162 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4163 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4164 browser.getBrowser().setContent(js);
4165 noteCache.put(currentNoteGuid, js.toString());
4167 if (formatter.resourceError)
4168 resourceErrorMessage();
4169 readOnly = formatter.readOnly;
4170 inkNote = formatter.inkNote;
4172 readOnlyCache.put(currentNoteGuid, true);
4174 inkNoteCache.put(currentNoteGuid, true);
4176 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4177 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(currentNoteGuid));
4178 js = new QByteArray(cachedContent);
4179 browser.getBrowser().setContent(js);
4180 if (readOnlyCache.containsKey(currentNoteGuid))
4182 if (inkNoteCache.containsKey(currentNoteGuid))
4185 if (conn.getNoteTable().isThumbnailNeeded(currentNoteGuid)) {
4186 thumbnailHTMLReady(currentNoteGuid, js, Global.calculateThumbnailZoom(js.toString()));
4189 if (readOnly || inkNote)
4190 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4192 browser.getBrowser().page().setContentEditable(true);
4193 browser.setReadOnly(readOnly);
4194 deleteButton.setEnabled(!readOnly);
4195 tagButton.setEnabled(!readOnly);
4196 menuBar.noteDelete.setEnabled(!readOnly);
4197 menuBar.noteTags.setEnabled(!readOnly);
4198 browser.setNote(currentNote);
4200 if (currentNote != null && currentNote.getNotebookGuid() != null &&
4201 conn.getNotebookTable().isLinked(currentNote.getNotebookGuid())) {
4202 deleteButton.setEnabled(false);
4203 menuBar.notebookDeleteAction.setEnabled(false);
4205 deleteButton.setEnabled(true);
4206 menuBar.notebookDeleteAction.setEnabled(true);
4209 // Build a list of non-closed notebooks
4210 List<Notebook> nbooks = new ArrayList<Notebook>();
4211 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4212 boolean found=false;
4213 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4214 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4218 nbooks.add(listManager.getNotebookIndex().get(i));
4221 browser.setTitle(currentNote.getTitle());
4222 browser.setTag(getTagNamesForNote(currentNote));
4223 browser.setAuthor(currentNote.getAttributes().getAuthor());
4225 browser.setAltered(currentNote.getUpdated());
4226 browser.setCreation(currentNote.getCreated());
4227 if (currentNote.getAttributes().getSubjectDate() > 0)
4228 browser.setSubjectDate(currentNote.getAttributes().getSubjectDate());
4230 browser.setSubjectDate(currentNote.getCreated());
4231 browser.setUrl(currentNote.getAttributes().getSourceURL());
4233 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4234 List<Tag> tagList = tagFilter.getValidTags(currentNote);
4235 browser.setAllTags(tagList);
4237 browser.setCurrentTags(currentNote.getTagNames());
4239 scrollToGuid(currentNoteGuid);
4241 browser.loadingData(false);
4242 if (thumbnailViewer.isActiveWindow())
4245 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4246 browser.setNotebookList(notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex()));
4249 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4251 // Save a generated thumbnail
4252 private void toggleNoteInformation() {
4253 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4254 browserWindow.toggleInformation();
4255 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4256 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4257 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4259 // Listener triggered when a print button is pressed
4260 @SuppressWarnings("unused")
4261 private void printNote() {
4262 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4264 QPrintDialog dialog = new QPrintDialog();
4265 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4266 QPrinter printer = dialog.printer();
4267 browserWindow.getBrowser().print(printer);
4269 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4272 // Listener triggered when the email button is pressed
4273 @SuppressWarnings("unused")
4274 private void emailNote() {
4275 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4277 if (Desktop.isDesktopSupported()) {
4278 Desktop desktop = Desktop.getDesktop();
4280 String text2 = browserWindow.getContentsToEmail();
4281 QUrl url = new QUrl("mailto:");
4282 url.addQueryItem("subject", currentNote.getTitle());
4283 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4284 url.addQueryItem("body", text2);
4285 QDesktopServices.openUrl(url);
4289 if (desktop.isSupported(Desktop.Action.MAIL)) {
4290 URI uriMailTo = null;
4292 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4293 String text = browserWindow.getContentsToEmail();
4294 //text = "<b>" +text +"</b>";
4295 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4296 +"&BODY=" +text, null);
4297 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4298 +"&ATTACHMENT=d:/test.pdf", null);
4299 desktop.mail(uriMailTo);
4300 } catch (URISyntaxException e) {
4301 e.printStackTrace();
4302 } catch (IOException e) {
4303 e.printStackTrace();
4310 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4312 // Reindex all notes
4313 @SuppressWarnings("unused")
4314 private void fullReindex() {
4315 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4316 indexRunner.addWork("REINDEXALL");
4317 setMessage(tr("Database will be reindexed."));
4318 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4320 // Listener when a user wants to reindex a specific note
4321 @SuppressWarnings("unused")
4322 private void reindexNote() {
4323 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4324 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4325 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4327 if (selectedNotebookGUIDs.size() > 1)
4328 setMessage(tr("Notes will be reindexed."));
4330 setMessage(tr("Note will be reindexed."));
4331 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4334 @SuppressWarnings("unused")
4335 private void deleteNote() {
4336 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4337 if (currentNote == null)
4339 if (currentNoteGuid.equals(""))
4342 // If we are deleting non-trash notes
4343 if (currentNote.isActive()) {
4344 if (Global.verifyDelete()) {
4345 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete selected note(s)?"),
4346 QMessageBox.StandardButton.Yes,
4347 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4351 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4352 selectedNoteGUIDs.add(currentNoteGuid);
4353 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4354 listManager.deleteNote(selectedNoteGUIDs.get(i));
4357 // If we are deleting from the trash.
4358 if (Global.verifyDelete()) {
4359 if (QMessageBox.question(this, "Confirmation", "Permanently delete selected note(s)?",
4360 QMessageBox.StandardButton.Yes,
4361 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4365 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4366 selectedNoteGUIDs.add(currentNoteGuid);
4367 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4368 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4369 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4370 if (modelIndex != null) {
4371 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4372 String tableGuid = (String)ix.values().toArray()[0];
4373 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4374 listManager.getNoteTableModel().removeRow(j);
4379 listManager.expungeNote(selectedNoteGUIDs.get(i));
4382 currentNoteGuid = "";
4383 listManager.loadNotesIndex();
4384 noteIndexUpdated(false);
4385 refreshEvernoteNote(true);
4386 scrollToGuid(currentNoteGuid);
4387 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4390 @SuppressWarnings("unused")
4391 private void addNote() {
4392 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4393 // browserWindow.setEnabled(true);
4394 browserWindow.setReadOnly(false);
4396 Calendar currentTime = new GregorianCalendar();
4397 StringBuffer noteString = new StringBuffer(100);
4398 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4399 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4402 if (Global.overrideDefaultFont()) {
4403 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4404 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4405 noteString.append("<br clear=\"none\" />\n");
4406 noteString.append("</span>\n</font>\n");
4408 noteString.append("<br clear=\"none\" />\n");
4409 noteString.append("</en-note>");
4411 Long l = new Long(currentTime.getTimeInMillis());
4412 String randint = new String(Long.toString(l));
4414 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4416 // for the first non-archived notebook. Finally, if nothing else we
4417 // pick the first notebook in the list.
4418 String notebook = null;
4419 listManager.getNotebookIndex().get(0).getGuid();
4420 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4421 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4422 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4423 notebook = currentSelectedNotebook.text(2);
4425 boolean found = false;
4426 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4427 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4428 boolean match = false;
4429 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4430 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4432 j = listManager.getArchiveNotebookIndex().size();
4436 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4437 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4439 // Now we have a list of good notebooks, so we can look for the default
4441 for (int i=0; i<goodNotebooks.size(); i++) {
4442 if (goodNotebooks.get(i).isDefaultNotebook()) {
4443 notebook = goodNotebooks.get(i).getGuid();
4445 i = goodNotebooks.size();
4449 if (goodNotebooks.size() > 0 && !found)
4450 notebook = goodNotebooks.get(0).getGuid();
4453 notebook = listManager.getNotebookIndex().get(0).getGuid();
4456 Note newNote = new Note();
4457 newNote.setUpdateSequenceNum(0);
4458 newNote.setGuid(randint);
4459 newNote.setNotebookGuid(notebook);
4460 newNote.setTitle("");
4461 newNote.setContent(noteString.toString());
4462 newNote.setDeleted(0);
4463 newNote.setCreated(System.currentTimeMillis());
4464 newNote.setUpdated(System.currentTimeMillis());
4465 newNote.setActive(true);
4466 NoteAttributes na = new NoteAttributes();
4467 na.setLatitude(0.0);
4468 na.setLongitude(0.0);
4469 na.setAltitude(0.0);
4470 newNote.setAttributes(new NoteAttributes());
4471 newNote.setTagGuids(new ArrayList<String>());
4472 newNote.setTagNames(new ArrayList<String>());
4474 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4475 if (Global.newNoteWithSelectedTags()) {
4476 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4477 QTreeWidgetItem currentSelection;
4478 for (int i=0; i<selections.size(); i++) {
4479 currentSelection = selections.get(i);
4480 newNote.getTagGuids().add(currentSelection.text(2));
4481 newNote.getTagNames().add(currentSelection.text(0));
4485 conn.getNoteTable().addNote(newNote, true);
4486 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4487 listManager.addNote(newNote);
4488 // noteTableView.insertRow(newNote, true, -1);
4490 currentNote = newNote;
4491 currentNoteGuid = currentNote.getGuid();
4492 noteTableView.clearSelection();
4493 refreshEvernoteNote(true);
4494 listManager.countNotebookResults(listManager.getNoteIndex());
4495 browserWindow.titleLabel.setFocus();
4496 browserWindow.titleLabel.selectAll();
4497 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4499 // If the window is hidden, then we want to popup this in an external window &
4502 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4504 // Restore a note from the trash;
4505 @SuppressWarnings("unused")
4506 private void restoreNote() {
4508 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4509 selectedNoteGUIDs.add(currentNoteGuid);
4510 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4511 listManager.restoreNote(selectedNoteGUIDs.get(i));
4513 currentNoteGuid = "";
4514 listManager.loadNotesIndex();
4515 noteIndexUpdated(false);
4518 // Search a note for specific txt
4519 @SuppressWarnings("unused")
4520 private void findText() {
4522 find.setFocusOnTextField();
4524 @SuppressWarnings("unused")
4525 private void doFindText() {
4526 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4529 @SuppressWarnings("unused")
4530 private void updateNoteTitle(String guid, String title) {
4531 listManager.setNoteSynchronized(guid, false);
4533 // Signal received that note content has changed. Normally we just need the guid to remove
4534 // it from the cache.
4535 @SuppressWarnings("unused")
4536 private void invalidateNoteCache(String guid, String content) {
4537 String v = noteCache.remove(guid);
4538 // if (guid.equals(currentNoteGuid) && !noteDirty)
4539 refreshEvernoteNote(true);
4541 // Signal received that a note guid has changed
4542 @SuppressWarnings("unused")
4543 private void noteGuidChanged(String oldGuid, String newGuid) {
4544 if (noteCache.containsKey(oldGuid)) {
4545 if (!oldGuid.equals(currentNoteGuid)) {
4546 String cache = noteCache.get(oldGuid);
4547 noteCache.put(newGuid, cache);
4548 noteCache.remove(oldGuid);
4550 noteCache.remove(oldGuid);
4551 noteCache.put(newGuid, browserWindow.getContent());
4555 listManager.updateNoteGuid(oldGuid, newGuid, false);
4556 if (currentNoteGuid.equals(oldGuid)) {
4557 if (currentNote != null)
4558 currentNote.setGuid(newGuid);
4559 currentNoteGuid = newGuid;
4562 if (externalWindows.containsKey(oldGuid)) {
4563 ExternalBrowse b = externalWindows.get(oldGuid);
4564 externalWindows.remove(oldGuid);
4565 b.getBrowserWindow().getNote().setGuid(newGuid);
4566 externalWindows.put(newGuid, b);
4569 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4570 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4571 noteTableView.proxyModel.addGuid(newGuid);
4572 i=listManager.getNoteIndex().size();
4576 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4577 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4578 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4579 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4583 // Toggle the note editor button bar
4584 private void toggleEditorButtonBar() {
4585 if (browserWindow.buttonsVisible) {
4586 browserWindow.hideButtons();
4587 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4588 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4590 browserWindow.buttonsVisible = true;
4591 showEditorButtons(browserWindow);
4593 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4595 // Show editor buttons
4596 private void showEditorButtons(BrowserWindow browser) {
4597 browser.buttonLayout.setVisible(true);
4598 browser.undoAction.setVisible(false);
4600 browser.undoButton.setVisible(false);
4602 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4603 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4604 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4605 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4606 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4607 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4608 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4609 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4610 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4611 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4612 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4613 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4614 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4615 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4616 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4617 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4618 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4619 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4620 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4621 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4622 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4623 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4624 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4626 private void duplicateNote(String guid) {
4628 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4629 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4630 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4631 oldNote.setResources(resList);
4632 duplicateNote(oldNote);
4634 private void duplicateNote(Note oldNote) {
4636 // Now that we have a good notebook guid, we need to move the conflicting note
4637 // to the local notebook
4638 Calendar currentTime = new GregorianCalendar();
4639 Long l = new Long(currentTime.getTimeInMillis());
4640 String newGuid = new String(Long.toString(l));
4642 // Note newNote = oldNote.deepCopy();
4643 Note newNote = (Note)Global.deepCopy(oldNote);
4644 newNote.setUpdateSequenceNum(0);
4645 newNote.setGuid(newGuid);
4646 newNote.setDeleted(0);
4647 newNote.setActive(true);
4650 List<String> tagNames = new ArrayList<String>();
4651 List<String> tagGuids = new ArrayList<String>();;
4652 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4653 tagNames.add(oldNote.getTagNames().get(i));
4654 tagGuids.add(oldNote.getTagGuids().get(i));
4657 // Sort note Tags to make them look nice
4658 for (int i=0; i<tagNames.size()-1; i++) {
4659 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4660 String n1 = tagNames.get(i);
4661 String n2 = tagNames.get(i+1);
4662 tagNames.set(i, n2);
4663 tagNames.set(i+1, n1);
4666 newNote.setTagGuids(tagGuids);
4667 newNote.setTagNames(tagNames);
4669 // Add tag guids to note
4672 // Duplicate resources
4673 List<Resource> resList = oldNote.getResources();
4674 if (resList == null)
4675 resList = new ArrayList<Resource>();
4677 for (int i=0; i<resList.size(); i++) {
4679 while (l == prevGuid) {
4680 currentTime = new GregorianCalendar();
4681 l = new Long(currentTime.getTimeInMillis());
4684 String newResGuid = new String(Long.toString(l));
4685 resList.get(i).setNoteGuid(newGuid);
4686 resList.get(i).setGuid(newResGuid);
4687 resList.get(i).setUpdateSequenceNum(0);
4688 resList.get(i).setActive(true);
4689 conn.getNoteTable().noteResourceTable.saveNoteResource(
4690 (Resource)Global.deepCopy(resList.get(i)), true);
4692 newNote.setResources(resList);
4694 // Add note to the database
4695 listManager.addNote(newNote);
4696 conn.getNoteTable().addNote(newNote, true);
4697 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4698 noteTableView.insertRow(newNote, true, -1);
4699 currentNoteGuid = newNote.getGuid();
4700 currentNote = newNote;
4701 refreshEvernoteNote(true);
4702 listManager.countNotebookResults(listManager.getNoteIndex());
4706 @SuppressWarnings("unused")
4707 private void allNotes() {
4708 clearAttributeFilter();
4709 clearNotebookFilter();
4710 clearSavedSearchFilter();
4713 searchField.clear();
4714 if (Global.mimicEvernoteInterface) {
4715 notebookTree.selectGuid("");
4717 notebookTreeSelection();
4720 @SuppressWarnings("unused")
4721 private void mergeNotes() {
4722 logger.log(logger.HIGH, "Merging notes");
4725 String masterGuid = null;
4726 List<String> sources = new ArrayList<String>();
4728 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4729 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4730 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4731 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4733 masterGuid = (String)ix.values().toArray()[0];
4735 sources.add((String)ix.values().toArray()[0]);
4738 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4739 logger.log(logger.EXTREME, "Children count: "+sources.size());
4740 mergeNoteContents(masterGuid, sources);
4741 currentNoteGuid = masterGuid;
4742 noteIndexUpdated(false);
4743 refreshEvernoteNote(true);
4746 private void mergeNoteContents(String targetGuid, List<String> sources) {
4747 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4748 String newContent = target.getContent();
4749 newContent = newContent.replace("</en-note>", "<br></br>");
4751 for (int i=0; i<sources.size(); i++) {
4752 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4753 if (source.isSetTitle()) {
4754 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4756 String sourceContent = source.getContent();
4757 logger.log(logger.EXTREME, "Merging contents into note");
4758 logger.log(logger.EXTREME, sourceContent);
4759 logger.log(logger.EXTREME, "End of content");
4760 int startOfNote = sourceContent.indexOf("<en-note>");
4761 sourceContent = sourceContent.substring(startOfNote+9);
4762 int endOfNote = sourceContent.indexOf("</en-note>");
4763 sourceContent = sourceContent.substring(0,endOfNote);
4764 newContent = newContent + sourceContent;
4765 logger.log(logger.EXTREME, "New note content");
4766 logger.log(logger.EXTREME, newContent);
4767 logger.log(logger.EXTREME, "End of content");
4768 for (int j=0; j<source.getResourcesSize(); j++) {
4769 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4770 Resource r = source.getResources().get(j);
4771 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4773 Calendar currentTime = new GregorianCalendar();
4774 Long l = new Long(currentTime.getTimeInMillis());
4778 while (l == prevGuid) {
4779 currentTime = new GregorianCalendar();
4780 l = new Long(currentTime.getTimeInMillis());
4782 String newResGuid = new String(Long.toString(l));
4783 newRes.setNoteGuid(targetGuid);
4784 newRes.setGuid(newResGuid);
4785 newRes.setUpdateSequenceNum(0);
4786 newRes.setActive(true);
4787 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
4790 logger.log(logger.EXTREME, "Updating note");
4791 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
4792 for (int i=0; i<sources.size(); i++) {
4793 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
4794 listManager.deleteNote(sources.get(i));
4796 logger.log(logger.EXTREME, "Exiting merge note");
4798 // A resource within a note has had a guid change
4799 @SuppressWarnings("unused")
4800 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
4801 if (!oldGuid.equals(newGuid))
4802 Global.resourceMap.put(oldGuid, newGuid);
4804 // View a thumbnail of the note
4805 public void thumbnailView() {
4807 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
4808 QFile thumbnail = new QFile(thumbnailName);
4809 if (!thumbnail.exists()) {
4811 QImage img = new QImage();
4812 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
4813 thumbnailViewer.setThumbnail(img);
4815 thumbnailViewer.setThumbnail(thumbnailName);
4816 if (!thumbnailViewer.isVisible())
4817 thumbnailViewer.showFullScreen();
4819 // An error happened while saving a note. Inform the user
4820 @SuppressWarnings("unused")
4821 private void saveRunnerError(String guid, String msg) {
4823 String title = "*Unknown*";
4824 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
4825 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
4826 title = listManager.getMasterNoteIndex().get(i).getTitle();
4827 i=listManager.getMasterNoteIndex().size();
4830 msg = "An error has happened while saving the note \"" +title+
4831 "\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
4832 "As a result, changes to the note may not be saved properly in the database."+
4833 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
4834 "\nbe lost. Please review the note to recover any critical data before restarting.";
4836 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
4839 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
4840 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
4841 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
4842 // Find an idle preview object
4843 for (int i=0; i<thumbGenerators.size(); i++) {
4844 if (thumbGenerators.get(i).mutex.tryLock()) {
4845 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
4846 thumbGenerators.get(i).loadContent(guid, html, zoom);
4850 if (thumbGenerators.size() >= 1) {
4851 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
4855 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
4856 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
4857 thumbGenerators.add(preview);
4859 if (preview.mutex.tryLock()) {
4860 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
4861 preview.loadContent(guid, html, zoom);
4863 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
4868 //**********************************************************
4869 //**********************************************************
4870 //* Online user actions
4871 //**********************************************************
4872 //**********************************************************
4873 private void setupOnlineMenu() {
4874 if (!Global.isConnected) {
4875 menuBar.noteOnlineHistoryAction.setEnabled(false);
4876 menuBar.selectiveSyncAction.setEnabled(false);
4879 menuBar.noteOnlineHistoryAction.setEnabled(true);
4880 menuBar.selectiveSyncAction.setEnabled(true);
4883 @SuppressWarnings("unused")
4884 private void viewNoteHistory() {
4885 if (currentNoteGuid == null || currentNoteGuid.equals(""))
4887 if (currentNote.getUpdateSequenceNum() == 0) {
4888 setMessage(tr("Note has never been synchronized."));
4889 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
4893 setMessage(tr("Getting Note History"));
4895 Note currentOnlineNote = null;
4898 if (Global.isPremium())
4899 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
4901 versions = new ArrayList<NoteVersionId>();
4902 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
4903 } catch (EDAMUserException e) {
4904 setMessage("EDAMUserException: " +e.getMessage());
4906 } catch (EDAMSystemException e) {
4907 setMessage("EDAMSystemException: " +e.getMessage());
4909 } catch (EDAMNotFoundException e) {
4910 setMessage(tr("Note not found on server."));
4911 QMessageBox.information(this, "Error", "This note could not be found on Evernote's servers.");
4913 } catch (TException e) {
4914 setMessage("EDAMTransactionException: " +e.getMessage());
4918 // If we've gotten this far, we have a good note.
4919 if (historyWindow == null) {
4920 historyWindow = new OnlineNoteHistory(logger, conn);
4921 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
4922 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
4923 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
4925 historyWindow.historyCombo.clear();
4927 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
4928 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
4930 historyWindow.setCurrent(isDirty);
4932 loadHistoryWindowContent(currentOnlineNote);
4933 historyWindow.load(versions);
4934 setMessage(tr("History retrieved"));
4936 historyWindow.exec();
4938 private Note reloadHistoryWindow(String selection) {
4940 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
4941 String dateTimeFormat = new String(fmt);
4942 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
4946 for (int i=0; i<versions.size(); i++) {
4947 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
4948 if (versionDate.toString().equals(selection))
4952 if (index > -1 || selection.indexOf("Current") > -1) {
4953 Note historyNote = null;
4956 usn = versions.get(index).getUpdateSequenceNum();
4957 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
4959 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
4960 } catch (EDAMUserException e) {
4961 setMessage("EDAMUserException: " +e.getMessage());
4964 } catch (EDAMSystemException e) {
4965 setMessage("EDAMSystemException: " +e.getMessage());
4968 } catch (EDAMNotFoundException e) {
4969 setMessage("EDAMNotFoundException: " +e.getMessage());
4972 } catch (TException e) {
4973 setMessage("EDAMTransactionException: " +e.getMessage());
4979 if (historyNote != null)
4980 historyWindow.setContent(historyNote);
4986 private void loadHistoryWindowContent(Note note) {
4987 note.setUpdateSequenceNum(0);
4988 historyWindow.setContent(note);
4990 @SuppressWarnings("unused")
4991 private void restoreHistoryNoteAsNew() {
4992 setMessage(tr("Restoring as new note."));
4993 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
4994 setMessage(tr("Note has been restored as a new note."));
4996 @SuppressWarnings("unused")
4997 private void restoreHistoryNote() {
4998 setMessage(tr("Restoring note."));
4999 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5000 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5003 for (int i=0; i<n.getResourcesSize(); i++) {
5004 n.getResources().get(i).setActive(true);
5005 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5007 listManager.addNote(n);
5008 conn.getNoteTable().addNote(n, true);
5009 refreshEvernoteNote(true);
5010 setMessage(tr("Note has been restored."));
5012 @SuppressWarnings("unused")
5013 private void setupSelectiveSync() {
5015 // Get a list of valid notebooks
5016 List<Notebook> notebooks = null;
5017 List<Tag> tags = null;
5018 List<LinkedNotebook> linkedNotebooks = null;
5020 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5021 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5022 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5023 } catch (EDAMUserException e) {
5024 setMessage("EDAMUserException: " +e.getMessage());
5026 } catch (EDAMSystemException e) {
5027 setMessage("EDAMSystemException: " +e.getMessage());
5029 } catch (TException e) {
5030 setMessage("EDAMTransactionException: " +e.getMessage());
5032 } catch (EDAMNotFoundException e) {
5033 setMessage("EDAMNotFoundException: " +e.getMessage());
5037 // Split up notebooks into synchronized & non-synchronized
5038 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5039 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5041 for (int i=notebooks.size()-1; i>=0; i--) {
5042 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5043 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5044 ignoredBooks.add(notebooks.get(i));
5045 j=dbIgnoredNotebooks.size();
5050 // split up tags into synchronized & non-synchronized
5051 List<Tag> ignoredTags = new ArrayList<Tag>();
5052 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5054 for (int i=tags.size()-1; i>=0; i--) {
5055 for (int j=0; j<dbIgnoredTags.size(); j++) {
5056 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5057 ignoredTags.add(tags.get(i));
5058 j=dbIgnoredTags.size();
5063 // split up linked notebooks into synchronized & non-synchronized
5064 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5065 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5066 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5067 String notebookGuid = linkedNotebooks.get(i).getGuid();
5068 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5069 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5070 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5071 j=dbIgnoredLinkedNotebooks.size();
5076 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5078 if (!ignore.okClicked())
5083 // Clear out old notebooks & add the new ones
5084 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5085 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5086 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5089 List<String> newNotebooks = new ArrayList<String>();
5090 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5091 String text = ignore.getIgnoredBookList().takeItem(i).text();
5092 for (int j=0; j<notebooks.size(); j++) {
5093 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5094 Notebook n = notebooks.get(j);
5095 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5097 newNotebooks.add(n.getGuid());
5102 // Clear out old tags & add new ones
5103 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5104 for (int i=0; i<oldIgnoreTags.size(); i++) {
5105 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5108 List<String> newTags = new ArrayList<String>();
5109 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5110 String text = ignore.getIgnoredTagList().takeItem(i).text();
5111 for (int j=0; j<tags.size(); j++) {
5112 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5113 Tag t = tags.get(j);
5114 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5115 newTags.add(t.getGuid());
5121 // Clear out old tags & add new ones
5122 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5123 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5124 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5127 List<String> newLinked = new ArrayList<String>();
5128 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5129 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5130 for (int j=0; j<linkedNotebooks.size(); j++) {
5131 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5132 LinkedNotebook t = linkedNotebooks.get(j);
5133 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5134 newLinked.add(t.getGuid());
5135 j=linkedNotebooks.size();
5140 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5146 //**********************************************************
5147 //**********************************************************
5148 //* XML Modifying methods
5149 //**********************************************************
5150 //**********************************************************
5151 // An error has happended fetching a resource. let the user know
5152 private void resourceErrorMessage() {
5155 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5156 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5157 "In a perfect world this wouldn't happen, but it has.\n" +
5158 "It is embarasing when a program like me, designed to save all your\n"+
5159 "precious data, has a problem finding data.\n\n" +
5160 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5161 "In the mean time, I'm not going to let you make changes to this note.\n" +
5162 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5163 "this note on the Evernote servers. Sorry."+
5164 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5166 browserWindow.setReadOnly(true);
5172 //**********************************************************
5173 //**********************************************************
5175 //**********************************************************
5176 //**********************************************************
5177 // We should now do a sync with Evernote
5178 private void syncTimer() {
5179 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5180 syncRunner.syncNeeded = true;
5181 syncRunner.disableUploads = Global.disableUploads;
5183 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5185 private void syncStart() {
5186 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5188 if (!syncRunning && Global.isConnected) {
5189 syncRunner.setConnected(true);
5190 syncRunner.setKeepRunning(Global.keepRunning);
5191 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5193 if (syncThreadsReady > 0) {
5194 thumbnailRunner.interrupt = true;
5195 saveNoteIndexWidth();
5196 saveNoteColumnPositions();
5197 if (syncRunner.addWork("SYNC")) {
5199 syncRunner.syncNeeded = true;
5204 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5206 @SuppressWarnings("unused")
5207 private void syncThreadComplete(Boolean refreshNeeded) {
5208 setMessage(tr("Finalizing Synchronization"));
5210 syncRunning = false;
5211 syncRunner.syncNeeded = false;
5212 synchronizeAnimationTimer.stop();
5213 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5215 if (currentNote == null) {
5216 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5218 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5219 noteIndexUpdated(false);
5220 noteTableView.selectionModel().blockSignals(true);
5221 scrollToGuid(currentNoteGuid);
5222 noteTableView.selectionModel().blockSignals(false);
5223 refreshEvernoteNote(false);
5224 scrollToGuid(currentNoteGuid);
5226 if (!syncRunner.error)
5227 setMessage(tr("Synchronization Complete"));
5229 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5230 logger.log(logger.MEDIUM, "Sync complete.");
5232 public void saveUploadAmount(long t) {
5233 Global.saveUploadAmount(t);
5235 public void saveUserInformation(User user) {
5236 Global.saveUserInformation(user);
5238 public void saveEvernoteUpdateCount(int i) {
5239 Global.saveEvernoteUpdateCount(i);
5241 public void refreshLists() {
5242 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5244 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5245 tagIndexUpdated(true);
5246 notebookIndexUpdated();
5247 savedSearchIndexUpdated();
5248 listManager.loadNotesIndex();
5250 noteTableView.selectionModel().blockSignals(true);
5251 noteIndexUpdated(true);
5252 noteTableView.selectionModel().blockSignals(false);
5253 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5257 @SuppressWarnings("unused")
5258 private void authTimer() {
5259 Calendar cal = Calendar.getInstance();
5261 // If we are not connected let's get out of here
5262 if (!Global.isConnected)
5265 // If this is the first time through, then we need to set this
5266 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5267 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5269 // long now = new Date().getTime();
5270 // if (now > Global.authRefreshTime && Global.isConnected) {
5271 syncRunner.authRefreshNeeded = true;
5275 @SuppressWarnings("unused")
5276 private void authRefreshComplete(boolean goodSync) {
5277 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5278 Global.isConnected = syncRunner.isConnected;
5280 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5281 authTimer.start(1000*60*15);
5282 logger.log(logger.LOW, "Authentication token has been renewed");
5283 // setMessage("Authentication token has been renewed.");
5285 authTimer.start(1000*60*5);
5286 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5287 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5289 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5293 @SuppressWarnings("unused")
5294 private synchronized void indexTimer() {
5295 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5298 if (!indexDisabled && indexRunner.idle) {
5299 thumbnailRunner.interrupt = true;
5300 indexRunner.addWork("SCAN");
5302 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5305 @SuppressWarnings("unused")
5306 private void indexStarted() {
5307 setMessage(tr("Indexing notes"));
5309 @SuppressWarnings("unused")
5310 private void indexComplete() {
5311 setMessage(tr("Index complete"));
5313 @SuppressWarnings("unused")
5314 private synchronized void toggleNoteIndexing() {
5315 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5316 indexDisabled = !indexDisabled;
5318 setMessage(tr("Indexing is now enabled."));
5320 setMessage(tr("Indexing is now disabled."));
5321 menuBar.disableIndexing.setChecked(indexDisabled);
5322 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5325 @SuppressWarnings("unused")
5326 private void threadMonitorCheck() {
5331 alive = listManager.threadCheck(Global.tagCounterThreadId);
5334 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5335 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the tag counter thread has died. I recommend "+
5336 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5337 disableTagThreadCheck = true;
5342 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5344 notebookThreadDeadCount++;
5345 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5346 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the notebook counter thread has died. I recommend "+
5347 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5348 disableNotebookThreadCheck=true;
5351 notebookThreadDeadCount=0;
5353 alive = listManager.threadCheck(Global.trashCounterThreadId);
5356 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5357 QMessageBox.information(this, tr("A thread his died."), ("It appears as the trash counter thread has died. I recommend "+
5358 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5359 disableTrashThreadCheck = true;
5364 alive = listManager.threadCheck(Global.saveThreadId);
5366 saveThreadDeadCount++;
5367 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5368 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the note saver thread has died. I recommend "+
5369 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5370 disableSaveThreadCheck = true;
5373 saveThreadDeadCount=0;
5375 if (!syncThread.isAlive()) {
5376 syncThreadDeadCount++;
5377 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5378 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the synchronization thread has died. I recommend "+
5379 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5380 disableSyncThreadCheck = true;
5383 syncThreadDeadCount=0;
5385 if (!indexThread.isAlive()) {
5386 indexThreadDeadCount++;
5387 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5388 QMessageBox.information(this, tr("A thread his died."), tr("It appears as the index thread has died. I recommend "+
5389 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5390 disableIndexThreadCheck = true;
5393 indexThreadDeadCount=0;
5398 private void thumbnailTimer() {
5399 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5400 thumbnailRunner.addWork("SCAN");
5404 //**************************************************
5405 //* Backup & Restore
5406 //**************************************************
5407 @SuppressWarnings("unused")
5408 private void databaseBackup() {
5409 QFileDialog fd = new QFileDialog(this);
5410 fd.setFileMode(FileMode.AnyFile);
5411 fd.setConfirmOverwrite(true);
5412 fd.setWindowTitle(tr("Backup Database"));
5413 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5414 fd.setAcceptMode(AcceptMode.AcceptSave);
5415 if (saveLastPath == null || saveLastPath.equals(""))
5416 fd.setDirectory(System.getProperty("user.home"));
5418 fd.setDirectory(saveLastPath);
5419 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5425 saveLastPath = fd.selectedFiles().get(0);
5426 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5427 setMessage(tr("Backing up database"));
5429 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5431 ExportData noteWriter = new ExportData(conn, true);
5432 String fileName = fd.selectedFiles().get(0);
5434 if (!fileName.endsWith(".nnex"))
5435 fileName = fileName +".nnex";
5436 noteWriter.exportData(fileName);
5437 setMessage(tr("Database backup completed."));
5442 @SuppressWarnings("unused")
5443 private void databaseRestore() {
5444 if (QMessageBox.question(this, tr("Confirmation"),
5445 tr("This is used to restore a database from backups.\n" +
5446 "It is HIGHLY recommened that this only be used to populate\n" +
5447 "an empty database. Restoring into a database that\n already has data" +
5448 " can cause problems.\n\nAre you sure you want to continue?"),
5449 QMessageBox.StandardButton.Yes,
5450 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5455 QFileDialog fd = new QFileDialog(this);
5456 fd.setFileMode(FileMode.ExistingFile);
5457 fd.setConfirmOverwrite(true);
5458 fd.setWindowTitle(tr("Restore Database"));
5459 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5460 fd.setAcceptMode(AcceptMode.AcceptOpen);
5461 if (saveLastPath == null || saveLastPath.equals(""))
5462 fd.setDirectory(System.getProperty("user.home"));
5464 fd.setDirectory(saveLastPath);
5465 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5471 saveLastPath = fd.selectedFiles().get(0);
5472 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5474 setMessage(tr("Restoring database"));
5475 ImportData noteReader = new ImportData(conn, true);
5476 noteReader.importData(fd.selectedFiles().get(0));
5478 if (noteReader.lastError != 0) {
5479 setMessage(noteReader.getErrorMessage());
5480 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5485 listManager.loadNoteTitleColors();
5487 refreshEvernoteNote(true);
5488 setMessage(tr("Database has been restored."));
5491 @SuppressWarnings("unused")
5492 private void exportNotes() {
5493 QFileDialog fd = new QFileDialog(this);
5494 fd.setFileMode(FileMode.AnyFile);
5495 fd.setConfirmOverwrite(true);
5496 fd.setWindowTitle(tr("Backup Database"));
5497 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5498 fd.setAcceptMode(AcceptMode.AcceptSave);
5499 fd.setDirectory(System.getProperty("user.home"));
5500 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5506 setMessage(tr("Exporting Notes"));
5509 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5510 selectedNoteGUIDs.add(currentNoteGuid);
5512 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5513 String fileName = fd.selectedFiles().get(0);
5515 if (!fileName.endsWith(".nnex"))
5516 fileName = fileName +".nnex";
5517 noteWriter.exportData(fileName);
5518 setMessage(tr("Export completed."));
5524 @SuppressWarnings("unused")
5525 private void importNotes() {
5526 QFileDialog fd = new QFileDialog(this);
5527 fd.setFileMode(FileMode.ExistingFile);
5528 fd.setConfirmOverwrite(true);
5529 fd.setWindowTitle(tr("Import Notes"));
5530 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5531 fd.setAcceptMode(AcceptMode.AcceptOpen);
5532 if (saveLastPath == null || saveLastPath.equals(""))
5533 fd.setDirectory(System.getProperty("user.home"));
5535 fd.setDirectory(saveLastPath);
5536 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5542 setMessage("Importing Notes");
5545 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5546 selectedNoteGUIDs.add(currentNoteGuid);
5548 ImportData noteReader = new ImportData(conn, false);
5549 String fileName = fd.selectedFiles().get(0);
5550 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5552 if (!fileName.endsWith(".nnex"))
5553 fileName = fileName +".nnex";
5554 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5555 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5557 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5559 noteReader.importData(fileName);
5561 if (noteReader.lastError != 0) {
5562 setMessage(noteReader.getErrorMessage());
5563 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5568 listManager.loadNoteTitleColors();
5570 refreshEvernoteNote(false);
5571 setMessage(tr("Notes have been imported."));
5574 setMessage("Import completed.");
5581 //**************************************************
5582 //* Duplicate a note
5583 //**************************************************
5584 @SuppressWarnings("unused")
5585 private void duplicateNote() {
5587 duplicateNote(currentNoteGuid);
5592 //**************************************************
5594 //**************************************************
5595 public void setupFolderImports() {
5596 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5598 if (importKeepWatcher == null)
5599 importKeepWatcher = new QFileSystemWatcher();
5600 if (importDeleteWatcher == null) {
5601 importDeleteWatcher = new QFileSystemWatcher();
5602 for (int i=0; i<records.size(); i++) {
5603 if (!records.get(i).keep)
5604 folderImportDelete(records.get(i).folder);
5610 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5611 for (int i=0; i<records.size(); i++) {
5612 if (records.get(i).keep)
5613 importKeepWatcher.addPath(records.get(i).folder);
5615 importDeleteWatcher.addPath(records.get(i).folder);
5618 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5619 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5621 // Look at the files already there so we don't import them again if a new file is created
5622 if (importedFiles == null) {
5623 importedFiles = new ArrayList<String>();
5624 for (int j=0; j<records.size(); j++) {
5625 QDir dir = new QDir(records.get(j).folder);
5626 List<QFileInfo> list = dir.entryInfoList();
5627 for (int k=0; k<list.size(); k++) {
5628 if (list.get(k).isFile())
5629 importedFiles.add(list.get(k).absoluteFilePath());
5634 public void folderImport() {
5635 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5636 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5638 if (!dialog.okClicked())
5641 // We have some sort of update.
5642 if (importKeepWatcher.directories().size() > 0)
5643 importKeepWatcher.removePaths(importKeepWatcher.directories());
5644 if (importDeleteWatcher.directories().size() > 0)
5645 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5647 conn.getWatchFolderTable().expungeAll();
5648 // Start building from the table
5649 for (int i=0; i<dialog.table.rowCount(); i++) {
5650 QTableWidgetItem item = dialog.table.item(i, 0);
5651 String dir = item.text();
5652 item = dialog.table.item(i, 1);
5653 String notebook = item.text();
5654 item = dialog.table.item(i, 2);
5656 if (item.text().equalsIgnoreCase("Keep"))
5661 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5662 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5664 setupFolderImports();
5667 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5669 String whichOS = System.getProperty("os.name");
5670 if (whichOS.contains("Windows"))
5671 dirName = dirName.replace('/','\\');
5673 FileImporter importer = new FileImporter(logger, conn);
5675 QDir dir = new QDir(dirName);
5676 List<QFileInfo> list = dir.entryInfoList();
5677 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5679 for (int i=0; i<list.size(); i++){
5681 boolean redundant = false;
5682 // Check if we've already imported this one or if it existed before
5683 for (int j=0; j<importedFiles.size(); j++) {
5684 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
5689 importer.setFileInfo(list.get(i));
5690 importer.setFileName(list.get(i).absoluteFilePath());
5693 if (list.get(i).isFile() && importer.isValidType()) {
5695 if (!importer.importFile()) {
5696 // If we can't get to the file, it is probably locked. We'll try again later.
5697 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5698 importFilesKeep.add(list.get(i).absoluteFilePath());
5702 Note newNote = importer.getNote();
5703 newNote.setNotebookGuid(notebook);
5704 newNote.setTitle(dir.at(i));
5705 listManager.addNote(newNote);
5706 conn.getNoteTable().addNote(newNote, true);
5707 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5708 noteTableView.insertRow(newNote, true, -1);
5709 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5710 listManager.countNotebookResults(listManager.getNoteIndex());
5711 importedFiles.add(list.get(i).absoluteFilePath());
5719 public void folderImportDelete(String dirName) {
5721 String whichOS = System.getProperty("os.name");
5722 if (whichOS.contains("Windows"))
5723 dirName = dirName.replace('/','\\');
5725 FileImporter importer = new FileImporter(logger, conn);
5726 QDir dir = new QDir(dirName);
5727 List<QFileInfo> list = dir.entryInfoList();
5728 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
5730 for (int i=0; i<list.size(); i++){
5731 importer.setFileInfo(list.get(i));
5732 importer.setFileName(list.get(i).absoluteFilePath());
5734 if (list.get(i).isFile() && importer.isValidType()) {
5736 if (!importer.importFile()) {
5737 // If we can't get to the file, it is probably locked. We'll try again later.
5738 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5739 importFilesKeep.add(list.get(i).absoluteFilePath());
5743 Note newNote = importer.getNote();
5744 newNote.setNotebookGuid(notebook);
5745 newNote.setTitle(dir.at(i));
5746 listManager.addNote(newNote);
5747 conn.getNoteTable().addNote(newNote, true);
5748 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
5749 noteTableView.insertRow(newNote, true, -1);
5750 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
5751 listManager.countNotebookResults(listManager.getNoteIndex());
5752 dir.remove(dir.at(i));
5758 //**************************************************
5760 //**************************************************
5761 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
5762 logger.log(logger.HIGH, "Entering exernalFileEdited");
5764 // Strip URL prefix and base dir path
5765 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
5766 String name = fileName.replace(dPath, "");
5767 int pos = name.lastIndexOf('.');
5770 guid = guid.substring(0,pos);
5772 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
5774 guid = name.substring(0, pos);
5777 QFile file = new QFile(fileName);
5778 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
5779 // If we can't get to the file, it is probably locked. We'll try again later.
5780 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5781 externalFiles.add(fileName);
5784 QByteArray binData = file.readAll();
5786 if (binData.size() == 0) {
5787 // If we can't get to the file, it is probably locked. We'll try again later.
5788 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
5789 externalFiles.add(fileName);
5793 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
5795 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
5796 if (r == null || r.getData() == null || r.getData().getBody() == null)
5798 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
5799 MessageDigest md = MessageDigest.getInstance("MD5");
5800 md.update(binData.toByteArray());
5801 byte[] hash = md.digest();
5802 String newHash = Global.byteArrayToHexString(hash);
5803 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
5804 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
5806 if (externalWindows.containsKey(r.getNoteGuid())) {
5807 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
5808 r.getGuid(), oldHash, newHash);
5810 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
5811 Data data = r.getData();
5812 data.setBody(binData.toByteArray());
5813 data.setBodyHash(hash);
5814 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
5816 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
5818 if (r.getNoteGuid().equals(currentNoteGuid)) {
5819 QWebSettings.setMaximumPagesInCache(0);
5820 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5821 refreshEvernoteNote(true);
5822 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
5825 if (externalWindows.containsKey(r.getNoteGuid())) {
5826 QWebSettings.setMaximumPagesInCache(0);
5827 QWebSettings.setObjectCacheCapacities(0, 0, 0);
5828 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
5832 logger.log(logger.HIGH, "Exiting externalFielEdited");
5834 // This is a timer event that tries to save any external files that were edited. This
5835 // is only needed if we couldn't save a file earlier.
5836 public void externalFileEditedSaver() {
5837 for (int i=externalFiles.size()-1; i>=0; i--) {
5839 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
5840 externalFileEdited(externalFiles.get(i));
5841 externalFiles.remove(i);
5842 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5844 for (int i=0; i<importFilesKeep.size(); i++) {
5846 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
5847 folderImportKeep(importFilesKeep.get(i));
5848 importFilesKeep.remove(i);
5849 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
5851 for (int i=0; i<importFilesDelete.size(); i++) {
5852 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
5853 folderImportDelete(importFilesDelete.get(i));
5854 importFilesDelete.remove(i);
5861 // If an attachment on the current note was edited, we need to update the current notes's hash
5862 // Update a note content's hash. This happens if a resource is edited outside of NN
5863 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
5864 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
5866 for (;position>-1;) {
5867 endPos = browser.getContent().indexOf(">", position+1);
5868 String oldSegment = browser.getContent().substring(position,endPos);
5869 int hashPos = oldSegment.indexOf("hash=\"");
5870 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
5871 String hash = oldSegment.substring(hashPos+6, hashEnd);
5872 if (hash.equalsIgnoreCase(oldHash)) {
5873 String newSegment = oldSegment.replace(oldHash, newHash);
5874 String content = browser.getContent().substring(0,position) +
5876 browser.getContent().substring(endPos);
5877 browser.getBrowser().setContent(new QByteArray(content));;
5880 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
5885 //*************************************************
5886 //* Minimize to tray
5887 //*************************************************
5889 public void changeEvent(QEvent e) {
5890 if (e.type() == QEvent.Type.WindowStateChange) {
5891 if (isMinimized() && Global.showTrayIcon()) {
5893 QTimer.singleShot(10, this, "hide()");
5897 windowMaximized = true;
5899 windowMaximized = false;
5903 //*************************************************
5904 //* Check database userid & passwords
5905 //*************************************************
5906 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
5907 Connection connection;
5910 Class.forName("org.h2.Driver");
5911 } catch (ClassNotFoundException e1) {
5912 e1.printStackTrace();
5917 String passwordString = null;
5918 if (cypherPassword==null || cypherPassword.trim().equals(""))
5919 passwordString = userPassword;
5921 passwordString = cypherPassword+" "+userPassword;
5922 connection = DriverManager.getConnection(url,userid,passwordString);
5923 } catch (SQLException e) {
5928 } catch (SQLException e) {
5929 e.printStackTrace();