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.QMimeData;
79 import com.trolltech.qt.core.QModelIndex;
80 import com.trolltech.qt.core.QSize;
81 import com.trolltech.qt.core.QTemporaryFile;
82 import com.trolltech.qt.core.QTextCodec;
83 import com.trolltech.qt.core.QThreadPool;
84 import com.trolltech.qt.core.QTimer;
85 import com.trolltech.qt.core.QTranslator;
86 import com.trolltech.qt.core.QUrl;
87 import com.trolltech.qt.core.Qt;
88 import com.trolltech.qt.core.Qt.BGMode;
89 import com.trolltech.qt.core.Qt.ItemDataRole;
90 import com.trolltech.qt.core.Qt.KeyboardModifier;
91 import com.trolltech.qt.core.Qt.MouseButton;
92 import com.trolltech.qt.core.Qt.SortOrder;
93 import com.trolltech.qt.core.Qt.WidgetAttribute;
94 import com.trolltech.qt.gui.QAbstractItemView;
95 import com.trolltech.qt.gui.QAbstractItemView.ScrollHint;
96 import com.trolltech.qt.gui.QAction;
97 import com.trolltech.qt.gui.QApplication;
98 import com.trolltech.qt.gui.QClipboard;
99 import com.trolltech.qt.gui.QCloseEvent;
100 import com.trolltech.qt.gui.QColor;
101 import com.trolltech.qt.gui.QComboBox;
102 import com.trolltech.qt.gui.QCursor;
103 import com.trolltech.qt.gui.QDesktopServices;
104 import com.trolltech.qt.gui.QDialog;
105 import com.trolltech.qt.gui.QFileDialog;
106 import com.trolltech.qt.gui.QFileDialog.AcceptMode;
107 import com.trolltech.qt.gui.QFileDialog.FileMode;
108 import com.trolltech.qt.gui.QGridLayout;
109 import com.trolltech.qt.gui.QHBoxLayout;
110 import com.trolltech.qt.gui.QIcon;
111 import com.trolltech.qt.gui.QImage;
112 import com.trolltech.qt.gui.QKeySequence;
113 import com.trolltech.qt.gui.QLabel;
114 import com.trolltech.qt.gui.QMainWindow;
115 import com.trolltech.qt.gui.QMenu;
116 import com.trolltech.qt.gui.QMessageBox;
117 import com.trolltech.qt.gui.QMessageBox.StandardButton;
118 import com.trolltech.qt.gui.QPainter;
119 import com.trolltech.qt.gui.QPalette.ColorRole;
120 import com.trolltech.qt.gui.QPixmap;
121 import com.trolltech.qt.gui.QPrintDialog;
122 import com.trolltech.qt.gui.QPrinter;
123 import com.trolltech.qt.gui.QShortcut;
124 import com.trolltech.qt.gui.QSizePolicy;
125 import com.trolltech.qt.gui.QSizePolicy.Policy;
126 import com.trolltech.qt.gui.QSpinBox;
127 import com.trolltech.qt.gui.QSplashScreen;
128 import com.trolltech.qt.gui.QSplitter;
129 import com.trolltech.qt.gui.QStatusBar;
130 import com.trolltech.qt.gui.QSystemTrayIcon;
131 import com.trolltech.qt.gui.QTableWidgetItem;
132 import com.trolltech.qt.gui.QTextEdit;
133 import com.trolltech.qt.gui.QToolBar;
134 import com.trolltech.qt.gui.QTreeWidgetItem;
135 import com.trolltech.qt.network.QNetworkAccessManager;
136 import com.trolltech.qt.network.QNetworkReply;
137 import com.trolltech.qt.network.QNetworkRequest;
138 import com.trolltech.qt.webkit.QWebPage.WebAction;
139 import com.trolltech.qt.webkit.QWebSettings;
141 import cx.fbn.nevernote.config.InitializationException;
142 import cx.fbn.nevernote.config.StartupConfig;
143 import cx.fbn.nevernote.dialog.AccountDialog;
144 import cx.fbn.nevernote.dialog.ConfigDialog;
145 import cx.fbn.nevernote.dialog.DBEncryptDialog;
146 import cx.fbn.nevernote.dialog.DatabaseLoginDialog;
147 import cx.fbn.nevernote.dialog.DatabaseStatus;
148 import cx.fbn.nevernote.dialog.FindDialog;
149 import cx.fbn.nevernote.dialog.IgnoreSync;
150 import cx.fbn.nevernote.dialog.LogFileDialog;
151 import cx.fbn.nevernote.dialog.LoginDialog;
152 import cx.fbn.nevernote.dialog.NotebookArchive;
153 import cx.fbn.nevernote.dialog.NotebookEdit;
154 import cx.fbn.nevernote.dialog.OnlineNoteHistory;
155 import cx.fbn.nevernote.dialog.PublishNotebook;
156 import cx.fbn.nevernote.dialog.SavedSearchEdit;
157 import cx.fbn.nevernote.dialog.SetIcon;
158 import cx.fbn.nevernote.dialog.ShareNotebook;
159 import cx.fbn.nevernote.dialog.SharedNotebookSyncError;
160 import cx.fbn.nevernote.dialog.StackNotebook;
161 import cx.fbn.nevernote.dialog.SynchronizationRequiredWarning;
162 import cx.fbn.nevernote.dialog.TagEdit;
163 import cx.fbn.nevernote.dialog.TagMerge;
164 import cx.fbn.nevernote.dialog.ThumbnailViewer;
165 import cx.fbn.nevernote.dialog.UpgradeAvailableDialog;
166 import cx.fbn.nevernote.dialog.WatchFolder;
167 import cx.fbn.nevernote.filters.FilterEditorNotebooks;
168 import cx.fbn.nevernote.filters.FilterEditorTags;
169 import cx.fbn.nevernote.gui.AttributeTreeWidget;
170 import cx.fbn.nevernote.gui.BrowserWindow;
171 import cx.fbn.nevernote.gui.DateAttributeFilterTable;
172 import cx.fbn.nevernote.gui.ExternalBrowse;
173 import cx.fbn.nevernote.gui.MainMenuBar;
174 import cx.fbn.nevernote.gui.NotebookTreeWidget;
175 import cx.fbn.nevernote.gui.SavedSearchTreeWidget;
176 import cx.fbn.nevernote.gui.SearchPanel;
177 import cx.fbn.nevernote.gui.TableView;
178 import cx.fbn.nevernote.gui.TagTreeWidget;
179 import cx.fbn.nevernote.gui.Thumbnailer;
180 import cx.fbn.nevernote.gui.TrashTreeWidget;
181 import cx.fbn.nevernote.gui.controls.QuotaProgressBar;
182 import cx.fbn.nevernote.sql.DatabaseConnection;
183 import cx.fbn.nevernote.sql.WatchFolderRecord;
184 import cx.fbn.nevernote.threads.IndexRunner;
185 import cx.fbn.nevernote.threads.SyncRunner;
186 import cx.fbn.nevernote.threads.ThumbnailRunner;
187 import cx.fbn.nevernote.utilities.AESEncrypter;
188 import cx.fbn.nevernote.utilities.ApplicationLogger;
189 import cx.fbn.nevernote.utilities.FileImporter;
190 import cx.fbn.nevernote.utilities.FileUtils;
191 import cx.fbn.nevernote.utilities.ListManager;
192 import cx.fbn.nevernote.utilities.SyncTimes;
193 import cx.fbn.nevernote.xml.ExportData;
194 import cx.fbn.nevernote.xml.ImportData;
195 import cx.fbn.nevernote.xml.NoteFormatter;
198 public class NeverNote extends QMainWindow{
200 QStatusBar statusBar; // Application status bar
202 DatabaseConnection conn;
204 MainMenuBar menuBar; // Main menu bar
205 FindDialog find; // Text search in note dialog
206 List<String> emitLog; // Messages displayed in the status bar;
207 QSystemTrayIcon trayIcon; // little tray icon
208 QMenu trayMenu; // System tray menu
209 QAction trayExitAction; // Exit the application
210 QAction trayShowAction; // toggle the show/hide action
211 QAction trayAddNoteAction; // Add a note from the system tray
212 QNetworkAccessManager versionChecker; // Used when checking for new versions
214 NotebookTreeWidget notebookTree; // List of notebooks
215 AttributeTreeWidget attributeTree; // List of note attributes
216 TagTreeWidget tagTree; // list of user created tags
217 SavedSearchTreeWidget savedSearchTree; // list of saved searches
218 TrashTreeWidget trashTree; // Trashcan
219 TableView noteTableView; // List of notes (the widget).
221 public BrowserWindow browserWindow; // Window containing browser & labels
222 public QToolBar toolBar; // The tool bar under the menu
223 QComboBox searchField; // search filter bar on the toolbar;
224 QShortcut searchShortcut; // Shortcut to search bar
225 boolean searchPerformed = false; // Search was done?
226 QuotaProgressBar quotaBar; // The current quota usage
228 ApplicationLogger logger;
229 List<String> selectedNotebookGUIDs; // List of notebook GUIDs
230 List<String> selectedTagGUIDs; // List of selected tag GUIDs
231 List<String> selectedNoteGUIDs; // List of selected notes
232 String selectedSavedSearchGUID; // Currently selected saved searches
233 private final HashMap<String, ExternalBrowse> externalWindows; // Notes being edited by an external window;
235 NoteFilter filter; // Note filter
236 String currentNoteGuid; // GUID of the current note
237 Note currentNote; // The currently viewed note
238 boolean noteDirty; // Has the note been changed?
239 boolean inkNote; // if this is an ink note, it is read only
240 boolean readOnly; // Is this note read-only?
243 ListManager listManager; // DB runnable task
245 List<QTemporaryFile> tempFiles; // Array of temporary files;
247 QTimer indexTimer; // timer to start the index thread
248 IndexRunner indexRunner; // thread to index notes
251 QTimer syncTimer; // Sync on an interval
252 QTimer syncDelayTimer; // Sync delay to free up database
253 SyncRunner syncRunner; // thread to do a sync.
254 QThread syncThread; // Thread which talks to evernote
255 ThumbnailRunner thumbnailRunner; // Runner for thumbnail thread
256 QThread thumbnailThread; // Thread that generates pretty pictures
257 QTimer saveTimer; // Timer to save note contents
259 QTimer authTimer; // Refresh authentication
260 QTimer externalFileSaveTimer; // Save files altered externally
261 QTimer thumbnailTimer; // Wakeup & scan for thumbnails
262 List<String> externalFiles; // External files to save later
263 List<String> importFilesKeep; // Auto-import files to save later
264 List<String> importFilesDelete; // Auto-import files to save later
266 int indexTime; // how often to try and index
267 boolean indexRunning; // Is indexing running?
268 boolean indexDisabled; // Is indexing disabled?
270 int syncThreadsReady; // number of sync threads that are free
271 int syncTime; // Sync interval
272 boolean syncRunning; // Is sync running?
273 boolean automaticSync; // do sync automatically?
274 QTreeWidgetItem attributeTreeSelected;
276 QAction prevButton; // Go to the previous item viewed
277 QAction nextButton; // Go to the next item in the history
278 QAction downButton; // Go to the next item in the list
279 QAction upButton; // Go to the prev. item in the list;
280 QAction synchronizeButton; // Synchronize with Evernote
281 QAction allNotesButton; // Reset & view all notes
282 QTimer synchronizeAnimationTimer; // Timer to change animation button
283 int synchronizeIconAngle; // Used to rotate sync icon
284 QAction printButton; // Print Button
285 QAction tagButton; // Tag edit button
286 QAction attributeButton; // Attribute information button
287 QAction emailButton; // Email button
288 QAction deleteButton; // Delete button
289 QAction newButton; // new Note Button;
290 QSpinBox zoomSpinner; // Zoom zoom
291 QAction searchClearButton; // Clear the search field
293 SearchPanel searchLayout; // Widget to hold search field, zoom, & quota
295 QSplitter mainLeftRightSplitter; // main splitter for left/right side
296 QSplitter leftSplitter1; // first left hand splitter
297 QSplitter browserIndexSplitter; // splitter between note index & note text
299 QFileSystemWatcher importKeepWatcher; // Watch & keep auto-import
300 QFileSystemWatcher importDeleteWatcher; // Watch & Delete auto-import
301 List<String> importedFiles; // History of imported files (so we don't import twice)
303 OnlineNoteHistory historyWindow; // online history window
304 List<NoteVersionId> versions; // history versions
306 QTimer threadMonitorTimer; // Timer to watch threads.
307 int dbThreadDeadCount=0; // number of consecutive dead times for the db thread
308 int syncThreadDeadCount=0; // number of consecutive dead times for the sync thread
309 int indexThreadDeadCount=0; // number of consecutive dead times for the index thread
310 int notebookThreadDeadCount=0; // number of consecutive dead times for the notebook thread
311 int tagDeadCount=0; // number of consecutive dead times for the tag thread
312 int trashDeadCount=0; // number of consecutive dead times for the trash thread
313 int saveThreadDeadCount=0; // number of consecutive dead times for the save thread
314 boolean disableTagThreadCheck=false;
315 boolean disableNotebookThreadCheck=false;
316 boolean disableTrashThreadCheck=false;
317 boolean disableSaveThreadCheck=false;
318 boolean disableSyncThreadCheck=false;
319 boolean disableIndexThreadCheck=false;
321 HashMap<String, String> noteCache; // Cash of note content
322 HashMap<String, Boolean> readOnlyCache; // List of cashe notes that are read-only
323 HashMap<String, Boolean> inkNoteCache; // List of cache notes that are ink notes
324 List<String> historyGuids; // GUIDs of previously viewed items
325 int historyPosition; // Position within the viewed items
326 boolean fromHistory; // Is this from the history queue?
327 String trashNoteGuid; // Guid to restore / set into or out of trash to save position
328 List<Thumbnailer> thumbGenerators; // generate preview image
329 ThumbnailViewer thumbnailViewer; // View preview thumbnail;
330 boolean encryptOnShutdown; // should I encrypt when I close?
331 boolean decryptOnShutdown; // should I decrypt on shutdown;
332 String encryptCipher; // What cipher should I use?
333 Signal0 minimizeToTray;
334 boolean windowMaximized = false; // Keep track of the window state for restores
335 List<String> pdfReadyQueue; // Queue of PDFs that are ready to be rendered.
336 List<QPixmap> syncIcons; // Array of icons used in sync animation
337 private boolean closeAction = false; // Used to say when to close or when to minimize
338 private static Logger log = Logger.getLogger(NeverNote.class);
339 private String saveLastPath; // last path we used
340 private final QTimer messageTimer; // Timer to clear the status message.
341 private QTimer blockTimer;
342 BrowserWindow blockingWindow;
344 String iconPath = new String("classpath:cx/fbn/nevernote/icons/");
347 //***************************************************************
348 //***************************************************************
349 //** Constructor & main entry point
350 //***************************************************************
351 //***************************************************************
352 // Application Constructor
353 @SuppressWarnings("static-access")
354 public NeverNote(DatabaseConnection dbConn) {
356 if (conn.getConnection() == null) {
357 String msg = new String(tr("Unable to connect to the database.\n\nThe most probable reason is that some other process\n" +
358 "is accessing the database or NeverNote is already running.\n\n" +
359 "Please end any other process or shutdown the other NeverNote before starting.\n\nExiting program."));
361 QMessageBox.critical(null, tr("Database Connection Error") ,msg);
364 setObjectName("mainWindow");
365 // thread().setPriority(Thread.MAX_PRIORITY);
367 logger = new ApplicationLogger("nevernote.log");
368 logger.log(logger.HIGH, "Starting Application");
370 decryptOnShutdown = false;
371 encryptOnShutdown = false;
372 conn.checkDatabaseVersion();
376 // Start building the invalid XML tables
377 Global.invalidElements = conn.getInvalidXMLTable().getInvalidElements();
378 List<String> elements = conn.getInvalidXMLTable().getInvalidAttributeElements();
380 for (int i=0; i<elements.size(); i++) {
381 Global.invalidAttributes.put(elements.get(i), conn.getInvalidXMLTable().getInvalidAttributes(elements.get(i)));
384 logger.log(logger.EXTREME, "Starting GUI build");
386 QTranslator nevernoteTranslator = new QTranslator();
387 nevernoteTranslator.load(Global.getFileManager().getTranslateFilePath("nevernote_" + QLocale.system().name() + ".qm"));
388 QApplication.instance().installTranslator(nevernoteTranslator);
390 Global.originalPalette = QApplication.palette();
391 QApplication.setStyle(Global.getStyle());
392 if (Global.useStandardPalette())
393 QApplication.setPalette(QApplication.style().standardPalette());
394 setWindowTitle(tr("NeverNote"));
396 mainLeftRightSplitter = new QSplitter();
397 setCentralWidget(mainLeftRightSplitter);
398 leftSplitter1 = new QSplitter();
399 leftSplitter1.setOrientation(Qt.Orientation.Vertical);
401 browserIndexSplitter = new QSplitter();
402 browserIndexSplitter.setOrientation(Qt.Orientation.Vertical);
404 //* Setup threads & thread timers
405 // int indexRunnerCount = Global.getIndexThreads();
406 // indexRunnerCount = 1;
407 QThreadPool.globalInstance().setMaxThreadCount(Global.threadCount); // increase max thread count
409 logger.log(logger.EXTREME, "Building list manager");
410 listManager = new ListManager(conn, logger);
412 logger.log(logger.EXTREME, "Building index runners & timers");
413 indexRunner = new IndexRunner("indexRunner.log",
414 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
415 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
416 indexThread = new QThread(indexRunner, "Index Thread");
417 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
418 indexRunner.indexImageRecognition = Global.indexImageRecognition();
419 indexRunner.indexNoteBody = Global.indexNoteBody();
420 indexRunner.indexNoteTitle = Global.indexNoteTitle();
421 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
424 synchronizeAnimationTimer = new QTimer();
425 synchronizeAnimationTimer.timeout.connect(this, "updateSyncButton()");
427 indexTimer = new QTimer();
428 indexTime = 1000*Global.getIndexThreadSleepInterval();
429 indexTimer.start(indexTime); // Start indexing timer
430 indexTimer.timeout.connect(this, "indexTimer()");
431 indexDisabled = false;
432 indexRunning = false;
434 logger.log(logger.EXTREME, "Setting sync thread & timers");
436 syncRunner = new SyncRunner("syncRunner.log",
437 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
438 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
439 syncTime = new SyncTimes().timeValue(Global.getSyncInterval());
440 syncTimer = new QTimer();
441 syncTimer.timeout.connect(this, "syncTimer()");
442 syncRunner.status.message.connect(this, "setMessage(String)");
443 syncRunner.syncSignal.finished.connect(this, "syncThreadComplete(Boolean)");
444 syncRunner.syncSignal.errorDisconnect.connect(this, "remoteErrorDisconnect()");
447 automaticSync = true;
448 syncTimer.start(syncTime*60*1000);
450 automaticSync = false;
453 syncRunner.setEvernoteUpdateCount(Global.getEvernoteUpdateCount());
454 syncThread = new QThread(syncRunner, "Synchronization Thread");
458 logger.log(logger.EXTREME, "Starting thumnail thread");
459 pdfReadyQueue = new ArrayList<String>();
460 thumbnailRunner = new ThumbnailRunner("thumbnailRunner.log",
461 Global.getDatabaseUrl(), Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
462 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword);
463 thumbnailThread = new QThread(thumbnailRunner, "Thumbnail Thread");
464 thumbnailRunner.noteSignal.thumbnailPageReady.connect(this, "thumbnailHTMLReady(String,QByteArray,Integer)");
465 thumbnailThread.start();
466 thumbGenerators = new ArrayList<Thumbnailer>();
467 thumbnailTimer = new QTimer();
468 thumbnailTimer.timeout.connect(this, "thumbnailTimer()");
470 thumbnailTimer.setInterval(500*1000); // Thumbnail every minute
471 thumbnailTimer.start();
473 logger.log(logger.EXTREME, "Starting authentication timer");
474 authTimer = new QTimer();
475 authTimer.timeout.connect(this, "authTimer()");
476 authTimer.start(1000*60*15);
477 syncRunner.syncSignal.authRefreshComplete.connect(this, "authRefreshComplete(boolean)");
479 logger.log(logger.EXTREME, "Setting save note timer");
480 saveTimer = new QTimer();
481 saveTimer.timeout.connect(this, "saveNote()");
482 if (Global.getAutoSaveInterval() > 0) {
483 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
486 listManager.saveRunner.noteSignals.noteSaveRunnerError.connect(this, "saveRunnerError(String, String)");
488 logger.log(logger.EXTREME, "Starting external file monitor timer");
489 externalFileSaveTimer = new QTimer();
490 externalFileSaveTimer.timeout.connect(this, "externalFileEditedSaver()");
491 externalFileSaveTimer.setInterval(1000*5); // save every 5 seconds;
492 externalFiles = new ArrayList<String>();
493 importFilesDelete = new ArrayList<String>();
494 importFilesKeep = new ArrayList<String>();
495 externalFileSaveTimer.start();
497 notebookTree = new NotebookTreeWidget(conn);
498 attributeTree = new AttributeTreeWidget();
499 tagTree = new TagTreeWidget(conn);
500 savedSearchTree = new SavedSearchTreeWidget();
501 trashTree = new TrashTreeWidget();
502 noteTableView = new TableView(logger, listManager);
505 searchField = new QComboBox();
506 searchField.setObjectName("searchField");
507 //setStyleSheet("QComboBox#searchField { background-color: yellow }");
508 searchField.setEditable(true);
509 searchField.activatedIndex.connect(this, "searchFieldChanged()");
510 searchField.setDuplicatesEnabled(false);
511 searchField.editTextChanged.connect(this,"searchFieldTextChanged(String)");
512 searchShortcut = new QShortcut(this);
513 setupShortcut(searchShortcut, "Focus_Search");
514 searchShortcut.activated.connect(this, "focusSearch()");
516 quotaBar = new QuotaProgressBar();
518 zoomSpinner = new QSpinBox();
519 zoomSpinner.setMinimum(10);
520 zoomSpinner.setMaximum(1000);
521 zoomSpinner.setAccelerated(true);
522 zoomSpinner.setSingleStep(10);
523 zoomSpinner.setValue(100);
524 zoomSpinner.valueChanged.connect(this, "zoomChanged()");
526 searchLayout = new SearchPanel(searchField, quotaBar, notebookTree, zoomSpinner);
529 QGridLayout leftGrid = new QGridLayout();
530 leftSplitter1.setContentsMargins(5, 0, 0, 7);
531 leftSplitter1.setLayout(leftGrid);
532 leftGrid.addWidget(searchLayout,1,1);
533 leftGrid.addWidget(tagTree,2,1);
534 leftGrid.addWidget(attributeTree,3,1);
535 leftGrid.addWidget(savedSearchTree,4,1);
536 leftGrid.addWidget(trashTree,5, 1);
538 // Setup the browser window
539 noteCache = new HashMap<String,String>();
540 readOnlyCache = new HashMap<String, Boolean>();
541 inkNoteCache = new HashMap<String, Boolean>();
542 browserWindow = new BrowserWindow(conn);
544 mainLeftRightSplitter.addWidget(leftSplitter1);
545 mainLeftRightSplitter.addWidget(browserIndexSplitter);
547 if (Global.getListView() == Global.View_List_Wide) {
548 browserIndexSplitter.addWidget(noteTableView);
549 browserIndexSplitter.addWidget(browserWindow);
551 mainLeftRightSplitter.addWidget(noteTableView);
552 mainLeftRightSplitter.addWidget(browserWindow);
555 // Setup the thumbnail viewer
556 thumbnailViewer = new ThumbnailViewer();
557 thumbnailViewer.upArrow.connect(this, "upAction()");
558 thumbnailViewer.downArrow.connect(this, "downAction()");
559 thumbnailViewer.leftArrow.connect(this, "nextViewedAction()");
560 thumbnailViewer.rightArrow.connect(this, "previousViewedAction()");
562 //Setup external browser manager
563 externalWindows = new HashMap<String, ExternalBrowse>();
565 listManager.loadNotesIndex();
566 initializeNotebookTree();
568 initializeSavedSearchTree();
569 attributeTree.itemClicked.connect(this, "attributeTreeClicked(QTreeWidgetItem, Integer)");
570 attributeTreeSelected = null;
571 initializeNoteTable();
573 selectedNoteGUIDs = new ArrayList<String>();
574 statusBar = new QStatusBar();
575 setStatusBar(statusBar);
576 menuBar = new MainMenuBar(this);
577 emitLog = new ArrayList<String>();
579 tagTree.setDeleteAction(menuBar.tagDeleteAction);
580 tagTree.setMergeAction(menuBar.tagMergeAction);
581 tagTree.setEditAction(menuBar.tagEditAction);
582 tagTree.setAddAction(menuBar.tagAddAction);
583 tagTree.setIconAction(menuBar.tagIconAction);
584 tagTree.setVisible(Global.isWindowVisible("tagTree"));
585 leftSplitter1.setVisible(Global.isWindowVisible("leftPanel"));
586 tagTree.noteSignal.tagsAdded.connect(this, "tagsAdded(String, String)");
587 menuBar.hideTags.setChecked(Global.isWindowVisible("tagTree"));
588 listManager.tagSignal.listChanged.connect(this, "reloadTagTree()");
590 if (!Global.isWindowVisible("zoom")) {
591 searchLayout.hideZoom();
592 menuBar.hideZoom.setChecked(false);
595 notebookTree.setDeleteAction(menuBar.notebookDeleteAction);
596 notebookTree.setEditAction(menuBar.notebookEditAction);
597 notebookTree.setAddAction(menuBar.notebookAddAction);
598 notebookTree.setIconAction(menuBar.notebookIconAction);
599 notebookTree.setStackAction(menuBar.notebookStackAction);
600 notebookTree.setPublishAction(menuBar.notebookPublishAction);
601 notebookTree.setShareAction(menuBar.notebookShareAction);
602 notebookTree.setVisible(Global.isWindowVisible("notebookTree"));
603 notebookTree.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
604 notebookTree.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
605 notebookTree.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
606 menuBar.hideNotebooks.setChecked(Global.isWindowVisible("notebookTree"));
608 savedSearchTree.setAddAction(menuBar.savedSearchAddAction);
609 savedSearchTree.setEditAction(menuBar.savedSearchEditAction);
610 savedSearchTree.setDeleteAction(menuBar.savedSearchDeleteAction);
611 savedSearchTree.setIconAction(menuBar.savedSearchIconAction);
612 savedSearchTree.itemSelectionChanged.connect(this, "updateSavedSearchSelection()");
613 savedSearchTree.setVisible(Global.isWindowVisible("savedSearchTree"));
614 menuBar.hideSavedSearches.setChecked(Global.isWindowVisible("savedSearchTree"));
616 noteTableView.setAddAction(menuBar.noteAdd);
617 noteTableView.setDeleteAction(menuBar.noteDelete);
618 noteTableView.setRestoreAction(menuBar.noteRestoreAction);
619 noteTableView.setNoteDuplicateAction(menuBar.noteDuplicateAction);
620 noteTableView.setNoteHistoryAction(menuBar.noteOnlineHistoryAction);
621 noteTableView.noteSignal.titleColorChanged.connect(this, "titleColorChanged(Integer)");
622 noteTableView.setMergeNotesAction(menuBar.noteMergeAction);
623 noteTableView.setCopyAsUrlAction(menuBar.noteCopyAsUrlAction);
624 noteTableView.doubleClicked.connect(this, "listDoubleClick()");
625 listManager.trashSignal.countChanged.connect(trashTree, "updateCounts(Integer)");
627 quotaBar.setMouseClickAction(menuBar.accountAction);
630 trashTree.itemSelectionChanged.connect(this, "trashTreeSelection()");
631 trashTree.setEmptyAction(menuBar.emptyTrashAction);
632 trashTree.setVisible(Global.isWindowVisible("trashTree"));
633 menuBar.hideTrash.setChecked(Global.isWindowVisible("trashTree"));
634 trashTree.updateCounts(listManager.getTrashCount());
635 attributeTree.setVisible(Global.isWindowVisible("attributeTree"));
636 menuBar.hideAttributes.setChecked(Global.isWindowVisible("attributeTree"));
638 noteTableView.setVisible(Global.isWindowVisible("noteList"));
639 menuBar.hideNoteList.setChecked(Global.isWindowVisible("noteList"));
641 if (!Global.isWindowVisible("editorButtonBar"))
642 toggleEditorButtonBar();
643 if (!Global.isWindowVisible("leftPanel"))
644 menuBar.hideLeftSide.setChecked(true);
645 if (Global.isWindowVisible("noteInformation"))
646 toggleNoteInformation();
647 quotaBar.setVisible(Global.isWindowVisible("quota"));
648 if (!quotaBar.isVisible())
649 menuBar.hideQuota.setChecked(false);
650 searchField.setVisible(Global.isWindowVisible("searchField"));
651 if (!searchField.isVisible())
652 menuBar.hideSearch.setChecked(false);
654 if (searchField.isHidden() && quotaBar.isHidden() && zoomSpinner.isHidden() && notebookTree.isHidden())
659 find = new FindDialog();
660 find.getOkButton().clicked.connect(this, "doFindText()");
662 // Setup the tray icon menu bar
663 trayShowAction = new QAction(tr("Show/Hide"), this);
664 trayExitAction = new QAction(tr("Exit"), this);
665 trayAddNoteAction = new QAction(tr("Add Note"), this);
667 trayExitAction.triggered.connect(this, "closeNeverNote()");
668 trayAddNoteAction.triggered.connect(this, "addNote()");
669 trayShowAction.triggered.connect(this, "trayToggleVisible()");
671 trayMenu = new QMenu(this);
672 trayMenu.addAction(trayAddNoteAction);
673 trayMenu.addAction(trayShowAction);
674 trayMenu.addAction(trayExitAction);
677 trayIcon = new QSystemTrayIcon(this);
678 trayIcon.setToolTip(tr("NeverNote"));
679 trayIcon.setContextMenu(trayMenu);
680 trayIcon.activated.connect(this, "trayActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
683 currentNoteGuid = Global.getLastViewedNoteGuid();
684 historyGuids = new ArrayList<String>();
688 if (!currentNoteGuid.trim().equals("")) {
689 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
692 noteIndexUpdated(true);
694 menuBar.showEditorBar.setChecked(Global.isWindowVisible("editorButtonBar"));
695 if (menuBar.showEditorBar.isChecked())
696 showEditorButtons(browserWindow);
697 tagIndexUpdated(true);
698 savedSearchIndexUpdated();
699 notebookIndexUpdated();
701 setupSyncSignalListeners();
702 setupBrowserSignalListeners();
703 setupIndexListeners();
706 tagTree.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
707 tagTree.showAllTags(true);
709 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
710 setWindowIcon(appIcon);
711 trayIcon.setIcon(appIcon);
712 if (Global.showTrayIcon())
717 scrollToGuid(currentNoteGuid);
718 if (Global.automaticLogin()) {
720 if (Global.isConnected)
723 setupFolderImports();
726 restoreWindowState(true);
728 if (Global.mimicEvernoteInterface) {
729 notebookTree.selectGuid("");
732 threadMonitorTimer = new QTimer();
733 threadMonitorTimer.timeout.connect(this, "threadMonitorCheck()");
734 threadMonitorTimer.start(1000*10); // Check for threads every 10 seconds;
736 historyGuids.add(currentNoteGuid);
739 menuBar.blockSignals(true);
740 menuBar.narrowListView.blockSignals(true);
741 menuBar.wideListView.blockSignals(true);
742 if (Global.getListView() == Global.View_List_Narrow) {
743 menuBar.narrowListView.setChecked(true);
746 menuBar.wideListView.setChecked(true);
748 menuBar.blockSignals(false);
749 menuBar.narrowListView.blockSignals(false);
750 menuBar.wideListView.blockSignals(false);
752 if (Global.getListView() == Global.View_List_Wide) {
753 browserIndexSplitter.addWidget(noteTableView);
754 browserIndexSplitter.addWidget(browserWindow);
756 mainLeftRightSplitter.addWidget(noteTableView);
757 mainLeftRightSplitter.addWidget(browserWindow);
760 messageTimer = new QTimer();
761 messageTimer.timeout.connect(this, "clearMessage()");
762 messageTimer.setInterval(1000*15);
765 int sortCol = Global.getSortColumn();
766 int sortOrder = Global.getSortOrder();
767 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
768 if (Global.checkVersionUpgrade())
773 public static void main(String[] args) {
774 log.setLevel(Level.FATAL);
775 QApplication.initialize(args);
776 QPixmap pixmap = new QPixmap("classpath:cx/fbn/nevernote/icons/splash_logo.png");
777 QSplashScreen splash = new QSplashScreen(pixmap);
780 DatabaseConnection dbConn;
783 initializeGlobalSettings(args);
785 showSplash = Global.isWindowVisible("SplashScreen");
789 dbConn = setupDatabaseConnection();
791 // Must be last stage of setup - only safe once DB is open hence we know we are the only instance running
792 Global.getFileManager().purgeResDirectory(true);
794 } catch (InitializationException e) {
797 QMessageBox.critical(null, "Startup error", "Aborting: " + e.getMessage());
801 NeverNote application = new NeverNote(dbConn);
803 application.setAttribute(WidgetAttribute.WA_DeleteOnClose, true);
804 if (Global.startMinimized())
805 application.showMinimized();
807 if (Global.wasWindowMaximized())
808 application.showMaximized();
814 splash.finish(application);
816 System.out.println("Goodbye.");
821 * Open the internal database, or create if not present
823 * @throws InitializationException when opening the database fails, e.g. because another process has it locked
825 private static DatabaseConnection setupDatabaseConnection() throws InitializationException {
826 ApplicationLogger logger = new ApplicationLogger("nevernote-database.log");
828 File f = Global.getFileManager().getDbDirFile(Global.databaseName + ".h2.db");
829 boolean dbExists = f.exists();
831 Global.setDatabaseUrl("");
833 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") > -1) {
834 boolean goodCheck = false;
836 DatabaseLoginDialog dialog = new DatabaseLoginDialog();
838 if (!dialog.okPressed())
840 Global.cipherPassword = dialog.getPassword();
841 goodCheck = databaseCheck(Global.getDatabaseUrl(), Global.getDatabaseUserid(),
842 Global.getDatabaseUserPassword(), Global.cipherPassword);
845 DatabaseConnection dbConn = new DatabaseConnection(logger,Global.getDatabaseUrl(),
846 Global.getIndexDatabaseUrl(), Global.getResourceDatabaseUrl(),
847 Global.getDatabaseUserid(), Global.getDatabaseUserPassword(), Global.cipherPassword, 0);
851 // Encrypt the database upon shutdown
852 private void encryptOnShutdown() {
853 String dbPath= Global.getFileManager().getDbDirPath("");
854 String dbName = "NeverNote";
856 Statement st = conn.getConnection().createStatement();
857 st.execute("shutdown");
858 if (QMessageBox.question(this, tr("Are you sure"),
859 tr("Are you sure you wish to encrypt the database?"),
860 QMessageBox.StandardButton.Yes,
861 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
862 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, null, Global.cipherPassword.toCharArray(), true);
863 Global.setDatabaseUrl(Global.getDatabaseUrl() + ";CIPHER="+encryptCipher);
864 Global.setDatabaseUrl(Global.getIndexDatabaseUrl() + ";CIPHER="+encryptCipher);
865 Global.setDatabaseUrl(Global.getResourceDatabaseUrl() + ";CIPHER="+encryptCipher);
866 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
868 } catch (SQLException e) {
873 // Decrypt the database upon shutdown
874 private void decryptOnShutdown() {
875 String dbPath= Global.getFileManager().getDbDirPath("");
876 String dbName = "NeverNote";
878 Statement st = conn.getConnection().createStatement();
879 st.execute("shutdown");
880 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
881 encryptCipher = "AES";
883 encryptCipher = "XTEA";
884 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
885 "Are you sure you wish to decrypt the database?"),
886 QMessageBox.StandardButton.Yes,
887 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
889 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
890 Global.setDatabaseUrl("");
891 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
893 } catch (SQLException e) {
898 * Encrypt/Decrypt the local database
900 public void doDatabaseEncrypt() {
901 // The database is not currently encrypted
902 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
903 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
904 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
905 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
906 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
907 "Do you wish to proceed?"),
908 QMessageBox.StandardButton.Yes,
909 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
912 DBEncryptDialog dialog = new DBEncryptDialog();
914 if (dialog.okPressed()) {
915 Global.cipherPassword = dialog.getPassword();
916 encryptOnShutdown = true;
917 encryptCipher = dialog.getEncryptionMethod();
920 DBEncryptDialog dialog = new DBEncryptDialog();
921 dialog.setWindowTitle(tr("Database Decryption"));
922 dialog.hideEncryption();
924 if (dialog.okPressed()) {
925 if (!dialog.getPassword().equals(Global.cipherPassword)) {
926 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
929 decryptOnShutdown = true;
936 private static void initializeGlobalSettings(String[] args) throws InitializationException {
937 StartupConfig startupConfig = new StartupConfig();
939 for (String arg : args) {
940 String lower = arg.toLowerCase();
941 if (lower.startsWith("--name="))
942 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
943 if (lower.startsWith("--home="))
944 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
945 if (lower.startsWith("--disable-viewing"))
946 startupConfig.setDisableViewing(true);
948 Global.setup(startupConfig);
953 public void closeEvent(QCloseEvent event) {
954 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
959 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
962 if (currentNote!= null & browserWindow!=null) {
963 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
964 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
967 setMessage(tr("Beginning shutdown."));
969 // Close down external windows
970 Collection<ExternalBrowse> windows = externalWindows.values();
971 Iterator<ExternalBrowse> iterator = windows.iterator();
972 while (iterator.hasNext()) {
973 ExternalBrowse browser = iterator.next();
974 browser.windowClosing.disconnect();
979 externalFileEditedSaver();
980 if (Global.isConnected && Global.synchronizeOnClose()) {
981 setMessage(tr("Performing synchronization before closing."));
982 syncRunner.syncNeeded = true;
983 syncRunner.addWork("SYNC");
985 syncRunner.keepRunning = false;
987 syncRunner.addWork("STOP");
988 setMessage("Closing Program.");
989 threadMonitorTimer.stop();
991 thumbnailRunner.addWork("STOP");
992 indexRunner.addWork("STOP");
997 if (tempFiles != null)
1000 browserWindow.noteSignal.tagsChanged.disconnect();
1001 browserWindow.noteSignal.titleChanged.disconnect();
1002 browserWindow.noteSignal.noteChanged.disconnect();
1003 browserWindow.noteSignal.notebookChanged.disconnect();
1004 browserWindow.noteSignal.createdDateChanged.disconnect();
1005 browserWindow.noteSignal.alteredDateChanged.disconnect();
1006 syncRunner.searchSignal.listChanged.disconnect();
1007 syncRunner.tagSignal.listChanged.disconnect();
1008 syncRunner.notebookSignal.listChanged.disconnect();
1009 syncRunner.noteIndexSignal.listChanged.disconnect();
1012 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1013 saveNoteColumnPositions();
1014 saveNoteIndexWidth();
1016 int width = notebookTree.columnWidth(0);
1017 Global.setColumnWidth("notebookTreeName", width);
1018 width = tagTree.columnWidth(0);
1019 Global.setColumnWidth("tagTreeName", width);
1021 Global.saveWindowMaximized(isMaximized());
1022 Global.saveCurrentNoteGuid(currentNoteGuid);
1024 int sortCol = noteTableView.proxyModel.sortColumn();
1025 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1026 Global.setSortColumn(sortCol);
1027 Global.setSortOrder(sortOrder);
1031 Global.keepRunning = false;
1033 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1034 if (indexRunner.thread().isAlive())
1035 indexRunner.thread().join(50);
1036 if (!indexRunner.thread().isAlive())
1037 logger.log(logger.MEDIUM, "Index thread has stopped");
1039 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1040 indexRunner.thread().interrupt();
1042 } catch (InterruptedException e1) {
1043 e1.printStackTrace();
1046 if (!syncRunner.thread().isAlive()) {
1047 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1048 if (syncRunner.thread().isAlive()) {
1049 System.out.println(tr("Synchronizing. Please be patient."));
1050 for(;syncRunner.thread().isAlive();) {
1053 } catch (InterruptedException e) {
1054 e.printStackTrace();
1058 logger.log(logger.MEDIUM, "Sync thread has stopped");
1061 if (encryptOnShutdown) {
1062 encryptOnShutdown();
1064 if (decryptOnShutdown) {
1065 decryptOnShutdown();
1068 Global.getFileManager().purgeResDirectory(false);
1069 } catch (InitializationException e) {
1070 System.out.println(tr("Empty res directory purge failed"));
1071 e.printStackTrace();
1073 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1076 @SuppressWarnings("unused")
1077 private void closeNeverNote() {
1081 public void setMessage(String s) {
1082 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1085 logger.log(logger.HIGH, "Message: " +s);
1086 statusBar.showMessage(s);
1090 messageTimer.stop();
1091 messageTimer.setSingleShot(true);
1092 messageTimer.start();
1095 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1098 private void clearMessage() {
1099 statusBar.clearMessage();
1103 private void waitCursor(boolean wait) {
1105 if (QApplication.overrideCursor() == null)
1106 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1109 while (QApplication.overrideCursor() != null)
1110 QApplication.restoreOverrideCursor();
1112 listManager.refreshCounters();
1115 private void setupIndexListeners() {
1116 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1117 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1118 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1119 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1121 private void setupSyncSignalListeners() {
1122 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1123 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1124 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1125 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1126 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1128 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1129 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1130 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1132 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1133 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1134 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1135 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1136 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1138 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1141 private void setupBrowserSignalListeners() {
1142 setupBrowserWindowListeners(browserWindow, true);
1145 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1146 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1147 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1148 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1149 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1150 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1151 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1152 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1153 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1154 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1155 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1156 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1157 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1158 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1159 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1160 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1161 browser.unblockApplication.connect(this, "unblockApplication()");
1162 if (master) browser.focusLost.connect(this, "saveNote()");
1163 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1164 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1167 //**************************************************
1169 //**************************************************
1170 private void setupShortcut(QShortcut action, String text) {
1171 if (!Global.shortcutKeys.containsAction(text))
1173 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1176 //***************************************************************
1177 //***************************************************************
1178 //* Settings and look & feel
1179 //***************************************************************
1180 //***************************************************************
1181 @SuppressWarnings("unused")
1182 private void settings() {
1183 logger.log(logger.HIGH, "Entering NeverNote.settings");
1184 saveNoteColumnPositions();
1185 saveNoteIndexWidth();
1187 ConfigDialog settings = new ConfigDialog(this);
1188 String dateFormat = Global.getDateFormat();
1189 String timeFormat = Global.getTimeFormat();
1191 indexTime = 1000*Global.getIndexThreadSleepInterval();
1192 indexTimer.start(indexTime); // reset indexing timer
1195 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1196 indexRunner.indexNoteBody = Global.indexNoteBody();
1197 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1198 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1199 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1200 if (Global.showTrayIcon())
1205 if (menuBar.showEditorBar.isChecked())
1206 showEditorButtons(browserWindow);
1208 // Reset the save timer
1209 if (Global.getAutoSaveInterval() > 0)
1210 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1215 // Set special reloads
1216 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1217 conn.executeSql("Delete from LinkedNotebook");
1218 conn.executeSql("delete from SharedNotebook");
1219 conn.executeSql("Delete from Notebook where linked=true");
1220 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1221 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1226 readOnlyCache.clear();
1227 inkNoteCache.clear();
1228 noteIndexUpdated(true);
1230 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1232 // Restore things to the way they were
1233 private void restoreWindowState(boolean mainWindow) {
1234 // We need to name things or this doesn't work.
1235 setObjectName("NeverNote");
1236 restoreState(Global.restoreState(objectName()));
1237 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1238 browserIndexSplitter.setObjectName("browserIndexSplitter");
1239 leftSplitter1.setObjectName("leftSplitter1");
1241 // Restore the actual positions.
1243 restoreGeometry(Global.restoreGeometry(objectName()));
1244 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1245 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1246 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1249 // Save window positions for the next start
1250 private void saveWindowState() {
1251 Global.saveGeometry(objectName(), saveGeometry());
1252 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1253 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1254 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1255 Global.saveState(objectName(), saveState());
1257 // Load the style sheet
1258 private void loadStyleSheet() {
1259 String styleSheetName = "default.qss";
1260 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1261 styleSheetName = "default-cleanlooks.qss";
1262 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1263 QFile file = new QFile(fileName);
1265 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1266 if (!file.exists()) {
1267 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1268 file = new QFile(fileName);
1270 file.open(OpenModeFlag.ReadOnly);
1271 String styleSheet = file.readAll().toString();
1273 setStyleSheet(styleSheet);
1275 // Save column positions for the next time
1276 private void saveNoteColumnPositions() {
1277 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1278 Global.setColumnPosition("noteTableCreationPosition", position);
1279 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1280 Global.setColumnPosition("noteTableTagPosition", position);
1281 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1282 Global.setColumnPosition("noteTableNotebookPosition", position);
1283 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1284 Global.setColumnPosition("noteTableChangedPosition", position);
1285 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1286 Global.setColumnPosition("noteTableAuthorPosition", position);
1287 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1288 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1289 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1290 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1291 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1292 Global.setColumnPosition("noteTableTitlePosition", position);
1293 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1294 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1295 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1296 Global.setColumnPosition("noteTableGuidPosition", position);
1297 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1298 Global.setColumnPosition("noteTableThumbnailPosition", position);
1301 // Save column widths for the next time
1302 private void saveNoteIndexWidth() {
1304 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1305 Global.setColumnWidth("noteTableCreationPosition", width);
1306 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1307 Global.setColumnWidth("noteTableChangedPosition", width);
1308 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1309 Global.setColumnWidth("noteTableGuidPosition", width);
1310 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1311 Global.setColumnWidth("noteTableNotebookPosition", width);
1312 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1313 Global.setColumnWidth("noteTableTagPosition", width);
1314 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1315 Global.setColumnWidth("noteTableTitlePosition", width);
1316 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1317 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1318 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1319 Global.setColumnWidth("noteTableAuthorPosition", width);
1320 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1321 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1322 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1323 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1324 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1325 Global.setColumnWidth("noteTableThumbnailPosition", width);
1326 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1327 Global.setColumnWidth("noteTableGuidPosition", width);
1330 @SuppressWarnings("unused")
1331 private void toggleSearchWindow() {
1332 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1333 searchLayout.toggleSearchField();
1334 menuBar.hideSearch.setChecked(searchField.isVisible());
1335 Global.saveWindowVisible("searchField", searchField.isVisible());
1336 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1338 @SuppressWarnings("unused")
1339 private void toggleQuotaWindow() {
1340 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1341 searchLayout.toggleQuotaBar();
1342 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1343 Global.saveWindowVisible("quota", quotaBar.isVisible());
1344 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1346 @SuppressWarnings("unused")
1347 private void toggleZoomWindow() {
1348 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1349 searchLayout.toggleZoom();
1350 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1351 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1352 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1357 //***************************************************************
1358 //***************************************************************
1359 //** These functions deal with Notebook menu items
1360 //***************************************************************
1361 //***************************************************************
1362 // Setup the tree containing the user's notebooks.
1363 private void initializeNotebookTree() {
1364 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1365 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1366 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1367 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1368 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1370 // Listener when a notebook is selected
1371 private void notebookTreeSelection() {
1372 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1375 clearAttributeFilter();
1376 clearSavedSearchFilter();
1377 if (Global.mimicEvernoteInterface) {
1379 searchField.clear();
1381 menuBar.noteRestoreAction.setVisible(false);
1382 menuBar.notebookEditAction.setEnabled(true);
1383 menuBar.notebookDeleteAction.setEnabled(true);
1384 menuBar.notebookPublishAction.setEnabled(true);
1385 menuBar.notebookShareAction.setEnabled(true);
1386 menuBar.notebookIconAction.setEnabled(true);
1387 menuBar.notebookStackAction.setEnabled(true);
1388 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1389 selectedNotebookGUIDs.clear();
1391 String stackName = "";
1392 if (selections.size() > 0) {
1393 guid = (selections.get(0).text(2));
1394 stackName = selections.get(0).text(0);
1396 if (!Global.mimicEvernoteInterface) {
1397 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1398 if (selections.size()==0) {
1399 selectedNotebookGUIDs.clear();
1400 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1401 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1403 menuBar.notebookEditAction.setEnabled(false);
1404 menuBar.notebookDeleteAction.setEnabled(false);
1405 menuBar.notebookStackAction.setEnabled(false);
1406 menuBar.notebookIconAction.setEnabled(false);
1409 if (!guid.equals("") && !guid.equals("STACK")) {
1410 selectedNotebookGUIDs.add(guid);
1411 menuBar.notebookIconAction.setEnabled(true);
1413 menuBar.notebookIconAction.setEnabled(true);
1414 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1415 Notebook book = listManager.getNotebookIndex().get(j);
1416 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1417 selectedNotebookGUIDs.add(book.getGuid());
1420 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1421 listManager.loadNotesIndex();
1422 noteIndexUpdated(false);
1423 refreshEvernoteNote(true);
1424 listManager.refreshCounters = true;
1425 listManager.refreshCounters();
1426 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1429 private void clearNotebookFilter() {
1430 notebookTree.blockSignals(true);
1431 notebookTree.clearSelection();
1432 menuBar.noteRestoreAction.setVisible(false);
1433 menuBar.notebookEditAction.setEnabled(false);
1434 menuBar.notebookDeleteAction.setEnabled(false);
1435 selectedNotebookGUIDs.clear();
1436 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1437 notebookTree.blockSignals(false);
1439 // Triggered when the notebook DB has been updated
1440 private void notebookIndexUpdated() {
1441 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1443 // Get the possible icons
1444 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1445 notebookTree.setIcons(icons);
1447 if (selectedNotebookGUIDs == null)
1448 selectedNotebookGUIDs = new ArrayList<String>();
1449 List<Notebook> books = conn.getNotebookTable().getAll();
1450 for (int i=books.size()-1; i>=0; i--) {
1451 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1452 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1454 j=listManager.getArchiveNotebookIndex().size();
1460 listManager.countNotebookResults(listManager.getNoteIndex());
1461 notebookTree.blockSignals(true);
1462 notebookTree.load(books, listManager.getLocalNotebooks());
1463 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1464 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1466 selectedNotebookGUIDs.remove(i);
1468 listManager.refreshCounters = true;
1469 listManager.refreshCounters();
1470 notebookTree.blockSignals(false);
1472 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1474 // Show/Hide note information
1475 @SuppressWarnings("unused")
1476 private void toggleNotebookWindow() {
1477 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1478 searchLayout.toggleNotebook();
1479 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1480 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1481 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1483 // Add a new notebook
1484 @SuppressWarnings("unused")
1485 private void addNotebook() {
1486 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1487 NotebookEdit edit = new NotebookEdit();
1488 edit.setNotebooks(listManager.getNotebookIndex());
1491 if (!edit.okPressed())
1494 Calendar currentTime = new GregorianCalendar();
1495 Long l = new Long(currentTime.getTimeInMillis());
1496 String randint = new String(Long.toString(l));
1498 Notebook newBook = new Notebook();
1499 newBook.setUpdateSequenceNum(0);
1500 newBook.setGuid(randint);
1501 newBook.setName(edit.getNotebook());
1502 newBook.setServiceCreated(new Date().getTime());
1503 newBook.setServiceUpdated(new Date().getTime());
1504 newBook.setDefaultNotebook(false);
1505 newBook.setPublished(false);
1507 listManager.getNotebookIndex().add(newBook);
1509 listManager.getLocalNotebooks().add(newBook.getGuid());
1510 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1511 notebookIndexUpdated();
1512 listManager.countNotebookResults(listManager.getNoteIndex());
1513 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1514 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1516 // Edit an existing notebook
1517 @SuppressWarnings("unused")
1518 private void stackNotebook() {
1519 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1520 StackNotebook edit = new StackNotebook();
1522 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1523 QTreeWidgetItem currentSelection;
1524 for (int i=0; i<selections.size(); i++) {
1525 currentSelection = selections.get(0);
1526 String guid = currentSelection.text(2);
1527 if (guid.equalsIgnoreCase("")) {
1528 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1531 if (guid.equalsIgnoreCase("STACK")) {
1532 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1537 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1542 if (!edit.okPressed())
1545 String stack = edit.getStackName();
1547 for (int i=0; i<selections.size(); i++) {
1548 currentSelection = selections.get(i);
1549 String guid = currentSelection.text(2);
1550 listManager.updateNotebookStack(guid, stack);
1552 notebookIndexUpdated();
1553 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1555 // Edit an existing notebook
1556 @SuppressWarnings("unused")
1557 private void editNotebook() {
1558 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1559 NotebookEdit edit = new NotebookEdit();
1561 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1562 QTreeWidgetItem currentSelection;
1563 currentSelection = selections.get(0);
1564 edit.setNotebook(currentSelection.text(0));
1566 String guid = currentSelection.text(2);
1567 if (!guid.equalsIgnoreCase("STACK")) {
1568 edit.setTitle(tr("Edit Notebook"));
1569 edit.setNotebooks(listManager.getNotebookIndex());
1570 edit.setLocalCheckboxEnabled(false);
1571 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1572 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1573 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1574 i=listManager.getNotebookIndex().size();
1578 edit.setTitle(tr("Edit Stack"));
1579 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1580 edit.hideLocalCheckbox();
1581 edit.hideDefaultCheckbox();
1586 if (!edit.okPressed())
1590 if (guid.equalsIgnoreCase("STACK")) {
1591 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1592 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1593 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1594 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1595 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1597 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1598 currentSelection.setText(0, edit.getNotebook());
1602 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1603 currentSelection.setText(0, edit.getNotebook());
1605 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1606 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1607 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1608 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1609 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1610 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1611 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1612 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1614 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1615 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1616 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1617 linkedNotebook.setShareName(edit.getNotebook());
1618 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1620 i=listManager.getNotebookIndex().size();
1624 // Build a list of non-closed notebooks
1625 List<Notebook> nbooks = new ArrayList<Notebook>();
1626 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1627 boolean found=false;
1628 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1629 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1633 nbooks.add(listManager.getNotebookIndex().get(i));
1637 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1638 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1639 browserWindow.setNotebookList(filteredBooks);
1640 Iterator<String> set = externalWindows.keySet().iterator();
1641 while(set.hasNext())
1642 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1643 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1645 // Publish a notebook
1646 @SuppressWarnings("unused")
1647 private void publishNotebook() {
1648 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1649 QTreeWidgetItem currentSelection;
1650 currentSelection = selections.get(0);
1651 String guid = currentSelection.text(2);
1653 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1658 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1659 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1660 n = listManager.getNotebookIndex().get(i);
1662 i = listManager.getNotebookIndex().size();
1668 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1671 if (!publish.okClicked())
1674 Publishing p = publish.getPublishing();
1675 boolean isPublished = !publish.isStopPressed();
1676 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1677 n.setPublished(isPublished);
1679 listManager.getNotebookIndex().set(position, n);
1680 notebookIndexUpdated();
1682 // Publish a notebook
1683 @SuppressWarnings("unused")
1684 private void shareNotebook() {
1685 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1686 QTreeWidgetItem currentSelection;
1687 currentSelection = selections.get(0);
1688 String guid = currentSelection.text(2);
1690 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1694 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1695 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1696 n = listManager.getNotebookIndex().get(i);
1697 i = listManager.getNotebookIndex().size();
1701 String authToken = null;
1702 if (syncRunner.isConnected)
1703 authToken = syncRunner.authToken;
1704 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1709 // Delete an existing notebook
1710 @SuppressWarnings("unused")
1711 private void deleteNotebook() {
1712 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1713 boolean stacksFound = false;
1714 boolean notebooksFound = false;
1715 boolean assigned = false;
1716 // Check if any notes have this notebook
1717 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1718 for (int i=0; i<selections.size(); i++) {
1719 QTreeWidgetItem currentSelection;
1720 currentSelection = selections.get(i);
1721 String guid = currentSelection.text(2);
1722 if (!guid.equalsIgnoreCase("STACK")) {
1723 notebooksFound = true;
1724 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1725 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1726 if (noteGuid.equals(guid)) {
1728 j=listManager.getNoteIndex().size();
1729 i=selections.size();
1737 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1738 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1742 if (conn.getNotebookTable().getAll().size() == 1) {
1743 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1747 // If all notebooks are clear, verify the delete
1748 String msg1 = new String(tr("Delete selected notebooks?"));
1749 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1750 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1751 " not deleted unless selected?"));
1753 if (stacksFound && notebooksFound)
1755 if (!stacksFound && notebooksFound)
1757 if (stacksFound && !notebooksFound)
1759 if (QMessageBox.question(this, tr("Confirmation"), msg,
1760 QMessageBox.StandardButton.Yes,
1761 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1765 // If confirmed, delete the notebook
1766 for (int i=selections.size()-1; i>=0; i--) {
1767 QTreeWidgetItem currentSelection;
1768 currentSelection = selections.get(i);
1769 String guid = currentSelection.text(2);
1770 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1771 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1772 listManager.renameStack(currentSelection.text(0), "");
1774 conn.getNotebookTable().expungeNotebook(guid, true);
1775 listManager.deleteNotebook(guid);
1779 notebookIndexUpdated();
1780 // notebookTreeSelection();
1781 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1782 // listManager.countNotebookResults(listManager.getNoteIndex());
1783 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1785 // A note's notebook has been updated
1786 @SuppressWarnings("unused")
1787 private void updateNoteNotebook(String guid, String notebookGuid) {
1789 // Update the list manager
1790 listManager.updateNoteNotebook(guid, notebookGuid);
1791 listManager.countNotebookResults(listManager.getNoteIndex());
1792 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1794 // Find the name of the notebook
1795 String notebookName = null;
1796 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1797 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1798 notebookName = listManager.getNotebookIndex().get(i).getName();
1803 // If we found the name, update the browser window
1804 if (notebookName != null) {
1805 updateListNoteNotebook(guid, notebookName);
1806 if (guid.equals(currentNoteGuid)) {
1807 int pos = browserWindow.notebookBox.findText(notebookName);
1809 browserWindow.notebookBox.setCurrentIndex(pos);
1813 // If we're dealing with the current note, then we need to be sure and update the notebook there
1814 if (guid.equals(currentNoteGuid)) {
1815 if (currentNote != null) {
1816 currentNote.setNotebookGuid(notebookGuid);
1820 // Open/close notebooks
1821 @SuppressWarnings("unused")
1822 private void closeNotebooks() {
1823 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1825 if (!na.okClicked())
1829 listManager.getArchiveNotebookIndex().clear();
1831 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1832 String text = na.getClosedBookList().takeItem(i).text();
1833 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1834 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1835 Notebook n = listManager.getNotebookIndex().get(j);
1836 conn.getNotebookTable().setArchived(n.getGuid(),true);
1837 listManager.getArchiveNotebookIndex().add(n);
1838 j=listManager.getNotebookIndex().size();
1843 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1844 String text = na.getOpenBookList().takeItem(i).text();
1845 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1846 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1847 Notebook n = listManager.getNotebookIndex().get(j);
1848 conn.getNotebookTable().setArchived(n.getGuid(),false);
1849 j=listManager.getNotebookIndex().size();
1853 notebookTreeSelection();
1854 listManager.loadNotesIndex();
1855 notebookIndexUpdated();
1856 noteIndexUpdated(false);
1857 reloadTagTree(true);
1858 // noteIndexUpdated(false);
1860 // Build a list of non-closed notebooks
1861 List<Notebook> nbooks = new ArrayList<Notebook>();
1862 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1863 boolean found=false;
1864 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1865 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1869 nbooks.add(listManager.getNotebookIndex().get(i));
1872 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1873 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1874 browserWindow.setNotebookList(filteredBooks);
1876 // Update any external windows
1877 Iterator<String> set = externalWindows.keySet().iterator();
1878 while(set.hasNext())
1879 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1883 // Change the notebook's icon
1884 @SuppressWarnings("unused")
1885 private void setNotebookIcon() {
1886 boolean stackSelected = false;
1887 boolean allNotebookSelected = false;
1889 QTreeWidgetItem currentSelection;
1890 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1891 if (selections.size() == 0)
1894 currentSelection = selections.get(0);
1895 String guid = currentSelection.text(2);
1896 if (guid.equalsIgnoreCase(""))
1897 allNotebookSelected = true;
1898 if (guid.equalsIgnoreCase("STACK"))
1899 stackSelected = true;
1901 QIcon currentIcon = currentSelection.icon(0);
1905 if (!stackSelected && !allNotebookSelected) {
1906 icon = conn.getNotebookTable().getIcon(guid);
1908 dialog = new SetIcon(currentIcon, saveLastPath);
1909 dialog.setUseDefaultIcon(true);
1911 dialog = new SetIcon(icon, saveLastPath);
1912 dialog.setUseDefaultIcon(false);
1915 if (stackSelected) {
1916 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1918 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1921 dialog = new SetIcon(currentIcon, saveLastPath);
1922 dialog.setUseDefaultIcon(true);
1924 dialog = new SetIcon(icon, saveLastPath);
1925 dialog.setUseDefaultIcon(false);
1929 if (dialog.okPressed()) {
1930 saveLastPath = dialog.getPath();
1932 QIcon newIcon = dialog.getIcon();
1933 if (stackSelected) {
1934 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1935 if (newIcon == null) {
1936 newIcon = new QIcon(iconPath+"books2.png");
1938 currentSelection.setIcon(0,newIcon);
1941 if (allNotebookSelected) {
1942 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1943 if (newIcon == null) {
1944 newIcon = new QIcon(iconPath+"notebook-green.png");
1946 currentSelection.setIcon(0,newIcon);
1949 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1950 if (newIcon == null) {
1951 boolean isPublished = false;;
1952 boolean found = false;
1953 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1954 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1955 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1959 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1961 currentSelection.setIcon(0, newIcon);
1967 //***************************************************************
1968 //***************************************************************
1969 //** These functions deal with Tag menu items
1970 //***************************************************************
1971 //***************************************************************
1972 // Add a new notebook
1973 @SuppressWarnings("unused")
1974 private void addTag() {
1975 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1976 TagEdit edit = new TagEdit();
1977 edit.setTagList(listManager.getTagIndex());
1979 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1980 QTreeWidgetItem currentSelection = null;
1981 if (selections.size() > 0) {
1982 currentSelection = selections.get(0);
1983 edit.setParentTag(currentSelection.text(0));
1988 if (!edit.okPressed())
1991 Calendar currentTime = new GregorianCalendar();
1992 Long l = new Long(currentTime.getTimeInMillis());
1993 String randint = new String(Long.toString(l));
1995 Tag newTag = new Tag();
1996 newTag.setUpdateSequenceNum(0);
1997 newTag.setGuid(randint);
1998 newTag.setName(edit.getTag());
1999 if (edit.getParentTag().isChecked()) {
2000 newTag.setParentGuid(currentSelection.text(2));
2001 newTag.setParentGuidIsSet(true);
2002 currentSelection.setExpanded(true);
2004 conn.getTagTable().addTag(newTag, true);
2005 listManager.getTagIndex().add(newTag);
2006 reloadTagTree(true);
2008 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2010 @SuppressWarnings("unused")
2011 private void reloadTagTree() {
2012 reloadTagTree(false);
2014 private void reloadTagTree(boolean reload) {
2015 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2016 tagIndexUpdated(reload);
2017 boolean filter = false;
2019 listManager.countTagResults(listManager.getNoteIndex());
2020 if (notebookTree.selectedItems().size() > 0
2021 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2023 if (tagTree.selectedItems().size() > 0)
2025 tagTree.showAllTags(!filter);
2026 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2028 // Edit an existing tag
2029 @SuppressWarnings("unused")
2030 private void editTag() {
2031 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2032 TagEdit edit = new TagEdit();
2033 edit.setTitle("Edit Tag");
2034 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2035 QTreeWidgetItem currentSelection;
2036 currentSelection = selections.get(0);
2037 edit.setTag(currentSelection.text(0));
2038 edit.setTagList(listManager.getTagIndex());
2041 if (!edit.okPressed())
2044 String guid = currentSelection.text(2);
2045 currentSelection.setText(0,edit.getTag());
2047 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2048 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2049 listManager.getTagIndex().get(i).setName(edit.getTag());
2050 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2051 updateListTagName(guid);
2052 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2053 browserWindow.setTag(getTagNamesForNote(currentNote));
2054 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2058 browserWindow.setTag(getTagNamesForNote(currentNote));
2059 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2061 // Delete an existing tag
2062 @SuppressWarnings("unused")
2063 private void deleteTag() {
2064 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2066 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2067 QMessageBox.StandardButton.Yes,
2068 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2072 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2073 for (int i=selections.size()-1; i>=0; i--) {
2074 QTreeWidgetItem currentSelection;
2075 currentSelection = selections.get(i);
2076 removeTagItem(currentSelection.text(2));
2078 tagIndexUpdated(true);
2080 listManager.countTagResults(listManager.getNoteIndex());
2081 // tagTree.updateCounts(listManager.getTagCounter());
2082 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2084 // Remove a tag tree item. Go recursively down & remove the children too
2085 private void removeTagItem(String guid) {
2086 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2087 String parent = listManager.getTagIndex().get(j).getParentGuid();
2088 if (parent != null && parent.equals(guid)) {
2089 //Remove this tag's children
2090 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2093 //Now, remove this tag
2094 removeListTagName(guid);
2095 conn.getTagTable().expungeTag(guid, true);
2096 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2097 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2098 listManager.getTagIndex().remove(a);
2103 // Setup the tree containing the user's tags
2104 private void initializeTagTree() {
2105 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2106 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2107 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2108 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2109 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2110 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2112 // Listener when a tag is selected
2113 private void tagTreeSelection() {
2114 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2117 clearAttributeFilter();
2118 clearSavedSearchFilter();
2120 menuBar.noteRestoreAction.setVisible(false);
2122 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2123 QTreeWidgetItem currentSelection;
2124 selectedTagGUIDs.clear();
2125 for (int i=0; i<selections.size(); i++) {
2126 currentSelection = selections.get(i);
2127 selectedTagGUIDs.add(currentSelection.text(2));
2129 if (selections.size() > 0) {
2130 menuBar.tagEditAction.setEnabled(true);
2131 menuBar.tagDeleteAction.setEnabled(true);
2132 menuBar.tagIconAction.setEnabled(true);
2135 menuBar.tagEditAction.setEnabled(false);
2136 menuBar.tagDeleteAction.setEnabled(false);
2137 menuBar.tagIconAction.setEnabled(true);
2139 if (selections.size() > 1)
2140 menuBar.tagMergeAction.setEnabled(true);
2142 menuBar.tagMergeAction.setEnabled(false);
2143 listManager.setSelectedTags(selectedTagGUIDs);
2144 listManager.loadNotesIndex();
2145 noteIndexUpdated(false);
2146 refreshEvernoteNote(true);
2147 listManager.refreshCounters = true;
2148 listManager.refreshCounters();
2149 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2151 // trigger the tag index to be refreshed
2152 @SuppressWarnings("unused")
2153 private void tagIndexUpdated() {
2154 tagIndexUpdated(true);
2156 private void tagIndexUpdated(boolean reload) {
2157 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2158 if (selectedTagGUIDs == null)
2159 selectedTagGUIDs = new ArrayList<String>();
2161 listManager.reloadTagIndex();
2163 tagTree.blockSignals(true);
2165 tagTree.setIcons(conn.getTagTable().getAllIcons());
2166 tagTree.load(listManager.getTagIndex());
2169 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2170 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2172 selectedTagGUIDs.remove(i);
2174 tagTree.blockSignals(false);
2176 browserWindow.setTag(getTagNamesForNote(currentNote));
2177 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2179 // Show/Hide note information
2180 @SuppressWarnings("unused")
2181 private void toggleTagWindow() {
2182 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2183 if (tagTree.isVisible())
2187 menuBar.hideTags.setChecked(tagTree.isVisible());
2188 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2189 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2191 // A note's tags have been updated
2192 @SuppressWarnings("unused")
2193 private void updateNoteTags(String guid, List<String> tags) {
2194 // Save any new tags. We'll need them later.
2195 List<String> newTags = new ArrayList<String>();
2196 for (int i=0; i<tags.size(); i++) {
2197 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2198 newTags.add(tags.get(i));
2201 listManager.saveNoteTags(guid, tags);
2202 listManager.countTagResults(listManager.getNoteIndex());
2203 StringBuffer names = new StringBuffer("");
2204 for (int i=0; i<tags.size(); i++) {
2205 names = names.append(tags.get(i));
2206 if (i<tags.size()-1) {
2207 names.append(Global.tagDelimeter + " ");
2210 browserWindow.setTag(names.toString());
2213 // Now, we need to add any new tags to the tag tree
2214 for (int i=0; i<newTags.size(); i++)
2215 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2217 // Get a string containing all tag names for a note
2218 private String getTagNamesForNote(Note n) {
2219 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2220 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2222 StringBuffer buffer = new StringBuffer(100);
2223 Vector<String> v = new Vector<String>();
2224 List<String> guids = n.getTagGuids();
2229 for (int i=0; i<guids.size(); i++) {
2230 v.add(listManager.getTagNameByGuid(guids.get(i)));
2232 Comparator<String> comparator = Collections.reverseOrder();
2233 Collections.sort(v,comparator);
2234 Collections.reverse(v);
2236 for (int i = 0; i<v.size(); i++) {
2238 buffer.append(", ");
2239 buffer.append(v.get(i));
2242 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2243 return buffer.toString();
2245 // Tags were added via dropping notes from the note list
2246 @SuppressWarnings("unused")
2247 private void tagsAdded(String noteGuid, String tagGuid) {
2248 String tagName = null;
2249 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2250 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2251 tagName = listManager.getTagIndex().get(i).getName();
2252 i=listManager.getTagIndex().size();
2255 if (tagName == null)
2258 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2259 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2260 List<String> tagNames = new ArrayList<String>();
2261 tagNames.add(new String(tagName));
2262 Note n = listManager.getMasterNoteIndex().get(i);
2263 for (int j=0; j<n.getTagNames().size(); j++) {
2264 tagNames.add(new String(n.getTagNames().get(j)));
2266 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2267 if (n.getGuid().equals(currentNoteGuid)) {
2268 Collections.sort(tagNames);
2269 String display = "";
2270 for (int j=0; j<tagNames.size(); j++) {
2271 display = display+tagNames.get(j);
2272 if (j+2<tagNames.size())
2273 display = display+Global.tagDelimeter+" ";
2275 browserWindow.setTag(display);
2277 i=listManager.getMasterNoteIndex().size();
2282 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2284 private void clearTagFilter() {
2285 tagTree.blockSignals(true);
2286 tagTree.clearSelection();
2287 menuBar.noteRestoreAction.setVisible(false);
2288 menuBar.tagEditAction.setEnabled(false);
2289 menuBar.tagMergeAction.setEnabled(false);
2290 menuBar.tagDeleteAction.setEnabled(false);
2291 menuBar.tagIconAction.setEnabled(false);
2292 selectedTagGUIDs.clear();
2293 listManager.setSelectedTags(selectedTagGUIDs);
2294 tagTree.blockSignals(false);
2296 // Change the icon for a tag
2297 @SuppressWarnings("unused")
2298 private void setTagIcon() {
2299 QTreeWidgetItem currentSelection;
2300 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2301 if (selections.size() == 0)
2304 currentSelection = selections.get(0);
2305 String guid = currentSelection.text(2);
2307 QIcon currentIcon = currentSelection.icon(0);
2308 QIcon icon = conn.getTagTable().getIcon(guid);
2311 dialog = new SetIcon(currentIcon, saveLastPath);
2312 dialog.setUseDefaultIcon(true);
2314 dialog = new SetIcon(icon, saveLastPath);
2315 dialog.setUseDefaultIcon(false);
2318 if (dialog.okPressed()) {
2319 saveLastPath = dialog.getPath();
2320 QIcon newIcon = dialog.getIcon();
2321 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2322 if (newIcon == null)
2323 newIcon = new QIcon(iconPath+"tag.png");
2324 currentSelection.setIcon(0, newIcon);
2329 @SuppressWarnings("unused")
2330 private void mergeTags() {
2331 List<Tag> tags = new ArrayList<Tag>();
2332 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2333 for (int i=0; i<selections.size(); i++) {
2334 Tag record = new Tag();
2335 record.setGuid(selections.get(i).text(2));
2336 record.setName(selections.get(i).text(0));
2340 TagMerge mergeDialog = new TagMerge(tags);
2342 if (!mergeDialog.okClicked())
2344 String newGuid = mergeDialog.getNewTagGuid();
2346 for (int i=0; i<tags.size(); i++) {
2347 if (!tags.get(i).getGuid().equals(newGuid)) {
2348 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2349 for (int j=0; j<noteGuids.size(); j++) {
2350 String noteGuid = noteGuids.get(j);
2351 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2352 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2353 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2357 listManager.reloadIndexes();
2360 //***************************************************************
2361 //***************************************************************
2362 //** These functions deal with Saved Search menu items
2363 //***************************************************************
2364 //***************************************************************
2365 // Add a new notebook
2366 @SuppressWarnings("unused")
2367 private void addSavedSearch() {
2368 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2369 SavedSearchEdit edit = new SavedSearchEdit();
2370 edit.setSearchList(listManager.getSavedSearchIndex());
2373 if (!edit.okPressed())
2376 Calendar currentTime = new GregorianCalendar();
2377 Long l = new Long(currentTime.getTimeInMillis());
2378 String randint = new String(Long.toString(l));
2380 SavedSearch search = new SavedSearch();
2381 search.setUpdateSequenceNum(0);
2382 search.setGuid(randint);
2383 search.setName(edit.getName());
2384 search.setQuery(edit.getQuery());
2385 search.setFormat(QueryFormat.USER);
2386 listManager.getSavedSearchIndex().add(search);
2387 conn.getSavedSearchTable().addSavedSearch(search, true);
2388 savedSearchIndexUpdated();
2389 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2391 // Edit an existing tag
2392 @SuppressWarnings("unused")
2393 private void editSavedSearch() {
2394 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2395 SavedSearchEdit edit = new SavedSearchEdit();
2396 edit.setTitle(tr("Edit Search"));
2397 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2398 QTreeWidgetItem currentSelection;
2399 currentSelection = selections.get(0);
2400 String guid = currentSelection.text(1);
2401 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2402 edit.setName(currentSelection.text(0));
2403 edit.setQuery(s.getQuery());
2404 edit.setSearchList(listManager.getSavedSearchIndex());
2407 if (!edit.okPressed())
2410 List<SavedSearch> list = listManager.getSavedSearchIndex();
2411 SavedSearch search = null;
2412 boolean found = false;
2413 for (int i=0; i<list.size(); i++) {
2414 search = list.get(i);
2415 if (search.getGuid().equals(guid)) {
2422 search.setName(edit.getName());
2423 search.setQuery(edit.getQuery());
2424 conn.getSavedSearchTable().updateSavedSearch(search, true);
2425 savedSearchIndexUpdated();
2426 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2428 // Delete an existing tag
2429 @SuppressWarnings("unused")
2430 private void deleteSavedSearch() {
2431 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2433 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2434 QMessageBox.StandardButton.Yes,
2435 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2439 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2440 for (int i=selections.size()-1; i>=0; i--) {
2441 QTreeWidgetItem currentSelection;
2442 currentSelection = selections.get(i);
2443 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2444 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2445 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2446 listManager.getSavedSearchIndex().remove(j);
2447 j=listManager.getSavedSearchIndex().size()+1;
2450 selections.remove(i);
2452 savedSearchIndexUpdated();
2453 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2455 // Setup the tree containing the user's tags
2456 private void initializeSavedSearchTree() {
2457 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2458 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2459 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2461 // Listener when a tag is selected
2462 @SuppressWarnings("unused")
2463 private void savedSearchTreeSelection() {
2464 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2466 clearNotebookFilter();
2469 clearAttributeFilter();
2471 String currentGuid = selectedSavedSearchGUID;
2472 menuBar.savedSearchEditAction.setEnabled(true);
2473 menuBar.savedSearchDeleteAction.setEnabled(true);
2474 menuBar.savedSearchIconAction.setEnabled(true);
2475 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2476 QTreeWidgetItem currentSelection;
2477 selectedSavedSearchGUID = "";
2478 for (int i=0; i<selections.size(); i++) {
2479 currentSelection = selections.get(i);
2480 if (currentSelection.text(1).equals(currentGuid)) {
2481 currentSelection.setSelected(false);
2483 selectedSavedSearchGUID = currentSelection.text(1);
2485 // i = selections.size() +1;
2488 // There is the potential for no notebooks to be selected if this
2489 // happens then we make it look like all notebooks were selecetd.
2490 // If that happens, just select the "all notebooks"
2491 if (selections.size()==0) {
2492 clearSavedSearchFilter();
2494 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2496 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2498 private void clearSavedSearchFilter() {
2499 menuBar.savedSearchEditAction.setEnabled(false);
2500 menuBar.savedSearchDeleteAction.setEnabled(false);
2501 menuBar.savedSearchIconAction.setEnabled(false);
2502 savedSearchTree.blockSignals(true);
2503 savedSearchTree.clearSelection();
2504 savedSearchTree.blockSignals(false);
2505 selectedSavedSearchGUID = "";
2506 searchField.setEditText("");
2507 searchPerformed = false;
2508 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2510 // trigger the tag index to be refreshed
2511 private void savedSearchIndexUpdated() {
2512 if (selectedSavedSearchGUID == null)
2513 selectedSavedSearchGUID = new String();
2514 savedSearchTree.blockSignals(true);
2515 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2516 savedSearchTree.load(listManager.getSavedSearchIndex());
2517 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2518 savedSearchTree.blockSignals(false);
2520 // trigger when the saved search selection changes
2521 @SuppressWarnings("unused")
2522 private void updateSavedSearchSelection() {
2523 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2525 menuBar.savedSearchEditAction.setEnabled(true);
2526 menuBar.savedSearchDeleteAction.setEnabled(true);
2527 menuBar.savedSearchIconAction.setEnabled(true);
2528 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2530 if (selections.size() > 0) {
2531 menuBar.savedSearchEditAction.setEnabled(true);
2532 menuBar.savedSearchDeleteAction.setEnabled(true);
2533 menuBar.savedSearchIconAction.setEnabled(true);
2534 selectedSavedSearchGUID = selections.get(0).text(1);
2535 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2536 searchField.setEditText(s.getQuery());
2538 menuBar.savedSearchEditAction.setEnabled(false);
2539 menuBar.savedSearchDeleteAction.setEnabled(false);
2540 menuBar.savedSearchIconAction.setEnabled(false);
2541 selectedSavedSearchGUID = "";
2542 searchField.setEditText("");
2544 searchFieldChanged();
2546 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2550 // Show/Hide note information
2551 @SuppressWarnings("unused")
2552 private void toggleSavedSearchWindow() {
2553 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2554 if (savedSearchTree.isVisible())
2555 savedSearchTree.hide();
2557 savedSearchTree.show();
2558 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2560 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2561 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2563 // Change the icon for a saved search
2564 @SuppressWarnings("unused")
2565 private void setSavedSearchIcon() {
2566 QTreeWidgetItem currentSelection;
2567 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2568 if (selections.size() == 0)
2571 currentSelection = selections.get(0);
2572 String guid = currentSelection.text(1);
2574 QIcon currentIcon = currentSelection.icon(0);
2575 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2578 dialog = new SetIcon(currentIcon, saveLastPath);
2579 dialog.setUseDefaultIcon(true);
2581 dialog = new SetIcon(icon, saveLastPath);
2582 dialog.setUseDefaultIcon(false);
2585 if (dialog.okPressed()) {
2586 saveLastPath = dialog.getPath();
2587 QIcon newIcon = dialog.getIcon();
2588 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2589 if (newIcon == null)
2590 newIcon = new QIcon(iconPath+"search.png");
2591 currentSelection.setIcon(0, newIcon);
2599 //***************************************************************
2600 //***************************************************************
2601 //** These functions deal with Help menu & tool menu items
2602 //***************************************************************
2603 //***************************************************************
2604 // Show database status
2605 @SuppressWarnings("unused")
2606 private void databaseStatus() {
2608 indexRunner.interrupt = true;
2609 int dirty = conn.getNoteTable().getDirtyCount();
2610 int unindexed = conn.getNoteTable().getUnindexedCount();
2611 DatabaseStatus status = new DatabaseStatus();
2612 status.setUnsynchronized(dirty);
2613 status.setUnindexed(unindexed);
2614 status.setNoteCount(conn.getNoteTable().getNoteCount());
2615 status.setNotebookCount(listManager.getNotebookIndex().size());
2616 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2617 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2618 status.setTagCount(listManager.getTagIndex().size());
2619 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2620 status.setWordCount(conn.getWordsTable().getWordCount());
2624 // Compact the database
2625 @SuppressWarnings("unused")
2626 private void compactDatabase() {
2627 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2628 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2629 "but please be aware that depending upon the size of your database this can be time consuming " +
2630 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2631 QMessageBox.StandardButton.Yes,
2632 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2635 setMessage("Compacting database.");
2637 listManager.compactDatabase();
2639 setMessage("Database compact is complete.");
2640 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2642 @SuppressWarnings("unused")
2643 private void accountInformation() {
2644 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2645 AccountDialog dialog = new AccountDialog();
2647 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2649 @SuppressWarnings("unused")
2650 private void releaseNotes() {
2651 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2652 QDialog dialog = new QDialog(this);
2653 QHBoxLayout layout = new QHBoxLayout();
2654 QTextEdit textBox = new QTextEdit();
2655 layout.addWidget(textBox);
2656 textBox.setReadOnly(true);
2657 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2658 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2659 QIODevice.OpenModeFlag.Text)))
2661 textBox.setText(file.readAll().toString());
2663 dialog.setWindowTitle(tr("Release Notes"));
2664 dialog.setLayout(layout);
2666 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2668 // Called when user picks Log from the help menu
2669 @SuppressWarnings("unused")
2670 private void logger() {
2671 logger.log(logger.HIGH, "Entering NeverNote.logger");
2672 LogFileDialog dialog = new LogFileDialog(emitLog);
2674 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2676 // Menu option "help/about" was selected
2677 @SuppressWarnings("unused")
2678 private void about() {
2679 logger.log(logger.HIGH, "Entering NeverNote.about");
2680 QMessageBox.about(this,
2681 tr("About NeverNote"),
2682 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2684 +tr("<hr></center>Evernote"
2685 +"An Open Source Evernote Client.<br><br>"
2686 +"Licensed under GPL v2. <br><hr><br>"
2687 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2688 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2689 +"PDFRenderer is licened under the LGPL<br>"
2690 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2691 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2692 +"Jazzy is licened under the LGPL<br>"
2693 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2694 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2695 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2696 logger.log(logger.HIGH, "Leaving NeverNote.about");
2698 // Hide the entire left hand side
2699 @SuppressWarnings("unused")
2700 private void toggleLeftSide() {
2703 hidden = !menuBar.hideLeftSide.isChecked();
2704 menuBar.hideLeftSide.setChecked(!hidden);
2707 leftSplitter1.setHidden(true);
2709 leftSplitter1.setHidden(false);
2711 Global.saveWindowVisible("leftPanel", hidden);
2714 public void checkForUpdates() {
2715 // Send off thread to check for a new version
2716 versionChecker = new QNetworkAccessManager(this);
2717 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2718 QNetworkRequest request = new QNetworkRequest();
2719 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2720 versionChecker.get(request);
2722 @SuppressWarnings("unused")
2723 private void upgradeFileRead(QNetworkReply reply) {
2724 if (!reply.isReadable())
2727 String winVersion = Global.version;
2728 String osxVersion = Global.version;
2729 String linuxVersion = Global.version;
2730 String linux64Version = Global.version;
2731 String version = Global.version;
2733 // Determine the versions available
2734 QByteArray data = reply.readLine();
2735 while (data != null && !reply.atEnd()) {
2736 String line = data.toString();
2738 if (line.contains(":"))
2739 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2742 if (line.toLowerCase().contains("windows"))
2743 winVersion = lineVersion;
2744 else if (line.toLowerCase().contains("os-x"))
2745 osxVersion = lineVersion;
2746 else if (line.toLowerCase().contains("linux amd64"))
2747 linux64Version = lineVersion;
2748 else if (line.toLowerCase().contains("linux i386"))
2749 linuxVersion = lineVersion;
2750 else if (line.toLowerCase().contains("default"))
2751 version = lineVersion;
2753 // Read the next line
2754 data = reply.readLine();
2757 // Now we need to determine what system we are on.
2758 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2759 version = winVersion;
2760 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2761 version = osxVersion;
2762 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2763 if (System.getProperty("os.arch").contains("amd64") ||
2764 System.getProperty("os.arch").contains("x86_64"))
2765 version = linux64Version;
2767 version = linuxVersion;
2771 for (String validVersion : Global.validVersions) {
2772 if (version.equals(validVersion))
2776 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2778 if (dialog.remindMe())
2779 Global.setCheckVersionUpgrade(true);
2781 Global.setCheckVersionUpgrade(false);
2785 //***************************************************************
2786 //***************************************************************
2787 //** These functions deal with the Toolbar
2788 //***************************************************************
2789 //***************************************************************
2790 @SuppressWarnings("unused")
2791 private void focusSearch() {
2792 searchField.setFocus();
2795 // Text in the search bar has been cleared
2796 private void searchFieldCleared() {
2799 // This is done because we want to force a reload of
2800 // images. Some images we may want to highlight the text.
2801 readOnlyCache.clear();
2802 inkNoteCache.clear();
2804 QWebSettings.setMaximumPagesInCache(0);
2805 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2807 searchField.setEditText("");
2808 saveNoteColumnPositions();
2809 saveNoteIndexWidth();
2810 noteIndexUpdated(true);
2811 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2812 currentNote = listManager.getNoteIndex().get(0);
2813 currentNoteGuid = currentNote.getGuid();
2815 refreshEvernoteNote(true);
2816 if (currentNote != null)
2817 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2819 // text in the search bar changed. We only use this to tell if it was cleared,
2820 // otherwise we trigger off searchFieldChanged.
2821 @SuppressWarnings("unused")
2822 private void searchFieldTextChanged(String text) {
2823 QWebSettings.setMaximumPagesInCache(0);
2824 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2826 if (text.trim().equals("")) {
2827 searchFieldCleared();
2828 if (searchPerformed) {
2830 // This is done because we want to force a reload of
2831 // images. Some images we may want to highlight the text.
2833 readOnlyCache.clear();
2834 inkNoteCache.clear();
2836 listManager.setEnSearch("");
2837 listManager.loadNotesIndex();
2838 refreshEvernoteNote(true);
2839 noteIndexUpdated(false);
2840 refreshEvernoteNote(true);
2842 searchPerformed = false;
2845 // Text in the toolbar has changed
2846 private void searchFieldChanged() {
2847 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2849 readOnlyCache.clear();
2850 inkNoteCache.clear();
2851 saveNoteColumnPositions();
2852 saveNoteIndexWidth();
2853 String text = searchField.currentText();
2854 listManager.setEnSearch(text.trim());
2855 listManager.loadNotesIndex();
2856 noteIndexUpdated(false);
2857 refreshEvernoteNote(true);
2858 searchPerformed = true;
2859 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2862 // Build the window tool bar
2863 private void setupToolBar() {
2864 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2865 toolBar = addToolBar(tr("Tool Bar"));
2866 toolBar.setObjectName("toolBar");
2867 menuBar.setupToolBarVisible();
2868 if (!Global.isWindowVisible("toolBar"))
2869 toolBar.setVisible(false);
2871 toolBar.setVisible(true);
2873 // toolBar.addWidget(menuBar);
2874 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2875 // toolBar.addSeparator();
2876 prevButton = toolBar.addAction(tr("Previous"));
2877 QIcon prevIcon = new QIcon(iconPath+"back.png");
2878 prevButton.setIcon(prevIcon);
2879 prevButton.triggered.connect(this, "previousViewedAction()");
2880 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2882 nextButton = toolBar.addAction(tr("Next"));
2883 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2884 nextButton.setIcon(nextIcon);
2885 nextButton.triggered.connect(this, "nextViewedAction()");
2886 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2888 upButton = toolBar.addAction(tr("Up"));
2889 QIcon upIcon = new QIcon(iconPath+"up.png");
2890 upButton.setIcon(upIcon);
2891 upButton.triggered.connect(this, "upAction()");
2892 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2895 downButton = toolBar.addAction(tr("Down"));
2896 QIcon downIcon = new QIcon(iconPath+"down.png");
2897 downButton.setIcon(downIcon);
2898 downButton.triggered.connect(this, "downAction()");
2899 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2901 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2902 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2903 synchronizeIconAngle = 0;
2904 synchronizeButton.triggered.connect(this, "evernoteSync()");
2905 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2907 printButton = toolBar.addAction(tr("Print"));
2908 QIcon printIcon = new QIcon(iconPath+"print.png");
2909 printButton.setIcon(printIcon);
2910 printButton.triggered.connect(this, "printNote()");
2911 togglePrintButton(Global.isToolbarButtonVisible("print"));
2913 tagButton = toolBar.addAction(tr("Tag"));
2914 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2915 tagButton.setIcon(tagIcon);
2916 tagButton.triggered.connect(browserWindow, "modifyTags()");
2917 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2919 attributeButton = toolBar.addAction(tr("Attributes"));
2920 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2921 attributeButton.setIcon(attributeIcon);
2922 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2923 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2925 emailButton = toolBar.addAction(tr("Email"));
2926 QIcon emailIcon = new QIcon(iconPath+"email.png");
2927 emailButton.setIcon(emailIcon);
2928 emailButton.triggered.connect(this, "emailNote()");
2929 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2931 deleteButton = toolBar.addAction(tr("Delete"));
2932 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2933 deleteButton.setIcon(deleteIcon);
2934 deleteButton.triggered.connect(this, "deleteNote()");
2935 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2937 newButton = toolBar.addAction(tr("New"));
2938 QIcon newIcon = new QIcon(iconPath+"new.png");
2939 newButton.triggered.connect(this, "addNote()");
2940 newButton.setIcon(newIcon);
2941 toggleNewButton(Global.isToolbarButtonVisible("new"));
2943 allNotesButton = toolBar.addAction(tr("All Notes"));
2944 QIcon allIcon = new QIcon(iconPath+"books.png");
2945 allNotesButton.triggered.connect(this, "allNotes()");
2946 allNotesButton.setIcon(allIcon);
2947 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2949 //toolBar.addSeparator();
2950 //toolBar.addWidget(new QLabel(tr("Quota:")));
2951 //toolBar.addWidget(quotaBar);
2952 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2954 //toolBar.addSeparator();
2956 //toolBar.addWidget(new QLabel(tr("Zoom")));
2957 //toolBar.addWidget(zoomSpinner);
2959 //toolBar.addWidget(new QLabel(" "));
2960 //toolBar.addSeparator();
2961 //toolBar.addWidget(new QLabel(tr(" Search:")));
2962 //toolBar.addWidget(searchField);
2963 QSizePolicy sizePolicy = new QSizePolicy();
2964 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2965 QLabel spacer = new QLabel("");
2966 spacer.setSizePolicy(sizePolicy);
2967 toolBar.addWidget(spacer);
2968 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2970 //searchClearButton = toolBar.addAction("Search Clear");
2971 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2972 //searchClearButton.setIcon(searchClearIcon);
2973 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2974 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2976 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2978 // Update the sychronize button picture
2980 public QMenu createPopupMenu() {
2981 QMenu contextMenu = super.createPopupMenu();
2983 contextMenu.addSeparator();
2984 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2985 contextMenu.addAction(prevAction);
2986 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2988 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2989 contextMenu.addAction(nextAction);
2990 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2992 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2993 contextMenu.addAction(upAction);
2994 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2996 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2997 contextMenu.addAction(downAction);
2998 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
3000 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
3001 contextMenu.addAction(synchronizeAction);
3002 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3004 QAction printAction = addContextAction("print", tr("Print"));
3005 contextMenu.addAction(printAction);
3006 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3008 QAction tagAction = addContextAction("tag", tr("Tag"));
3009 contextMenu.addAction(tagAction);
3010 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3012 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3013 contextMenu.addAction(attributeAction);
3014 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3016 QAction emailAction = addContextAction("email", tr("Email"));
3017 contextMenu.addAction(emailAction);
3018 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3020 QAction deleteAction = addContextAction("delete", tr("Delete"));
3021 contextMenu.addAction(deleteAction);
3022 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3024 QAction newAction = addContextAction("new", tr("Add"));
3025 contextMenu.addAction(newAction);
3026 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3028 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3029 contextMenu.addAction(allNotesAction);
3030 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3032 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3033 contextMenu.addAction(searchClearAction);
3034 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3039 private QAction addContextAction(String config, String name) {
3040 QAction newAction = new QAction(this);
3041 newAction.setText(name);
3042 newAction.setCheckable(true);
3043 newAction.setChecked(Global.isToolbarButtonVisible(config));
3046 private void togglePrevArrowButton(Boolean toggle) {
3047 prevButton.setVisible(toggle);
3048 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3050 private void toggleNextArrowButton(Boolean toggle) {
3051 nextButton.setVisible(toggle);
3052 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3054 private void toggleUpArrowButton(Boolean toggle) {
3055 upButton.setVisible(toggle);
3056 Global.saveToolbarButtonsVisible("upArrow", toggle);
3058 private void toggleDownArrowButton(Boolean toggle) {
3059 downButton.setVisible(toggle);
3060 Global.saveToolbarButtonsVisible("downArrow", toggle);
3062 private void toggleSynchronizeButton(Boolean toggle) {
3063 synchronizeButton.setVisible(toggle);
3064 Global.saveToolbarButtonsVisible("synchronize", toggle);
3066 private void togglePrintButton(Boolean toggle) {
3067 printButton.setVisible(toggle);
3068 Global.saveToolbarButtonsVisible("print", toggle);
3070 private void toggleTagButton(Boolean toggle) {
3071 tagButton.setVisible(toggle);
3072 Global.saveToolbarButtonsVisible("tag", toggle);
3074 private void toggleAttributeButton(Boolean toggle) {
3075 attributeButton.setVisible(toggle);
3076 Global.saveToolbarButtonsVisible("attribute", toggle);
3078 private void toggleEmailButton(Boolean toggle) {
3079 emailButton.setVisible(toggle);
3080 Global.saveToolbarButtonsVisible("email", toggle);
3082 private void toggleDeleteButton(Boolean toggle) {
3083 deleteButton.setVisible(toggle);
3084 Global.saveToolbarButtonsVisible("delete", toggle);
3086 private void toggleNewButton(Boolean toggle) {
3087 newButton.setVisible(toggle);
3088 Global.saveToolbarButtonsVisible("new", toggle);
3090 private void toggleAllNotesButton(Boolean toggle) {
3091 allNotesButton.setVisible(toggle);
3092 Global.saveToolbarButtonsVisible("allNotes", toggle);
3094 @SuppressWarnings("unused")
3095 private void toggleSearchClearButton(Boolean toggle) {
3096 searchClearButton.setVisible(toggle);
3097 Global.saveToolbarButtonsVisible("searchClear", toggle);
3104 @SuppressWarnings("unused")
3105 private void updateSyncButton() {
3107 if (syncIcons == null) {
3108 syncIcons = new ArrayList<QPixmap>();
3110 synchronizeIconAngle = 0;
3111 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3113 for (int i=0; i<=360; i++) {
3114 QPixmap rotatedPix = new QPixmap(pix.size());
3115 QPainter p = new QPainter(rotatedPix);
3116 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3117 QSize size = pix.size();
3118 p.translate(size.width()/2, size.height()/2);
3121 p.setBackgroundMode(BGMode.OpaqueMode);
3122 p.translate(-size.width()/2, -size.height()/2);
3123 p.drawPixmap(0,0, pix);
3125 syncIcons.add(rotatedPix);
3129 synchronizeIconAngle++;
3130 if (synchronizeIconAngle > 359)
3131 synchronizeIconAngle=0;
3132 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3135 // Synchronize with Evernote
3137 private void evernoteSync() {
3138 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3139 if (!Global.isConnected)
3141 if (Global.isConnected)
3142 synchronizeAnimationTimer.start(5);
3143 // synchronizeAnimationTimer.start(200);
3145 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3147 private void updateQuotaBar() {
3148 long limit = Global.getUploadLimit();
3149 long amount = Global.getUploadAmount();
3150 if (amount>0 && limit>0) {
3151 int percent =(int)(amount*100/limit);
3152 quotaBar.setValue(percent);
3154 quotaBar.setValue(0);
3157 @SuppressWarnings("unused")
3158 private void zoomChanged() {
3159 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3162 //****************************************************************
3163 //****************************************************************
3164 //* System Tray functions
3165 //****************************************************************
3166 //****************************************************************
3167 private void trayToggleVisible() {
3172 if (windowMaximized)
3179 @SuppressWarnings("unused")
3180 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3181 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3182 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3183 trayToggleVisible();
3188 //***************************************************************
3189 //***************************************************************
3190 //** These functions deal with the trash tree
3191 //***************************************************************
3192 //***************************************************************
3193 // Setup the tree containing the trash.
3194 @SuppressWarnings("unused")
3195 private void trashTreeSelection() {
3196 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3198 clearNotebookFilter();
3200 clearAttributeFilter();
3201 clearSavedSearchFilter();
3203 String tempGuid = currentNoteGuid;
3205 // currentNoteGuid = "";
3206 currentNote = new Note();
3207 selectedNoteGUIDs.clear();
3208 listManager.getSelectedNotebooks().clear();
3209 listManager.getSelectedTags().clear();
3210 listManager.setSelectedSavedSearch("");
3211 browserWindow.clear();
3213 // toggle the add buttons
3214 newButton.setEnabled(!newButton.isEnabled());
3215 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3216 menuBar.noteAdd.setVisible(true);
3218 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3219 if (selections.size() == 0) {
3220 currentNoteGuid = trashNoteGuid;
3221 trashNoteGuid = tempGuid;
3222 Global.showDeleted = false;
3223 menuBar.noteRestoreAction.setEnabled(false);
3224 menuBar.noteRestoreAction.setVisible(false);
3227 currentNoteGuid = trashNoteGuid;
3228 trashNoteGuid = tempGuid;
3229 menuBar.noteRestoreAction.setEnabled(true);
3230 menuBar.noteRestoreAction.setVisible(true);
3231 Global.showDeleted = true;
3233 listManager.loadNotesIndex();
3234 noteIndexUpdated(false);
3235 //// browserWindow.setEnabled(newButton.isEnabled());
3236 browserWindow.setReadOnly(!newButton.isEnabled());
3237 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3239 // Empty the trash file
3240 @SuppressWarnings("unused")
3241 private void emptyTrash() {
3242 // browserWindow.clear();
3243 logger.log(logger.EXTREME, "Emptying Trash");
3244 listManager.emptyTrash();
3245 logger.log(logger.EXTREME, "Resetting view after trash empty");
3246 if (trashTree.selectedItems().size() > 0) {
3247 listManager.getSelectedNotebooks().clear();
3248 listManager.getSelectedTags().clear();
3249 listManager.setSelectedSavedSearch("");
3250 newButton.setEnabled(!newButton.isEnabled());
3251 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3252 menuBar.noteAdd.setVisible(true);
3253 browserWindow.clear();
3256 clearNotebookFilter();
3257 clearSavedSearchFilter();
3258 clearAttributeFilter();
3260 Global.showDeleted = false;
3261 menuBar.noteRestoreAction.setEnabled(false);
3262 menuBar.noteRestoreAction.setVisible(false);
3264 listManager.loadNotesIndex();
3265 noteIndexUpdated(false);
3268 // Show/Hide trash window
3269 @SuppressWarnings("unused")
3270 private void toggleTrashWindow() {
3271 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3272 if (trashTree.isVisible())
3276 menuBar.hideTrash.setChecked(trashTree.isVisible());
3278 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3279 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3281 private void clearTrashFilter() {
3282 Global.showDeleted = false;
3283 newButton.setEnabled(true);
3284 menuBar.noteAdd.setEnabled(true);
3285 menuBar.noteAdd.setVisible(true);
3286 trashTree.blockSignals(true);
3287 trashTree.clearSelection();
3288 trashTree.blockSignals(false);
3293 //***************************************************************
3294 //***************************************************************
3295 //** These functions deal with connection settings
3296 //***************************************************************
3297 //***************************************************************
3298 // SyncRunner had a problem and things are disconnected
3299 @SuppressWarnings("unused")
3300 private void remoteErrorDisconnect() {
3301 menuBar.connectAction.setText(tr("Connect"));
3302 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3303 menuBar.synchronizeAction.setEnabled(false);
3304 Global.isConnected = false;
3305 synchronizeAnimationTimer.stop();
3308 // Do a manual connect/disconnect
3309 private void remoteConnect() {
3310 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3312 if (Global.isConnected) {
3313 Global.isConnected = false;
3314 syncRunner.enDisconnect();
3315 setupConnectMenuOptions();
3320 AESEncrypter aes = new AESEncrypter();
3322 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3323 } catch (FileNotFoundException e) {
3324 // File not found, so we'll just get empty strings anyway.
3327 if (Global.getProxyValue("url").equals("")) {
3328 System.setProperty("http.proxyHost","") ;
3329 System.setProperty("http.proxyPort", "") ;
3330 System.setProperty("https.proxyHost","") ;
3331 System.setProperty("https.proxyPort", "") ;
3334 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3335 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3336 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3337 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3339 if (Global.getProxyValue("userid").equals("")) {
3340 Authenticator.setDefault(new Authenticator() {
3342 protected PasswordAuthentication getPasswordAuthentication() {
3344 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3350 syncRunner.userStoreUrl = Global.userStoreUrl;
3351 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3352 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3354 String userid = aes.getUserid();
3355 String password = aes.getPassword();
3356 if (!userid.equals("") && !password.equals("")) {
3357 Global.username = userid;
3358 Global.password = password;
3359 syncRunner.username = Global.username;
3360 syncRunner.password = Global.password;
3361 syncRunner.enConnect();
3364 Global.isConnected = syncRunner.isConnected;
3366 if (!Global.isConnected) {
3367 // Show the login dialog box
3368 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3369 LoginDialog login = new LoginDialog();
3372 if (!login.okPressed()) {
3376 Global.username = login.getUserid();
3377 Global.password = login.getPassword();
3379 syncRunner.username = Global.username;
3380 syncRunner.password = Global.password;
3381 syncRunner.enConnect();
3382 Global.isConnected = syncRunner.isConnected;
3385 if (!Global.isConnected)
3388 setupConnectMenuOptions();
3389 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3391 private void setupConnectMenuOptions() {
3392 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3393 if (!Global.isConnected) {
3394 menuBar.connectAction.setText(tr("Connect"));
3395 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3396 menuBar.synchronizeAction.setEnabled(false);
3398 menuBar.connectAction.setText(tr("Disconnect"));
3399 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3400 menuBar.synchronizeAction.setEnabled(true);
3402 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3407 //***************************************************************
3408 //***************************************************************
3409 //** These functions deal with the GUI Attribute tree
3410 //***************************************************************
3411 //***************************************************************
3412 @SuppressWarnings("unused")
3413 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3415 // clearTagFilter();
3416 // clearNotebookFilter();
3418 // clearSavedSearchFilter();
3420 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3421 if (item.childCount() > 0) {
3422 item.setSelected(false);
3424 Global.createdBeforeFilter.reset();
3425 Global.createdSinceFilter.reset();
3426 Global.changedBeforeFilter.reset();
3427 Global.changedSinceFilter.reset();
3428 Global.containsFilter.reset();
3429 attributeTreeSelected = item;
3430 DateAttributeFilterTable f = null;
3431 f = findDateAttributeFilterTable(item.parent());
3433 f.select(item.parent().indexOfChild(item));
3435 Global.containsFilter.select(item.parent().indexOfChild(item));
3438 listManager.loadNotesIndex();
3439 noteIndexUpdated(false);
3442 attributeTreeSelected = null;
3443 item.setSelected(false);
3444 Global.createdBeforeFilter.reset();
3445 Global.createdSinceFilter.reset();
3446 Global.changedBeforeFilter.reset();
3447 Global.changedSinceFilter.reset();
3448 Global.containsFilter.reset();
3449 listManager.loadNotesIndex();
3450 noteIndexUpdated(false);
3452 // This determines what attribute filter we need, depending upon the selection
3453 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3454 if (w.parent() != null && w.childCount() > 0) {
3455 QTreeWidgetItem parent = w.parent();
3456 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3457 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3458 return Global.createdSinceFilter;
3459 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3460 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3461 return Global.createdBeforeFilter;
3462 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3463 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3464 return Global.changedSinceFilter;
3465 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3466 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3467 return Global.changedBeforeFilter;
3472 // Show/Hide attribute search window
3473 @SuppressWarnings("unused")
3474 private void toggleAttributesWindow() {
3475 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3476 if (attributeTree.isVisible())
3477 attributeTree.hide();
3479 attributeTree.show();
3480 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3482 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3483 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3485 private void clearAttributeFilter() {
3486 Global.createdBeforeFilter.reset();
3487 Global.createdSinceFilter.reset();
3488 Global.changedBeforeFilter.reset();
3489 Global.changedSinceFilter.reset();
3490 Global.containsFilter.reset();
3491 attributeTreeSelected = null;
3492 attributeTree.blockSignals(true);
3493 attributeTree.clearSelection();
3494 attributeTree.blockSignals(false);
3498 //***************************************************************
3499 //***************************************************************
3500 //** These functions deal with the GUI Note index table
3501 //***************************************************************
3502 //***************************************************************
3503 // Initialize the note list table
3504 private void initializeNoteTable() {
3505 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3506 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3507 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3508 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3510 // Show/Hide trash window
3511 @SuppressWarnings("unused")
3512 private void toggleNoteListWindow() {
3513 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3514 if (noteTableView.isVisible())
3515 noteTableView.hide();
3517 noteTableView.show();
3518 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3520 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3521 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3523 // Handle the event that a user selects a note from the table
3524 @SuppressWarnings("unused")
3525 private void noteTableSelection() {
3526 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3530 // If the ctrl key is pressed, then they are selecting multiple
3531 // entries and we don't want to change the currently viewed note.
3532 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3533 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3536 if (historyGuids.size() == 0) {
3537 historyGuids.add(currentNoteGuid);
3538 historyPosition = 1;
3540 noteTableView.showColumn(Global.noteTableGuidPosition);
3542 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3543 if (!Global.isColumnVisible("guid"))
3544 noteTableView.hideColumn(Global.noteTableGuidPosition);
3546 if (selections.size() > 0) {
3548 menuBar.noteDuplicateAction.setEnabled(true);
3549 menuBar.noteOnlineHistoryAction.setEnabled(true);
3550 menuBar.noteMergeAction.setEnabled(true);
3551 selectedNoteGUIDs.clear();
3552 if (selections.size() != 1 || Global.showDeleted) {
3553 menuBar.noteDuplicateAction.setEnabled(false);
3555 if (selections.size() != 1 || !Global.isConnected) {
3556 menuBar.noteOnlineHistoryAction.setEnabled(false);
3558 if (selections.size() == 1) {
3559 menuBar.noteMergeAction.setEnabled(false);
3561 for (int i=0; i<selections.size(); i++) {
3562 int row = selections.get(i).row();
3564 upButton.setEnabled(false);
3566 upButton.setEnabled(true);
3567 if (row < listManager.getNoteTableModel().rowCount()-1)
3568 downButton.setEnabled(true);
3570 downButton.setEnabled(false);
3571 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3572 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3573 currentNoteGuid = (String)ix.values().toArray()[0];
3574 selectedNoteGUIDs.add(currentNoteGuid);
3578 nextButton.setEnabled(true);
3579 prevButton.setEnabled(true);
3581 int endPosition = historyGuids.size()-1;
3582 for (int j=historyPosition; j<=endPosition; j++) {
3583 historyGuids.remove(historyGuids.size()-1);
3585 historyGuids.add(currentNoteGuid);
3586 historyPosition = historyGuids.size();
3588 if (historyPosition <= 1)
3589 prevButton.setEnabled(false);
3590 if (historyPosition == historyGuids.size())
3591 nextButton.setEnabled(false);
3593 fromHistory = false;
3594 scrollToGuid(currentNoteGuid);
3595 refreshEvernoteNote(true);
3596 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3598 // Trigger a refresh when the note db has been updated
3599 private void noteIndexUpdated(boolean reload) {
3600 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3602 refreshEvernoteNoteList();
3603 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3604 noteTableView.load(reload);
3605 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3607 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3608 pos = noteTableView.proxyModel.rowCount();
3611 if (noteTableView.proxyModel.rowCount() == 0)
3614 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3616 currentNoteGuid = (String)i.data();
3620 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3622 scrollToGuid(currentNoteGuid);
3623 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3625 // Called when the list of notes is updated
3626 private void refreshEvernoteNoteList() {
3627 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3628 browserWindow.setDisabled(false);
3629 if (selectedNoteGUIDs == null)
3630 selectedNoteGUIDs = new ArrayList<String>();
3631 selectedNoteGUIDs.clear(); // clear out old entries
3633 String saveCurrentNoteGuid = new String();
3634 String tempNoteGuid = new String();
3636 historyGuids.clear();
3637 historyPosition = 0;
3638 prevButton.setEnabled(false);
3639 nextButton.setEnabled(false);
3641 if (currentNoteGuid == null)
3642 currentNoteGuid = new String();
3644 //determine current note guid
3645 for (Note note : listManager.getNoteIndex()) {
3646 tempNoteGuid = note.getGuid();
3647 if (currentNoteGuid.equals(tempNoteGuid)) {
3648 saveCurrentNoteGuid = tempNoteGuid;
3652 if (listManager.getNoteIndex().size() == 0) {
3653 currentNoteGuid = "";
3655 browserWindow.clear();
3656 browserWindow.setDisabled(true);
3659 if (!saveCurrentNoteGuid.equals("")) {
3660 refreshEvernoteNote(false);
3662 currentNoteGuid = "";
3664 reloadTagTree(false);
3666 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3668 // Called when the previous arrow button is clicked
3669 @SuppressWarnings("unused")
3670 private void previousViewedAction() {
3671 if (!prevButton.isEnabled())
3673 if (historyPosition == 0)
3676 if (historyPosition <= 0)
3678 String historyGuid = historyGuids.get(historyPosition-1);
3680 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3681 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3682 if (modelIndex != null) {
3683 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3684 String tableGuid = (String)ix.values().toArray()[0];
3685 if (tableGuid.equals(historyGuid)) {
3686 noteTableView.selectRow(i);
3692 @SuppressWarnings("unused")
3693 private void nextViewedAction() {
3694 if (!nextButton.isEnabled())
3696 String historyGuid = historyGuids.get(historyPosition);
3699 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3700 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3701 if (modelIndex != null) {
3702 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3703 String tableGuid = (String)ix.values().toArray()[0];
3704 if (tableGuid.equals(historyGuid)) {
3705 noteTableView.selectRow(i);
3711 // Called when the up arrow is clicked
3712 @SuppressWarnings("unused")
3713 private void upAction() {
3714 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3715 int row = selections.get(0).row();
3717 noteTableView.selectRow(row-1);
3720 // Called when the down arrow is clicked
3721 @SuppressWarnings("unused")
3722 private void downAction() {
3723 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3724 int row = selections.get(0).row();
3725 int max = listManager.getNoteTableModel().rowCount();
3727 noteTableView.selectRow(row+1);
3730 // Update a tag string for a specific note in the list
3731 @SuppressWarnings("unused")
3732 private void updateListTags(String guid, List<String> tags) {
3733 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3734 StringBuffer tagBuffer = new StringBuffer();
3735 for (int i=0; i<tags.size(); i++) {
3736 tagBuffer.append(tags.get(i));
3737 if (i<tags.size()-1)
3738 tagBuffer.append(", ");
3741 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3742 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3743 if (modelIndex != null) {
3744 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3745 String tableGuid = (String)ix.values().toArray()[0];
3746 if (tableGuid.equals(guid)) {
3747 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3748 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3749 noteTableView.proxyModel.invalidate();
3754 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3756 // Update a title for a specific note in the list
3757 @SuppressWarnings("unused")
3758 private void updateListAuthor(String guid, String author) {
3759 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3761 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3762 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3763 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3764 if (modelIndex != null) {
3765 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3766 String tableGuid = (String)ix.values().toArray()[0];
3767 if (tableGuid.equals(guid)) {
3768 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3769 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3770 noteTableView.proxyModel.invalidate();
3776 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3778 private void updateListNoteNotebook(String guid, String notebook) {
3779 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3780 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3781 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3783 // Update a title for a specific note in the list
3784 @SuppressWarnings("unused")
3785 private void updateListSourceUrl(String guid, String url) {
3786 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3788 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3789 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3790 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3791 if (modelIndex != null) {
3792 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3793 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3794 String tableGuid = (String)ix.values().toArray()[0];
3795 if (tableGuid.equals(guid)) {
3796 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3797 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3798 noteTableView.proxyModel.invalidate();
3803 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3805 @SuppressWarnings("unused")
3806 private void updateListGuid(String oldGuid, String newGuid) {
3807 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3809 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3810 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3811 if (modelIndex != null) {
3812 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3813 String tableGuid = (String)ix.values().toArray()[0];
3814 if (tableGuid.equals(oldGuid)) {
3815 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3816 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3821 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3823 private void updateListTagName(String guid) {
3824 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3826 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3827 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3828 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3830 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3831 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3832 if (modelIndex != null) {
3833 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3834 String noteGuid = (String)ix.values().toArray()[0];
3835 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3836 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3837 i=listManager.getNoteTableModel().rowCount();
3843 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3845 private void removeListTagName(String guid) {
3846 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3848 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3849 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3850 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3851 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3852 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3855 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3856 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3857 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3858 if (modelIndex != null) {
3859 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3860 String noteGuid = (String)ix.values().toArray()[0];
3861 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3862 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3863 i=listManager.getNoteTableModel().rowCount();
3869 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3871 private void updateListNotebookName(String oldName, String newName) {
3872 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3874 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3875 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3876 if (modelIndex != null) {
3877 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3878 String tableName = (String)ix.values().toArray()[0];
3879 if (tableName.equalsIgnoreCase(oldName)) {
3880 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3884 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3886 @SuppressWarnings("unused")
3887 private void updateListDateCreated(String guid, QDateTime date) {
3888 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3890 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3891 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3892 if (modelIndex != null) {
3893 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3894 String tableGuid = (String)ix.values().toArray()[0];
3895 if (tableGuid.equals(guid)) {
3896 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3897 noteTableView.proxyModel.invalidate();
3902 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3904 @SuppressWarnings("unused")
3905 private void updateListDateSubject(String guid, QDateTime date) {
3906 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3908 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3909 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3910 if (modelIndex != null) {
3911 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3912 String tableGuid = (String)ix.values().toArray()[0];
3913 if (tableGuid.equals(guid)) {
3914 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3915 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3916 noteTableView.proxyModel.invalidate();
3921 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3923 private void updateListDateChanged(String guid, QDateTime date) {
3924 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3926 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3927 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3928 if (modelIndex != null) {
3929 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3930 String tableGuid = (String)ix.values().toArray()[0];
3931 if (tableGuid.equals(guid)) {
3932 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3933 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3938 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3940 private void updateListDateChanged() {
3941 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3942 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3943 updateListDateChanged(currentNoteGuid, date);
3944 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3947 private void scrollToCurrentGuid() {
3948 //scrollToGuid(currentNoteGuid);
3949 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3950 if (selections.size() == 0)
3952 QModelIndex index = selections.get(0);
3953 int row = selections.get(0).row();
3954 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3957 // Scroll to the current GUID in tthe list.
3958 // Scroll to a particular index item
3959 private void scrollToGuid(String guid) {
3960 if (currentNote == null || guid == null)
3962 if (currentNote.isActive() && Global.showDeleted) {
3963 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3964 if (!listManager.getNoteIndex().get(i).isActive()) {
3965 currentNote = listManager.getNoteIndex().get(i);
3966 currentNoteGuid = currentNote.getGuid();
3967 i = listManager.getNoteIndex().size();
3971 if (!currentNote.isActive() && !Global.showDeleted) {
3972 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3973 if (listManager.getNoteIndex().get(i).isActive()) {
3974 currentNote = listManager.getNoteIndex().get(i);
3975 currentNoteGuid = currentNote.getGuid();
3976 i = listManager.getNoteIndex().size();
3981 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3982 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3983 if (currentNoteGuid.equals(index.data())) {
3984 // noteTableView.selectionModel().blockSignals(true);
3985 noteTableView.selectRow(i);
3986 // noteTableView.selectionModel().blockSignals(false);
3987 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3988 i=listManager.getNoteTableModel().rowCount();
3991 noteTableView.repaint();
3993 // Show/Hide columns
3994 private void showColumns() {
3995 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3996 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3997 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3998 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3999 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
4000 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
4001 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4002 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4003 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4004 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4005 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4007 // Title color has changed
4008 @SuppressWarnings("unused")
4009 private void titleColorChanged(Integer color) {
4010 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
4012 QColor backgroundColor = new QColor();
4013 QColor foregroundColor = new QColor(QColor.black);
4014 backgroundColor.setRgb(color);
4016 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4017 foregroundColor.setRgb(QColor.white.rgb());
4019 if (selectedNoteGUIDs.size() == 0)
4020 selectedNoteGUIDs.add(currentNoteGuid);
4022 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4023 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4024 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4025 if (modelIndex != null) {
4026 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4027 String tableGuid = (String)ix.values().toArray()[0];
4028 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4029 for (int k=0; k<Global.noteTableColumnCount; k++) {
4030 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4031 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4032 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4034 i=listManager.getNoteTableModel().rowCount();
4039 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
4041 // Wide list was chosen
4042 public void narrowListView() {
4043 saveNoteColumnPositions();
4044 saveNoteIndexWidth();
4046 int sortCol = noteTableView.proxyModel.sortColumn();
4047 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4048 Global.setSortColumn(sortCol);
4049 Global.setSortOrder(sortOrder);
4051 Global.setListView(Global.View_List_Narrow);
4053 menuBar.wideListView.blockSignals(true);
4054 menuBar.narrowListView.blockSignals(true);
4056 menuBar.wideListView.setChecked(false);
4057 menuBar.narrowListView.setChecked(true);
4059 menuBar.wideListView.blockSignals(false);
4060 menuBar.narrowListView.blockSignals(false);
4062 mainLeftRightSplitter.addWidget(noteTableView);
4063 mainLeftRightSplitter.addWidget(browserWindow);
4064 restoreWindowState(false);
4065 noteTableView.repositionColumns();
4066 noteTableView.resizeColumnWidths();
4067 noteTableView.resizeRowHeights();
4069 sortCol = Global.getSortColumn();
4070 sortOrder = Global.getSortOrder();
4071 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4074 noteTableView.load(false);
4075 refreshEvernoteNote(true);
4076 scrollToCurrentGuid();
4078 public void wideListView() {
4079 int sortCol = noteTableView.proxyModel.sortColumn();
4080 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4081 Global.setSortColumn(sortCol);
4082 Global.setSortOrder(sortOrder);
4085 saveNoteColumnPositions();
4086 saveNoteIndexWidth();
4087 Global.setListView(Global.View_List_Wide);
4089 menuBar.wideListView.blockSignals(true);
4090 menuBar.narrowListView.blockSignals(true);
4092 menuBar.wideListView.setChecked(true);
4093 menuBar.narrowListView.setChecked(false);
4095 menuBar.wideListView.blockSignals(false);
4096 menuBar.narrowListView.blockSignals(false);
4097 browserIndexSplitter.setVisible(true);
4098 browserIndexSplitter.addWidget(noteTableView);
4099 browserIndexSplitter.addWidget(browserWindow);
4100 restoreWindowState(false);
4101 noteTableView.repositionColumns();
4102 noteTableView.resizeColumnWidths();
4103 noteTableView.resizeRowHeights();
4105 sortCol = Global.getSortColumn();
4106 sortOrder = Global.getSortOrder();
4107 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4110 noteTableView.load(false);
4111 scrollToCurrentGuid();
4115 //***************************************************************
4116 @SuppressWarnings("unused")
4117 private void evernoteLinkClick(String syncGuid, String locGuid) {
4119 if (conn.getNoteTable().guidExists(syncGuid)) {
4122 // If we didn't find it via the synchronized guid, look under the local guid
4123 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4124 // later synchronized (that causes the guid to change so we need to find the new one).
4125 if (conn.getNoteTable().guidExists(locGuid))
4128 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4131 openExternalEditor(guid);
4135 //If we've gotten this far, we can't find the note
4136 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4137 " seem to find that note."));
4139 //***************************************************************
4140 //***************************************************************
4141 //** External editor window functions
4142 //***************************************************************
4143 //***************************************************************
4144 private void listDoubleClick() {
4146 openExternalEditor(currentNoteGuid);
4148 private void openExternalEditor(String guid) {
4150 if (externalWindows.containsKey(guid)) {
4151 externalWindows.get(guid).raise();
4154 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4155 // We have a new external editor to create
4156 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4157 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4158 newBrowser.setWindowIcon(appIcon);
4159 externalWindows.put(guid, newBrowser);
4160 showEditorButtons(newBrowser.getBrowserWindow());
4161 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4162 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4163 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4164 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4165 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4166 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4167 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4168 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4170 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4171 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4172 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4176 @SuppressWarnings("unused")
4177 private void externalWindowTitleEdited(String guid, String text) {
4178 if (guid.equals(currentNoteGuid)) {
4179 browserWindow.setTitle(text);
4182 @SuppressWarnings({ "rawtypes", "unused" })
4183 private void externalWindowTagsEdited(String guid, List values) {
4184 StringBuffer line = new StringBuffer(100);
4185 for (int i=0; i<values.size(); i++) {
4187 line.append(Global.tagDelimeter+" ");
4188 line.append(values.get(i));
4190 if (guid.equals(currentNoteGuid)) {
4191 browserWindow.setTag(line.toString());
4194 @SuppressWarnings("unused")
4195 private void externalWindowClosing(String guid) {
4196 externalWindows.remove(guid);
4201 //***************************************************************
4202 //***************************************************************
4203 //** These functions deal with Note specific things
4204 //***************************************************************
4205 //***************************************************************
4206 @SuppressWarnings("unused")
4207 private void setNoteDirty() {
4208 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4210 // Find if the note is being edited externally. If it is, update it.
4211 if (externalWindows.containsKey(currentNoteGuid)) {
4212 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4213 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4214 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4215 window.getBrowserWindow().setContent(unicode);
4218 // If the note is dirty, then it is unsynchronized by default.
4222 // Set the note as dirty and check if its status is synchronized in the display table
4224 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4225 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4229 // If this wasn't already marked as unsynchronized, then we need to update the table
4230 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4231 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4232 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4233 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4234 if (modelIndex != null) {
4235 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4236 String tableGuid = (String)ix.values().toArray()[0];
4237 if (tableGuid.equals(currentNoteGuid)) {
4238 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4244 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4246 @SuppressWarnings("unused")
4247 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4248 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4249 QByteArray unicode = codec.fromUnicode(content);
4250 noteCache.remove(guid);
4251 noteCache.put(guid, unicode.toString());
4252 if (guid.equals(currentNoteGuid)) {
4254 browserWindow.setContent(unicode);
4257 thumbnailRunner.addWork("GENERATE "+ guid);
4258 saveNote(guid, browser);
4262 private void saveNote() {
4264 saveNote(currentNoteGuid, browserWindow);
4265 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4269 private void saveNote(String guid, BrowserWindow window) {
4270 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4273 logger.log(logger.EXTREME, "Saving to cache");
4274 QTextCodec codec = QTextCodec.codecForLocale();
4275 // QTextDecoder decoder = codec.makeDecoder();
4276 codec = QTextCodec.codecForName("UTF-8");
4277 QByteArray unicode = codec.fromUnicode(window.getContent());
4278 noteCache.put(guid, unicode.toString());
4280 logger.log(logger.EXTREME, "updating list manager");
4281 listManager.updateNoteContent(guid, window.getContent());
4282 logger.log(logger.EXTREME, "Updating title");
4283 listManager.updateNoteTitle(guid, window.getTitle());
4284 updateListDateChanged();
4286 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4287 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4288 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4289 currentNote = listManager.getNoteIndex().get(i);
4290 i = listManager.getNoteIndex().size();
4295 // Get a note from Evernote (and put it in the browser)
4296 private void refreshEvernoteNote(boolean reload) {
4297 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4299 if (Global.disableViewing) {
4300 browserWindow.setEnabled(false);
4305 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4307 Global.cryptCounter =0;
4309 browserWindow.setReadOnly(true);
4317 browserWindow.loadingData(true);
4319 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4320 if (currentNote == null)
4322 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4325 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4326 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4327 formatter.setNote(note, Global.pdfPreview());
4328 formatter.setHighlight(listManager.getEnSearch());
4330 if (!noteCache.containsKey(guid)) {
4331 js = new QByteArray();
4332 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4333 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4334 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>");
4335 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4336 js.append("<style> img { max-width:100%; }</style>");
4337 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4338 js.append("</head>");
4339 formatter.setNote(note, Global.pdfPreview());
4340 js.append(formatter.rebuildNoteHTML());
4341 js.append("</HTML>");
4342 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4343 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4344 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4345 // if (Global.enableHTMLEntitiesFix) {
4346 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4348 browser.setContent(js);
4349 noteCache.put(guid, js.toString());
4351 if (formatter.resourceError)
4352 resourceErrorMessage();
4353 if (formatter.formatError) {
4355 QMessageBox.information(this, tr("Error"),
4356 tr("NeverNote had issues formatting this note." +
4357 " To protect your data this note is being marked as read-only."));
4360 readOnly = formatter.readOnly;
4361 inkNote = formatter.inkNote;
4363 readOnlyCache.put(guid, true);
4365 inkNoteCache.put(guid, true);
4367 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4368 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4369 js = new QByteArray(cachedContent);
4370 browser.setContent(js);
4371 if (readOnlyCache.containsKey(guid))
4373 if (inkNoteCache.containsKey(guid))
4376 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4377 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4379 if (readOnly || inkNote)
4380 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4382 browser.getBrowser().page().setContentEditable(true);
4383 browser.setReadOnly(readOnly);
4384 deleteButton.setEnabled(!readOnly);
4385 tagButton.setEnabled(!readOnly);
4386 menuBar.noteDelete.setEnabled(!readOnly);
4387 menuBar.noteTags.setEnabled(!readOnly);
4388 browser.setNote(note);
4390 if (note != null && note.getNotebookGuid() != null &&
4391 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4392 deleteButton.setEnabled(false);
4393 menuBar.notebookDeleteAction.setEnabled(false);
4395 deleteButton.setEnabled(true);
4396 menuBar.notebookDeleteAction.setEnabled(true);
4399 // Build a list of non-closed notebooks
4400 List<Notebook> nbooks = new ArrayList<Notebook>();
4401 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4402 boolean found=false;
4403 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4404 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4408 nbooks.add(listManager.getNotebookIndex().get(i));
4411 browser.setTitle(note.getTitle());
4412 browser.setTag(getTagNamesForNote(note));
4413 browser.setAuthor(note.getAttributes().getAuthor());
4415 browser.setAltered(note.getUpdated());
4416 browser.setCreation(note.getCreated());
4417 if (note.getAttributes().getSubjectDate() > 0)
4418 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4420 browser.setSubjectDate(note.getCreated());
4421 browser.setUrl(note.getAttributes().getSourceURL());
4423 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4424 List<Tag> tagList = tagFilter.getValidTags(note);
4425 browser.setAllTags(tagList);
4427 browser.setCurrentTags(note.getTagNames());
4431 browser.loadingData(false);
4432 if (thumbnailViewer.isActiveWindow())
4435 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4436 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4439 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4441 // Save a generated thumbnail
4442 private void toggleNoteInformation() {
4443 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4444 browserWindow.toggleInformation();
4445 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4446 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4447 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4449 // Listener triggered when a print button is pressed
4450 @SuppressWarnings("unused")
4451 private void printNote() {
4452 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4454 QPrintDialog dialog = new QPrintDialog();
4455 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4456 QPrinter printer = dialog.printer();
4457 browserWindow.getBrowser().print(printer);
4459 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4462 // Listener triggered when the email button is pressed
4463 @SuppressWarnings("unused")
4464 private void emailNote() {
4465 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4467 if (Desktop.isDesktopSupported()) {
4468 Desktop desktop = Desktop.getDesktop();
4470 String text2 = browserWindow.getContentsToEmail();
4471 QUrl url = new QUrl("mailto:");
4472 url.addQueryItem("subject", currentNote.getTitle());
4473 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4474 url.addQueryItem("body", text2);
4475 QDesktopServices.openUrl(url);
4479 if (desktop.isSupported(Desktop.Action.MAIL)) {
4480 URI uriMailTo = null;
4482 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4483 String text = browserWindow.getContentsToEmail();
4484 //text = "<b>" +text +"</b>";
4485 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4486 +"&BODY=" +text, null);
4487 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4488 +"&ATTACHMENT=d:/test.pdf", null);
4489 desktop.mail(uriMailTo);
4490 } catch (URISyntaxException e) {
4491 e.printStackTrace();
4492 } catch (IOException e) {
4493 e.printStackTrace();
4500 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4502 // Reindex all notes
4503 @SuppressWarnings("unused")
4504 private void fullReindex() {
4505 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4506 indexRunner.addWork("REINDEXALL");
4507 setMessage(tr("Database will be reindexed."));
4508 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4510 // Listener when a user wants to reindex a specific note
4511 @SuppressWarnings("unused")
4512 private void reindexNote() {
4513 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4514 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4515 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4517 if (selectedNotebookGUIDs.size() > 1)
4518 setMessage(tr("Notes will be reindexed."));
4520 setMessage(tr("Note will be reindexed."));
4521 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4524 @SuppressWarnings("unused")
4525 private void deleteNote() {
4526 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4527 if (currentNote == null)
4529 if (currentNoteGuid.equals(""))
4531 String title = null;
4532 if (selectedNoteGUIDs.size() == 1)
4533 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4535 // If we are deleting non-trash notes
4536 if (currentNote.isActive()) {
4537 if (Global.verifyDelete()) {
4539 if (selectedNoteGUIDs.size() > 1) {
4540 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4543 msg = new String(tr("Delete note \"") +title +"\"?");
4545 msg = new String(tr("Delete note selected note?"));
4547 if (QMessageBox.question(this, tr("Confirmation"), msg,
4548 QMessageBox.StandardButton.Yes,
4549 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4553 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4554 selectedNoteGUIDs.add(currentNoteGuid);
4555 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4556 listManager.deleteNote(selectedNoteGUIDs.get(i));
4559 // If we are deleting from the trash.
4560 if (Global.verifyDelete()) {
4562 if (selectedNoteGUIDs.size() > 1) {
4563 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4566 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4568 msg = new String(tr("Permanently delete note selected note?"));
4570 if (QMessageBox.question(this, "Confirmation", msg,
4571 QMessageBox.StandardButton.Yes,
4572 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4576 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4577 selectedNoteGUIDs.add(currentNoteGuid);
4578 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4579 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4580 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4581 if (modelIndex != null) {
4582 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4583 String tableGuid = (String)ix.values().toArray()[0];
4584 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4585 listManager.getNoteTableModel().removeRow(j);
4590 listManager.expungeNote(selectedNoteGUIDs.get(i));
4593 currentNoteGuid = "";
4594 listManager.loadNotesIndex();
4595 noteIndexUpdated(false);
4596 refreshEvernoteNote(true);
4597 scrollToGuid(currentNoteGuid);
4598 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4601 @SuppressWarnings("unused")
4602 private void addNote() {
4603 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4604 // browserWindow.setEnabled(true);
4605 browserWindow.setReadOnly(false);
4607 Calendar currentTime = new GregorianCalendar();
4608 StringBuffer noteString = new StringBuffer(100);
4609 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4610 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4613 if (Global.overrideDefaultFont()) {
4614 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4615 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4616 noteString.append("<br clear=\"none\" />\n");
4617 noteString.append("</span>\n</font>\n");
4619 noteString.append("<br clear=\"none\" />\n");
4620 noteString.append("</en-note>");
4622 Long l = new Long(currentTime.getTimeInMillis());
4623 String randint = new String(Long.toString(l));
4625 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4627 // for the first non-archived notebook. Finally, if nothing else we
4628 // pick the first notebook in the list.
4629 String notebook = null;
4630 listManager.getNotebookIndex().get(0).getGuid();
4631 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4632 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4633 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4634 notebook = currentSelectedNotebook.text(2);
4636 boolean found = false;
4637 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4638 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4639 boolean match = false;
4640 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4641 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4643 j = listManager.getArchiveNotebookIndex().size();
4647 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4648 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4650 // Now we have a list of good notebooks, so we can look for the default
4652 for (int i=0; i<goodNotebooks.size(); i++) {
4653 if (goodNotebooks.get(i).isDefaultNotebook()) {
4654 notebook = goodNotebooks.get(i).getGuid();
4656 i = goodNotebooks.size();
4660 if (goodNotebooks.size() > 0 && !found)
4661 notebook = goodNotebooks.get(0).getGuid();
4664 notebook = listManager.getNotebookIndex().get(0).getGuid();
4667 Note newNote = new Note();
4668 newNote.setUpdateSequenceNum(0);
4669 newNote.setGuid(randint);
4670 newNote.setNotebookGuid(notebook);
4671 newNote.setTitle("Untitled Note");
4672 newNote.setContent(noteString.toString());
4673 newNote.setDeleted(0);
4674 newNote.setCreated(System.currentTimeMillis());
4675 newNote.setUpdated(System.currentTimeMillis());
4676 newNote.setActive(true);
4677 NoteAttributes na = new NoteAttributes();
4678 na.setLatitude(0.0);
4679 na.setLongitude(0.0);
4680 na.setAltitude(0.0);
4681 newNote.setAttributes(new NoteAttributes());
4682 newNote.setTagGuids(new ArrayList<String>());
4683 newNote.setTagNames(new ArrayList<String>());
4685 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4686 if (Global.newNoteWithSelectedTags()) {
4687 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4688 QTreeWidgetItem currentSelection;
4689 for (int i=0; i<selections.size(); i++) {
4690 currentSelection = selections.get(i);
4691 newNote.getTagGuids().add(currentSelection.text(2));
4692 newNote.getTagNames().add(currentSelection.text(0));
4696 conn.getNoteTable().addNote(newNote, true);
4697 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4698 listManager.addNote(newNote);
4699 // noteTableView.insertRow(newNote, true, -1);
4701 currentNote = newNote;
4702 currentNoteGuid = currentNote.getGuid();
4703 noteTableView.clearSelection();
4704 refreshEvernoteNote(true);
4705 listManager.countNotebookResults(listManager.getNoteIndex());
4706 browserWindow.titleLabel.setFocus();
4707 browserWindow.titleLabel.selectAll();
4708 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4710 // If the window is hidden, then we want to popup this in an external window &
4714 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4716 // Restore a note from the trash;
4717 @SuppressWarnings("unused")
4718 private void restoreNote() {
4720 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4721 selectedNoteGUIDs.add(currentNoteGuid);
4722 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4723 listManager.restoreNote(selectedNoteGUIDs.get(i));
4725 currentNoteGuid = "";
4726 listManager.loadNotesIndex();
4727 noteIndexUpdated(false);
4730 // Search a note for specific txt
4731 @SuppressWarnings("unused")
4732 private void findText() {
4734 find.setFocusOnTextField();
4736 @SuppressWarnings("unused")
4737 private void doFindText() {
4738 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4741 @SuppressWarnings("unused")
4742 private void updateNoteTitle(String guid, String title) {
4743 listManager.setNoteSynchronized(guid, false);
4745 // Signal received that note content has changed. Normally we just need the guid to remove
4746 // it from the cache.
4747 @SuppressWarnings("unused")
4748 private void invalidateNoteCache(String guid, String content) {
4749 noteCache.remove(guid);
4750 refreshEvernoteNote(true);
4752 // Signal received that a note guid has changed
4753 @SuppressWarnings("unused")
4754 private void noteGuidChanged(String oldGuid, String newGuid) {
4755 if (noteCache.containsKey(oldGuid)) {
4756 if (!oldGuid.equals(currentNoteGuid)) {
4757 String cache = noteCache.get(oldGuid);
4758 noteCache.put(newGuid, cache);
4759 noteCache.remove(oldGuid);
4761 noteCache.remove(oldGuid);
4762 noteCache.put(newGuid, browserWindow.getContent());
4766 listManager.updateNoteGuid(oldGuid, newGuid, false);
4767 if (currentNoteGuid.equals(oldGuid)) {
4768 if (currentNote != null)
4769 currentNote.setGuid(newGuid);
4770 currentNoteGuid = newGuid;
4773 if (externalWindows.containsKey(oldGuid)) {
4774 ExternalBrowse b = externalWindows.get(oldGuid);
4775 externalWindows.remove(oldGuid);
4776 b.getBrowserWindow().getNote().setGuid(newGuid);
4777 externalWindows.put(newGuid, b);
4780 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4781 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4782 noteTableView.proxyModel.addGuid(newGuid);
4783 i=listManager.getNoteIndex().size();
4787 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4788 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4789 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4790 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4794 // Toggle the note editor button bar
4795 private void toggleEditorButtonBar() {
4796 if (browserWindow.buttonsVisible) {
4797 browserWindow.hideButtons();
4798 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4799 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4801 browserWindow.buttonsVisible = true;
4802 showEditorButtons(browserWindow);
4804 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4806 // Show editor buttons
4807 private void showEditorButtons(BrowserWindow browser) {
4808 browser.buttonLayout.setVisible(true);
4809 browser.undoAction.setVisible(false);
4811 browser.undoButton.setVisible(false);
4813 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4814 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4815 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4816 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4817 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4818 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4819 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4820 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4821 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4822 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4823 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4824 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4825 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4826 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4827 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4828 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4829 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4830 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4831 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4832 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4833 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4834 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4835 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4837 private void duplicateNote(String guid) {
4839 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4840 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4841 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4842 oldNote.setResources(resList);
4843 duplicateNote(oldNote);
4845 private void duplicateNote(Note oldNote) {
4847 // Now that we have a good notebook guid, we need to move the conflicting note
4848 // to the local notebook
4849 Calendar currentTime = new GregorianCalendar();
4850 Long l = new Long(currentTime.getTimeInMillis());
4851 String newGuid = new String(Long.toString(l));
4853 // Note newNote = oldNote.deepCopy();
4854 Note newNote = (Note)Global.deepCopy(oldNote);
4855 newNote.setUpdateSequenceNum(0);
4856 newNote.setGuid(newGuid);
4857 newNote.setDeleted(0);
4858 newNote.setActive(true);
4861 List<String> tagNames = new ArrayList<String>();
4862 List<String> tagGuids = new ArrayList<String>();;
4863 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4864 tagNames.add(oldNote.getTagNames().get(i));
4865 tagGuids.add(oldNote.getTagGuids().get(i));
4868 // Sort note Tags to make them look nice
4869 for (int i=0; i<tagNames.size()-1; i++) {
4870 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4871 String n1 = tagNames.get(i);
4872 String n2 = tagNames.get(i+1);
4873 tagNames.set(i, n2);
4874 tagNames.set(i+1, n1);
4877 newNote.setTagGuids(tagGuids);
4878 newNote.setTagNames(tagNames);
4880 // Add tag guids to note
4883 // Duplicate resources
4884 List<Resource> resList = oldNote.getResources();
4885 if (resList == null)
4886 resList = new ArrayList<Resource>();
4888 for (int i=0; i<resList.size(); i++) {
4890 while (l == prevGuid) {
4891 currentTime = new GregorianCalendar();
4892 l = new Long(currentTime.getTimeInMillis());
4895 String newResGuid = new String(Long.toString(l));
4896 resList.get(i).setNoteGuid(newGuid);
4897 resList.get(i).setGuid(newResGuid);
4898 resList.get(i).setUpdateSequenceNum(0);
4899 resList.get(i).setActive(true);
4900 conn.getNoteTable().noteResourceTable.saveNoteResource(
4901 (Resource)Global.deepCopy(resList.get(i)), true);
4903 newNote.setResources(resList);
4905 // Add note to the database
4906 listManager.addNote(newNote);
4907 conn.getNoteTable().addNote(newNote, true);
4908 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4909 noteTableView.insertRow(newNote, true, -1);
4910 currentNoteGuid = newNote.getGuid();
4911 currentNote = newNote;
4912 refreshEvernoteNote(true);
4913 listManager.countNotebookResults(listManager.getNoteIndex());
4917 @SuppressWarnings("unused")
4918 private void allNotes() {
4919 clearAttributeFilter();
4920 clearNotebookFilter();
4921 clearSavedSearchFilter();
4924 searchField.clear();
4925 if (Global.mimicEvernoteInterface) {
4926 notebookTree.selectGuid("");
4928 notebookTreeSelection();
4929 refreshEvernoteNote(true);
4932 @SuppressWarnings("unused")
4933 private void mergeNotes() {
4934 logger.log(logger.HIGH, "Merging notes");
4937 String masterGuid = null;
4938 List<String> sources = new ArrayList<String>();
4940 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4941 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4942 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4943 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4945 masterGuid = (String)ix.values().toArray()[0];
4947 sources.add((String)ix.values().toArray()[0]);
4950 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4951 logger.log(logger.EXTREME, "Children count: "+sources.size());
4952 mergeNoteContents(masterGuid, sources);
4953 currentNoteGuid = masterGuid;
4954 noteIndexUpdated(false);
4955 refreshEvernoteNote(true);
4958 private void mergeNoteContents(String targetGuid, List<String> sources) {
4959 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4960 String newContent = target.getContent();
4961 newContent = newContent.replace("</en-note>", "<br></br>");
4963 for (int i=0; i<sources.size(); i++) {
4964 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4965 if (source.isSetTitle()) {
4966 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4968 String sourceContent = source.getContent();
4969 logger.log(logger.EXTREME, "Merging contents into note");
4970 logger.log(logger.EXTREME, sourceContent);
4971 logger.log(logger.EXTREME, "End of content");
4972 int startOfNote = sourceContent.indexOf("<en-note>");
4973 sourceContent = sourceContent.substring(startOfNote+9);
4974 int endOfNote = sourceContent.indexOf("</en-note>");
4975 sourceContent = sourceContent.substring(0,endOfNote);
4976 newContent = newContent + sourceContent;
4977 logger.log(logger.EXTREME, "New note content");
4978 logger.log(logger.EXTREME, newContent);
4979 logger.log(logger.EXTREME, "End of content");
4980 for (int j=0; j<source.getResourcesSize(); j++) {
4981 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4982 Resource r = source.getResources().get(j);
4983 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4985 Calendar currentTime = new GregorianCalendar();
4986 Long l = new Long(currentTime.getTimeInMillis());
4990 while (l == prevGuid) {
4991 currentTime = new GregorianCalendar();
4992 l = new Long(currentTime.getTimeInMillis());
4994 String newResGuid = new String(Long.toString(l));
4995 newRes.setNoteGuid(targetGuid);
4996 newRes.setGuid(newResGuid);
4997 newRes.setUpdateSequenceNum(0);
4998 newRes.setActive(true);
4999 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5002 logger.log(logger.EXTREME, "Updating note");
5003 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5004 for (int i=0; i<sources.size(); i++) {
5005 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5006 listManager.deleteNote(sources.get(i));
5008 logger.log(logger.EXTREME, "Exiting merge note");
5010 // A resource within a note has had a guid change
5011 @SuppressWarnings("unused")
5012 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5013 if (oldGuid != null && !oldGuid.equals(newGuid))
5014 Global.resourceMap.put(oldGuid, newGuid);
5016 // View a thumbnail of the note
5017 public void thumbnailView() {
5019 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5020 QFile thumbnail = new QFile(thumbnailName);
5021 if (!thumbnail.exists()) {
5023 QImage img = new QImage();
5024 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5025 thumbnailViewer.setThumbnail(img);
5027 thumbnailViewer.setThumbnail(thumbnailName);
5028 if (!thumbnailViewer.isVisible())
5029 thumbnailViewer.showFullScreen();
5031 // An error happened while saving a note. Inform the user
5032 @SuppressWarnings("unused")
5033 private void saveRunnerError(String guid, String msg) {
5035 String title = "*Unknown*";
5036 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5037 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5038 title = listManager.getMasterNoteIndex().get(i).getTitle();
5039 i=listManager.getMasterNoteIndex().size();
5042 msg = tr("An error has happened while saving the note \"") +title+
5043 tr("\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
5044 "As a result, changes to the note may not be saved properly in the database."+
5045 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5046 "\nbe lost. Please review the note to recover any critical data before restarting.");
5048 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5051 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5052 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5053 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5054 // Find an idle preview object
5055 for (int i=0; i<thumbGenerators.size(); i++) {
5056 if (thumbGenerators.get(i).mutex.tryLock()) {
5057 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5058 thumbGenerators.get(i).loadContent(guid, html, zoom);
5062 if (thumbGenerators.size() >= 1) {
5063 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5067 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5068 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5069 thumbGenerators.add(preview);
5071 if (preview.mutex.tryLock()) {
5072 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5073 preview.loadContent(guid, html, zoom);
5075 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5080 //**********************************************************
5081 //**********************************************************
5082 //* Online user actions
5083 //**********************************************************
5084 //**********************************************************
5085 private void setupOnlineMenu() {
5086 if (!Global.isConnected) {
5087 menuBar.noteOnlineHistoryAction.setEnabled(false);
5088 menuBar.selectiveSyncAction.setEnabled(false);
5091 menuBar.noteOnlineHistoryAction.setEnabled(true);
5092 menuBar.selectiveSyncAction.setEnabled(true);
5095 @SuppressWarnings("unused")
5096 private void viewNoteHistory() {
5097 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5099 if (currentNote.getUpdateSequenceNum() == 0) {
5100 setMessage(tr("Note has never been synchronized."));
5101 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5105 setMessage(tr("Getting Note History"));
5107 Note currentOnlineNote = null;
5110 if (Global.isPremium())
5111 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5113 versions = new ArrayList<NoteVersionId>();
5114 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5115 } catch (EDAMUserException e) {
5116 setMessage("EDAMUserException: " +e.getMessage());
5118 } catch (EDAMSystemException e) {
5119 setMessage("EDAMSystemException: " +e.getMessage());
5121 } catch (EDAMNotFoundException e) {
5122 setMessage(tr("Note not found on server."));
5123 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5125 } catch (TException e) {
5126 setMessage("EDAMTransactionException: " +e.getMessage());
5130 // If we've gotten this far, we have a good note.
5131 if (historyWindow == null) {
5132 historyWindow = new OnlineNoteHistory(logger, conn);
5133 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5134 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5135 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5137 historyWindow.historyCombo.clear();
5139 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5140 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5142 historyWindow.setCurrent(isDirty);
5144 loadHistoryWindowContent(currentOnlineNote);
5145 historyWindow.load(versions);
5146 setMessage(tr("History retrieved"));
5148 historyWindow.exec();
5150 private Note reloadHistoryWindow(String selection) {
5152 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5153 String dateTimeFormat = new String(fmt);
5154 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5158 for (int i=0; i<versions.size(); i++) {
5159 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5160 if (versionDate.toString().equals(selection))
5164 if (index > -1 || selection.indexOf("Current") > -1) {
5165 Note historyNote = null;
5168 usn = versions.get(index).getUpdateSequenceNum();
5169 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5171 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5172 } catch (EDAMUserException e) {
5173 setMessage("EDAMUserException: " +e.getMessage());
5176 } catch (EDAMSystemException e) {
5177 setMessage("EDAMSystemException: " +e.getMessage());
5180 } catch (EDAMNotFoundException e) {
5181 setMessage("EDAMNotFoundException: " +e.getMessage());
5184 } catch (TException e) {
5185 setMessage("EDAMTransactionException: " +e.getMessage());
5191 if (historyNote != null)
5192 historyWindow.setContent(historyNote);
5198 private void loadHistoryWindowContent(Note note) {
5199 note.setUpdateSequenceNum(0);
5200 historyWindow.setContent(note);
5202 @SuppressWarnings("unused")
5203 private void restoreHistoryNoteAsNew() {
5204 setMessage(tr("Restoring as new note."));
5205 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5206 setMessage(tr("Note has been restored as a new note."));
5208 @SuppressWarnings("unused")
5209 private void restoreHistoryNote() {
5210 setMessage(tr("Restoring note."));
5211 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5212 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5215 for (int i=0; i<n.getResourcesSize(); i++) {
5216 n.getResources().get(i).setActive(true);
5217 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5219 listManager.addNote(n);
5220 conn.getNoteTable().addNote(n, true);
5221 refreshEvernoteNote(true);
5222 setMessage(tr("Note has been restored."));
5224 @SuppressWarnings("unused")
5225 private void setupSelectiveSync() {
5227 // Get a list of valid notebooks
5228 List<Notebook> notebooks = null;
5229 List<Tag> tags = null;
5230 List<LinkedNotebook> linkedNotebooks = null;
5232 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5233 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5234 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5235 } catch (EDAMUserException e) {
5236 setMessage("EDAMUserException: " +e.getMessage());
5238 } catch (EDAMSystemException e) {
5239 setMessage("EDAMSystemException: " +e.getMessage());
5241 } catch (TException e) {
5242 setMessage("EDAMTransactionException: " +e.getMessage());
5244 } catch (EDAMNotFoundException e) {
5245 setMessage("EDAMNotFoundException: " +e.getMessage());
5249 // Split up notebooks into synchronized & non-synchronized
5250 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5251 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5253 for (int i=notebooks.size()-1; i>=0; i--) {
5254 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5255 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5256 ignoredBooks.add(notebooks.get(i));
5257 j=dbIgnoredNotebooks.size();
5262 // split up tags into synchronized & non-synchronized
5263 List<Tag> ignoredTags = new ArrayList<Tag>();
5264 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5266 for (int i=tags.size()-1; i>=0; i--) {
5267 for (int j=0; j<dbIgnoredTags.size(); j++) {
5268 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5269 ignoredTags.add(tags.get(i));
5270 j=dbIgnoredTags.size();
5275 // split up linked notebooks into synchronized & non-synchronized
5276 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5277 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5278 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5279 String notebookGuid = linkedNotebooks.get(i).getGuid();
5280 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5281 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5282 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5283 j=dbIgnoredLinkedNotebooks.size();
5288 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5290 if (!ignore.okClicked())
5295 // Clear out old notebooks & add the new ones
5296 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5297 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5298 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5301 List<String> newNotebooks = new ArrayList<String>();
5302 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5303 String text = ignore.getIgnoredBookList().takeItem(i).text();
5304 for (int j=0; j<notebooks.size(); j++) {
5305 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5306 Notebook n = notebooks.get(j);
5307 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5309 newNotebooks.add(n.getGuid());
5314 // Clear out old tags & add new ones
5315 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5316 for (int i=0; i<oldIgnoreTags.size(); i++) {
5317 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5320 List<String> newTags = new ArrayList<String>();
5321 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5322 String text = ignore.getIgnoredTagList().takeItem(i).text();
5323 for (int j=0; j<tags.size(); j++) {
5324 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5325 Tag t = tags.get(j);
5326 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5327 newTags.add(t.getGuid());
5333 // Clear out old tags & add new ones
5334 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5335 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5336 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5339 List<String> newLinked = new ArrayList<String>();
5340 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5341 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5342 for (int j=0; j<linkedNotebooks.size(); j++) {
5343 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5344 LinkedNotebook t = linkedNotebooks.get(j);
5345 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5346 newLinked.add(t.getGuid());
5347 j=linkedNotebooks.size();
5352 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5358 //**********************************************************
5359 //**********************************************************
5360 //* XML Modifying methods
5361 //**********************************************************
5362 //**********************************************************
5363 // An error has happended fetching a resource. let the user know
5364 private void resourceErrorMessage() {
5368 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5369 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5370 "In a perfect world this wouldn't happen, but it has.\n" +
5371 "It is embarasing when a program like me, designed to save all your\n"+
5372 "precious data, has a problem finding data.\n\n" +
5373 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5374 "In the mean time, I'm not going to let you make changes to this note.\n" +
5375 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5376 "this note on the Evernote servers. Sorry."+
5377 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5379 browserWindow.setReadOnly(true);
5386 //**********************************************************
5387 //**********************************************************
5389 //**********************************************************
5390 //**********************************************************
5391 // We should now do a sync with Evernote
5392 private void syncTimer() {
5393 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5394 syncRunner.syncNeeded = true;
5395 syncRunner.disableUploads = Global.disableUploads;
5397 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5399 private void syncStart() {
5400 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5402 if (!syncRunning && Global.isConnected) {
5403 syncRunner.setConnected(true);
5404 syncRunner.setKeepRunning(Global.keepRunning);
5405 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5407 if (syncThreadsReady > 0) {
5408 thumbnailRunner.interrupt = true;
5409 saveNoteIndexWidth();
5410 saveNoteColumnPositions();
5411 if (syncRunner.addWork("SYNC")) {
5413 syncRunner.syncNeeded = true;
5418 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5420 @SuppressWarnings("unused")
5421 private void syncThreadComplete(Boolean refreshNeeded) {
5422 setMessage(tr("Finalizing Synchronization"));
5424 syncRunning = false;
5425 syncRunner.syncNeeded = false;
5426 synchronizeAnimationTimer.stop();
5427 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5429 if (currentNote == null) {
5430 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5432 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5433 noteIndexUpdated(false);
5434 noteTableView.selectionModel().blockSignals(true);
5435 scrollToGuid(currentNoteGuid);
5436 noteTableView.selectionModel().blockSignals(false);
5437 refreshEvernoteNote(false);
5438 scrollToGuid(currentNoteGuid);
5441 // Check to see if there were any shared notebook errors
5442 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5443 String guid = syncRunner.errorSharedNotebooks.get(0);
5444 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5445 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5446 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5448 if (syncDialog.okPressed()) {
5449 if (syncDialog.doNothing.isChecked()) {
5450 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5453 if (syncDialog.deleteNotebook.isChecked()) {
5454 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5455 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5456 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5457 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5460 /* if (syncDialog.convertToLocal.isChecked()) {
5461 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, true);
5462 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5465 if (syncDialog.convertToShared.isChecked()) {
5466 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5467 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, false);
5475 // Finalize the synchronization
5476 if (!syncRunner.error)
5477 setMessage(tr("Synchronization Complete"));
5479 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5480 logger.log(logger.MEDIUM, "Sync complete.");
5482 public void saveUploadAmount(long t) {
5483 Global.saveUploadAmount(t);
5485 public void saveUserInformation(User user) {
5486 Global.saveUserInformation(user);
5488 public void saveEvernoteUpdateCount(int i) {
5489 Global.saveEvernoteUpdateCount(i);
5491 public void refreshLists() {
5492 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5494 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5495 tagIndexUpdated(true);
5496 notebookIndexUpdated();
5497 savedSearchIndexUpdated();
5498 listManager.loadNotesIndex();
5500 noteTableView.selectionModel().blockSignals(true);
5501 noteIndexUpdated(true);
5502 noteTableView.selectionModel().blockSignals(false);
5503 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5507 @SuppressWarnings("unused")
5508 private void authTimer() {
5509 Calendar cal = Calendar.getInstance();
5511 // If we are not connected let's get out of here
5512 if (!Global.isConnected)
5515 // If this is the first time through, then we need to set this
5516 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5517 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5519 // long now = new Date().getTime();
5520 // if (now > Global.authRefreshTime && Global.isConnected) {
5521 syncRunner.authRefreshNeeded = true;
5525 @SuppressWarnings("unused")
5526 private void authRefreshComplete(boolean goodSync) {
5527 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5528 Global.isConnected = syncRunner.isConnected;
5530 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5531 authTimer.start(1000*60*15);
5532 logger.log(logger.LOW, "Authentication token has been renewed");
5533 // setMessage("Authentication token has been renewed.");
5535 authTimer.start(1000*60*5);
5536 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5537 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5539 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5543 @SuppressWarnings("unused")
5544 private synchronized void indexTimer() {
5545 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5548 if (!indexDisabled && indexRunner.idle) {
5549 thumbnailRunner.interrupt = true;
5550 indexRunner.addWork("SCAN");
5552 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5555 @SuppressWarnings("unused")
5556 private void indexStarted() {
5557 setMessage(tr("Indexing notes"));
5559 @SuppressWarnings("unused")
5560 private void indexComplete() {
5561 setMessage(tr("Index complete"));
5563 @SuppressWarnings("unused")
5564 private synchronized void toggleNoteIndexing() {
5565 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5566 indexDisabled = !indexDisabled;
5568 setMessage(tr("Indexing is now enabled."));
5570 setMessage(tr("Indexing is now disabled."));
5571 menuBar.disableIndexing.setChecked(indexDisabled);
5572 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5575 @SuppressWarnings("unused")
5576 private void threadMonitorCheck() {
5581 alive = listManager.threadCheck(Global.tagCounterThreadId);
5584 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5585 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5586 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5587 disableTagThreadCheck = true;
5592 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5594 notebookThreadDeadCount++;
5595 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5596 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5597 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5598 disableNotebookThreadCheck=true;
5601 notebookThreadDeadCount=0;
5603 alive = listManager.threadCheck(Global.trashCounterThreadId);
5606 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5607 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5608 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5609 disableTrashThreadCheck = true;
5614 alive = listManager.threadCheck(Global.saveThreadId);
5616 saveThreadDeadCount++;
5617 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5618 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5619 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5620 disableSaveThreadCheck = true;
5623 saveThreadDeadCount=0;
5625 if (!syncThread.isAlive()) {
5626 syncThreadDeadCount++;
5627 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5628 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5629 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5630 disableSyncThreadCheck = true;
5633 syncThreadDeadCount=0;
5635 if (!indexThread.isAlive()) {
5636 indexThreadDeadCount++;
5637 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5638 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5639 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5640 disableIndexThreadCheck = true;
5643 indexThreadDeadCount=0;
5648 private void thumbnailTimer() {
5649 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5650 thumbnailRunner.addWork("SCAN");
5654 //**************************************************
5655 //* Backup & Restore
5656 //**************************************************
5657 @SuppressWarnings("unused")
5658 private void databaseBackup() {
5659 QFileDialog fd = new QFileDialog(this);
5660 fd.setFileMode(FileMode.AnyFile);
5661 fd.setConfirmOverwrite(true);
5662 fd.setWindowTitle(tr("Backup Database"));
5663 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5664 fd.setAcceptMode(AcceptMode.AcceptSave);
5665 if (saveLastPath == null || saveLastPath.equals(""))
5666 fd.setDirectory(System.getProperty("user.home"));
5668 fd.setDirectory(saveLastPath);
5669 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5675 saveLastPath = fd.selectedFiles().get(0);
5676 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5677 setMessage(tr("Backing up database"));
5679 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5681 ExportData noteWriter = new ExportData(conn, true);
5682 String fileName = fd.selectedFiles().get(0);
5684 if (!fileName.endsWith(".nnex"))
5685 fileName = fileName +".nnex";
5686 noteWriter.exportData(fileName);
5687 setMessage(tr("Database backup completed."));
5692 @SuppressWarnings("unused")
5693 private void databaseRestore() {
5694 if (QMessageBox.question(this, tr("Confirmation"),
5695 tr("This is used to restore a database from backups.\n" +
5696 "It is HIGHLY recommened that this only be used to populate\n" +
5697 "an empty database. Restoring into a database that\n already has data" +
5698 " can cause problems.\n\nAre you sure you want to continue?"),
5699 QMessageBox.StandardButton.Yes,
5700 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5705 QFileDialog fd = new QFileDialog(this);
5706 fd.setFileMode(FileMode.ExistingFile);
5707 fd.setConfirmOverwrite(true);
5708 fd.setWindowTitle(tr("Restore Database"));
5709 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5710 fd.setAcceptMode(AcceptMode.AcceptOpen);
5711 if (saveLastPath == null || saveLastPath.equals(""))
5712 fd.setDirectory(System.getProperty("user.home"));
5714 fd.setDirectory(saveLastPath);
5715 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5721 saveLastPath = fd.selectedFiles().get(0);
5722 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5724 setMessage(tr("Restoring database"));
5725 ImportData noteReader = new ImportData(conn, true);
5726 noteReader.importData(fd.selectedFiles().get(0));
5728 if (noteReader.lastError != 0) {
5729 setMessage(noteReader.getErrorMessage());
5730 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5735 listManager.loadNoteTitleColors();
5737 refreshEvernoteNote(true);
5738 setMessage(tr("Database has been restored."));
5741 @SuppressWarnings("unused")
5742 private void exportNotes() {
5743 QFileDialog fd = new QFileDialog(this);
5744 fd.setFileMode(FileMode.AnyFile);
5745 fd.setConfirmOverwrite(true);
5746 fd.setWindowTitle(tr("Backup Database"));
5747 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5748 fd.setAcceptMode(AcceptMode.AcceptSave);
5749 fd.setDirectory(System.getProperty("user.home"));
5750 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5756 setMessage(tr("Exporting Notes"));
5759 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5760 selectedNoteGUIDs.add(currentNoteGuid);
5762 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5763 String fileName = fd.selectedFiles().get(0);
5765 if (!fileName.endsWith(".nnex"))
5766 fileName = fileName +".nnex";
5767 noteWriter.exportData(fileName);
5768 setMessage(tr("Export completed."));
5774 @SuppressWarnings("unused")
5775 private void importNotes() {
5776 QFileDialog fd = new QFileDialog(this);
5777 fd.setFileMode(FileMode.ExistingFile);
5778 fd.setConfirmOverwrite(true);
5779 fd.setWindowTitle(tr("Import Notes"));
5780 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5781 fd.setAcceptMode(AcceptMode.AcceptOpen);
5782 if (saveLastPath == null || saveLastPath.equals(""))
5783 fd.setDirectory(System.getProperty("user.home"));
5785 fd.setDirectory(saveLastPath);
5786 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5792 setMessage(tr("Importing Notes"));
5795 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5796 selectedNoteGUIDs.add(currentNoteGuid);
5798 ImportData noteReader = new ImportData(conn, false);
5799 String fileName = fd.selectedFiles().get(0);
5800 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5802 if (!fileName.endsWith(".nnex"))
5803 fileName = fileName +".nnex";
5804 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5805 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5807 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5809 noteReader.importData(fileName);
5811 if (noteReader.lastError != 0) {
5812 setMessage(noteReader.getErrorMessage());
5813 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5818 listManager.loadNoteTitleColors();
5820 refreshEvernoteNote(false);
5821 setMessage(tr("Notes have been imported."));
5824 setMessage(tr("Import completed."));
5831 //**************************************************
5832 //* Duplicate a note
5833 //**************************************************
5834 @SuppressWarnings("unused")
5835 private void duplicateNote() {
5837 duplicateNote(currentNoteGuid);
5840 //**************************************************
5841 //* Action from when a user clicks Copy As URL
5842 //**************************************************
5843 @SuppressWarnings("unused")
5844 private void copyAsUrlClicked() {
5845 QClipboard clipboard = QApplication.clipboard();
5846 QMimeData mime = new QMimeData();
5848 mime.setText(currentNoteGuid);
5849 List<QUrl> urls = new ArrayList<QUrl>();
5851 // Start building the URL
5852 User user = Global.getUserInformation();
5854 // Check that we have everything we need
5855 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5856 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5858 if (!warning.neverSynchronize())
5861 Global.setBypassSynchronizationWarning(true);
5862 user.setShardId("s0");
5868 // Start building a list of URLs based upon the selected notes
5869 noteTableView.showColumn(Global.noteTableGuidPosition);
5871 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5872 if (!Global.isColumnVisible("guid"))
5873 noteTableView.hideColumn(Global.noteTableGuidPosition);
5875 // Check that the note is either synchronized, or in a local notebook
5876 for (int i=0; i<selections.size(); i++) {
5878 int row = selections.get(i).row();
5879 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5880 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5881 String selectedGuid = (String)ix.values().toArray()[0];
5883 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5884 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
5885 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
5886 "new notes to a local notebook."));
5891 // Start building the URLs
5892 for (int i=0; i<selections.size(); i++) {
5894 int row = selections.get(i).row();
5895 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5896 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5897 String selectedGuid = (String)ix.values().toArray()[0];
5898 mime.setText(selectedGuid);
5902 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5903 if (selectedNote.getUpdateSequenceNum() > 0) {
5907 gid = "00000000-0000-0000-0000-000000000000";
5910 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
5912 urls.add(new QUrl(url));
5915 clipboard.setMimeData(mime);
5919 //**************************************************
5921 //**************************************************
5922 public void setupFolderImports() {
5923 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5925 if (importKeepWatcher == null)
5926 importKeepWatcher = new QFileSystemWatcher();
5927 if (importDeleteWatcher == null) {
5928 importDeleteWatcher = new QFileSystemWatcher();
5929 for (int i=0; i<records.size(); i++) {
5930 if (!records.get(i).keep)
5931 folderImportDelete(records.get(i).folder);
5937 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5938 for (int i=0; i<records.size(); i++) {
5939 if (records.get(i).keep)
5940 importKeepWatcher.addPath(records.get(i).folder);
5942 importDeleteWatcher.addPath(records.get(i).folder);
5945 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5946 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5948 // Look at the files already there so we don't import them again if a new file is created
5949 if (importedFiles == null) {
5950 importedFiles = new ArrayList<String>();
5951 for (int j=0; j<records.size(); j++) {
5952 QDir dir = new QDir(records.get(j).folder);
5953 List<QFileInfo> list = dir.entryInfoList();
5954 for (int k=0; k<list.size(); k++) {
5955 if (list.get(k).isFile())
5956 importedFiles.add(list.get(k).absoluteFilePath());
5961 public void folderImport() {
5962 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5963 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5965 if (!dialog.okClicked())
5968 // We have some sort of update.
5969 if (importKeepWatcher.directories().size() > 0)
5970 importKeepWatcher.removePaths(importKeepWatcher.directories());
5971 if (importDeleteWatcher.directories().size() > 0)
5972 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5974 conn.getWatchFolderTable().expungeAll();
5975 // Start building from the table
5976 for (int i=0; i<dialog.table.rowCount(); i++) {
5977 QTableWidgetItem item = dialog.table.item(i, 0);
5978 String dir = item.text();
5979 item = dialog.table.item(i, 1);
5980 String notebook = item.text();
5981 item = dialog.table.item(i, 2);
5983 if (item.text().equalsIgnoreCase("Keep"))
5988 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5989 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5991 setupFolderImports();
5994 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5996 String whichOS = System.getProperty("os.name");
5997 if (whichOS.contains("Windows"))
5998 dirName = dirName.replace('/','\\');
6000 FileImporter importer = new FileImporter(logger, conn);
6002 QDir dir = new QDir(dirName);
6003 List<QFileInfo> list = dir.entryInfoList();
6004 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6006 for (int i=0; i<list.size(); i++){
6008 boolean redundant = false;
6009 // Check if we've already imported this one or if it existed before
6010 for (int j=0; j<importedFiles.size(); j++) {
6011 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6016 importer.setFileInfo(list.get(i));
6017 importer.setFileName(list.get(i).absoluteFilePath());
6020 if (list.get(i).isFile() && importer.isValidType()) {
6022 if (!importer.importFile()) {
6023 // If we can't get to the file, it is probably locked. We'll try again later.
6024 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6025 importFilesKeep.add(list.get(i).absoluteFilePath());
6029 Note newNote = importer.getNote();
6030 newNote.setNotebookGuid(notebook);
6031 newNote.setTitle(dir.at(i));
6032 listManager.addNote(newNote);
6033 conn.getNoteTable().addNote(newNote, true);
6034 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
6035 noteTableView.insertRow(newNote, true, -1);
6036 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6037 listManager.countNotebookResults(listManager.getNoteIndex());
6038 importedFiles.add(list.get(i).absoluteFilePath());
6046 public void folderImportDelete(String dirName) {
6048 String whichOS = System.getProperty("os.name");
6049 if (whichOS.contains("Windows"))
6050 dirName = dirName.replace('/','\\');
6052 FileImporter importer = new FileImporter(logger, conn);
6053 QDir dir = new QDir(dirName);
6054 List<QFileInfo> list = dir.entryInfoList();
6055 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6057 for (int i=0; i<list.size(); i++){
6058 importer.setFileInfo(list.get(i));
6059 importer.setFileName(list.get(i).absoluteFilePath());
6061 if (list.get(i).isFile() && importer.isValidType()) {
6063 if (!importer.importFile()) {
6064 // If we can't get to the file, it is probably locked. We'll try again later.
6065 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6066 importFilesKeep.add(list.get(i).absoluteFilePath());
6070 Note newNote = importer.getNote();
6071 newNote.setNotebookGuid(notebook);
6072 newNote.setTitle(dir.at(i));
6073 listManager.addNote(newNote);
6074 conn.getNoteTable().addNote(newNote, true);
6075 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
6076 noteTableView.insertRow(newNote, true, -1);
6077 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6078 listManager.countNotebookResults(listManager.getNoteIndex());
6079 dir.remove(dir.at(i));
6085 //**************************************************
6087 //**************************************************
6088 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6089 logger.log(logger.HIGH, "Entering exernalFileEdited");
6091 // Strip URL prefix and base dir path
6092 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6093 String name = fileName.replace(dPath, "");
6094 int pos = name.lastIndexOf('.');
6097 guid = guid.substring(0,pos);
6099 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6101 guid = name.substring(0, pos);
6104 QFile file = new QFile(fileName);
6105 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6106 // If we can't get to the file, it is probably locked. We'll try again later.
6107 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6108 externalFiles.add(fileName);
6111 QByteArray binData = file.readAll();
6113 if (binData.size() == 0) {
6114 // If we can't get to the file, it is probably locked. We'll try again later.
6115 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6116 externalFiles.add(fileName);
6120 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6122 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6123 if (r == null || r.getData() == null || r.getData().getBody() == null)
6125 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6126 MessageDigest md = MessageDigest.getInstance("MD5");
6127 md.update(binData.toByteArray());
6128 byte[] hash = md.digest();
6129 String newHash = Global.byteArrayToHexString(hash);
6130 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6131 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6133 if (externalWindows.containsKey(r.getNoteGuid())) {
6134 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6135 r.getGuid(), oldHash, newHash);
6137 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6138 Data data = r.getData();
6139 data.setBody(binData.toByteArray());
6140 data.setBodyHash(hash);
6141 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6143 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6145 if (r.getNoteGuid().equals(currentNoteGuid)) {
6146 QWebSettings.setMaximumPagesInCache(0);
6147 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6148 refreshEvernoteNote(true);
6149 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6152 if (externalWindows.containsKey(r.getNoteGuid())) {
6153 QWebSettings.setMaximumPagesInCache(0);
6154 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6155 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6159 logger.log(logger.HIGH, "Exiting externalFielEdited");
6161 // This is a timer event that tries to save any external files that were edited. This
6162 // is only needed if we couldn't save a file earlier.
6163 public void externalFileEditedSaver() {
6164 for (int i=externalFiles.size()-1; i>=0; i--) {
6166 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6167 externalFileEdited(externalFiles.get(i));
6168 externalFiles.remove(i);
6169 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6171 for (int i=0; i<importFilesKeep.size(); i++) {
6173 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6174 folderImportKeep(importFilesKeep.get(i));
6175 importFilesKeep.remove(i);
6176 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6178 for (int i=0; i<importFilesDelete.size(); i++) {
6179 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6180 folderImportDelete(importFilesDelete.get(i));
6181 importFilesDelete.remove(i);
6188 // If an attachment on the current note was edited, we need to update the current notes's hash
6189 // Update a note content's hash. This happens if a resource is edited outside of NN
6190 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6191 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6193 for (;position>-1;) {
6194 endPos = browser.getContent().indexOf(">", position+1);
6195 String oldSegment = browser.getContent().substring(position,endPos);
6196 int hashPos = oldSegment.indexOf("hash=\"");
6197 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6198 String hash = oldSegment.substring(hashPos+6, hashEnd);
6199 if (hash.equalsIgnoreCase(oldHash)) {
6200 String newSegment = oldSegment.replace(oldHash, newHash);
6201 String content = browser.getContent().substring(0,position) +
6203 browser.getContent().substring(endPos);
6204 browser.setContent(new QByteArray(content));;
6207 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6212 //*************************************************
6213 //* Minimize to tray
6214 //*************************************************
6216 public void changeEvent(QEvent e) {
6217 if (e.type() == QEvent.Type.WindowStateChange) {
6218 if (isMinimized() && Global.showTrayIcon()) {
6220 QTimer.singleShot(10, this, "hide()");
6224 windowMaximized = true;
6226 windowMaximized = false;
6230 //*************************************************
6231 //* Check database userid & passwords
6232 //*************************************************
6233 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6234 Connection connection;
6237 Class.forName("org.h2.Driver");
6238 } catch (ClassNotFoundException e1) {
6239 e1.printStackTrace();
6244 String passwordString = null;
6245 if (cypherPassword==null || cypherPassword.trim().equals(""))
6246 passwordString = userPassword;
6248 passwordString = cypherPassword+" "+userPassword;
6249 connection = DriverManager.getConnection(url,userid,passwordString);
6250 } catch (SQLException e) {
6255 } catch (SQLException e) {
6256 e.printStackTrace();
6261 //*************************************************
6262 //* View / Hide source HTML for a note
6263 //*************************************************
6264 public void viewSource() {
6265 browserWindow.showSource(menuBar.viewSource.isChecked());
6267 //*************************************************
6268 // Block the program. This is used for things
6269 // like async web calls.
6270 //*************************************************
6271 @SuppressWarnings("unused")
6272 private void blockApplication(BrowserWindow b) {
6273 // Block all signals
6277 blockTimer = new QTimer();
6278 blockTimer.setSingleShot(true);
6279 blockTimer.setInterval(15000);
6280 blockTimer.timeout.connect(this, "unblockApplication()");
6285 @SuppressWarnings("unused")
6286 private void unblockApplication() {
6288 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6289 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6290 blockingWindow.unblockTime = -1;
6291 blockingWindow.awaitingHttpResponse = false;
6293 blockingWindow = null;
6294 blockSignals(false);