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 QMessageBox.information(this, tr("Encryption Complete"), tr("Encryption is complete"));
866 } catch (SQLException e) {
871 // Decrypt the database upon shutdown
872 private void decryptOnShutdown() {
873 String dbPath= Global.getFileManager().getDbDirPath("");
874 String dbName = "NeverNote";
876 Statement st = conn.getConnection().createStatement();
877 st.execute("shutdown");
878 if (Global.getDatabaseUrl().toUpperCase().indexOf(";CIPHER=AES") > -1)
879 encryptCipher = "AES";
881 encryptCipher = "XTEA";
882 if (QMessageBox.question(this, tr("Confirmation"), tr("Are you sure",
883 "Are you sure you wish to decrypt the database?"),
884 QMessageBox.StandardButton.Yes,
885 QMessageBox.StandardButton.No) == StandardButton.Yes.value()) {
887 ChangeFileEncryption.execute(dbPath, dbName, encryptCipher, Global.cipherPassword.toCharArray(), null, true);
888 Global.setDatabaseUrl("");
889 QMessageBox.information(this, tr("Decryption Complete"), tr("Decryption is complete"));
891 } catch (SQLException e) {
896 * Encrypt/Decrypt the local database
898 public void doDatabaseEncrypt() {
899 // The database is not currently encrypted
900 if (Global.getDatabaseUrl().toUpperCase().indexOf("CIPHER=") == -1) {
901 if (QMessageBox.question(this, tr("Confirmation"), tr("Encrypting the database is used" +
902 "to enhance security and is performed\nupon shutdown, but please be aware that if"+
903 " you lose the password your\nis lost forever.\n\nIt is highly recommended you " +
904 "perform a backup and/or fully synchronize\n prior to executing this funtction.\n\n" +
905 "Do you wish to proceed?"),
906 QMessageBox.StandardButton.Yes,
907 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
910 DBEncryptDialog dialog = new DBEncryptDialog();
912 if (dialog.okPressed()) {
913 Global.cipherPassword = dialog.getPassword();
914 encryptOnShutdown = true;
915 encryptCipher = dialog.getEncryptionMethod();
918 DBEncryptDialog dialog = new DBEncryptDialog();
919 dialog.setWindowTitle(tr("Database Decryption"));
920 dialog.hideEncryption();
922 if (dialog.okPressed()) {
923 if (!dialog.getPassword().equals(Global.cipherPassword)) {
924 QMessageBox.critical(null, tr("Incorrect Password"), tr("Incorrect Password"));
927 decryptOnShutdown = true;
934 private static void initializeGlobalSettings(String[] args) throws InitializationException {
935 StartupConfig startupConfig = new StartupConfig();
937 for (String arg : args) {
938 String lower = arg.toLowerCase();
939 if (lower.startsWith("--name="))
940 startupConfig.setName(arg.substring(arg.indexOf('=') + 1));
941 if (lower.startsWith("--home="))
942 startupConfig.setHomeDirPath(arg.substring(arg.indexOf('=') + 1));
943 if (lower.startsWith("--disable-viewing"))
944 startupConfig.setDisableViewing(true);
946 Global.setup(startupConfig);
951 public void closeEvent(QCloseEvent event) {
952 if (Global.minimizeOnClose() && !closeAction && Global.showTrayIcon()) {
957 logger.log(logger.HIGH, "Entering NeverNote.closeEvent");
960 if (currentNote!= null & browserWindow!=null) {
961 if (!currentNote.getTitle().equals(browserWindow.getTitle()))
962 conn.getNoteTable().updateNoteTitle(currentNote.getGuid(), browserWindow.getTitle());
965 setMessage(tr("Beginning shutdown."));
967 // Close down external windows
968 Collection<ExternalBrowse> windows = externalWindows.values();
969 Iterator<ExternalBrowse> iterator = windows.iterator();
970 while (iterator.hasNext()) {
971 ExternalBrowse browser = iterator.next();
972 browser.windowClosing.disconnect();
977 externalFileEditedSaver();
978 if (Global.isConnected && Global.synchronizeOnClose()) {
979 setMessage(tr("Performing synchronization before closing."));
980 syncRunner.syncNeeded = true;
981 syncRunner.addWork("SYNC");
983 syncRunner.keepRunning = false;
985 syncRunner.addWork("STOP");
986 setMessage("Closing Program.");
987 threadMonitorTimer.stop();
989 thumbnailRunner.addWork("STOP");
990 indexRunner.addWork("STOP");
995 if (tempFiles != null)
998 browserWindow.noteSignal.tagsChanged.disconnect();
999 browserWindow.noteSignal.titleChanged.disconnect();
1000 browserWindow.noteSignal.noteChanged.disconnect();
1001 browserWindow.noteSignal.notebookChanged.disconnect();
1002 browserWindow.noteSignal.createdDateChanged.disconnect();
1003 browserWindow.noteSignal.alteredDateChanged.disconnect();
1004 syncRunner.searchSignal.listChanged.disconnect();
1005 syncRunner.tagSignal.listChanged.disconnect();
1006 syncRunner.notebookSignal.listChanged.disconnect();
1007 syncRunner.noteIndexSignal.listChanged.disconnect();
1010 Global.saveWindowVisible("toolBar", toolBar.isVisible());
1011 saveNoteColumnPositions();
1012 saveNoteIndexWidth();
1014 int width = notebookTree.columnWidth(0);
1015 Global.setColumnWidth("notebookTreeName", width);
1016 width = tagTree.columnWidth(0);
1017 Global.setColumnWidth("tagTreeName", width);
1019 Global.saveWindowMaximized(isMaximized());
1020 Global.saveCurrentNoteGuid(currentNoteGuid);
1022 int sortCol = noteTableView.proxyModel.sortColumn();
1023 int sortOrder = noteTableView.proxyModel.sortOrder().value();
1024 Global.setSortColumn(sortCol);
1025 Global.setSortOrder(sortOrder);
1029 Global.keepRunning = false;
1031 logger.log(logger.MEDIUM, "Waiting for indexThread to stop");
1032 if (indexRunner.thread().isAlive())
1033 indexRunner.thread().join(50);
1034 if (!indexRunner.thread().isAlive())
1035 logger.log(logger.MEDIUM, "Index thread has stopped");
1037 logger.log(logger.MEDIUM, "Index thread still running - interrupting");
1038 indexRunner.thread().interrupt();
1040 } catch (InterruptedException e1) {
1041 e1.printStackTrace();
1044 if (!syncRunner.thread().isAlive()) {
1045 logger.log(logger.MEDIUM, "Waiting for syncThread to stop");
1046 if (syncRunner.thread().isAlive()) {
1047 System.out.println(tr("Synchronizing. Please be patient."));
1048 for(;syncRunner.thread().isAlive();) {
1051 } catch (InterruptedException e) {
1052 e.printStackTrace();
1056 logger.log(logger.MEDIUM, "Sync thread has stopped");
1059 if (encryptOnShutdown) {
1060 encryptOnShutdown();
1062 if (decryptOnShutdown) {
1063 decryptOnShutdown();
1066 Global.getFileManager().purgeResDirectory(false);
1067 } catch (InitializationException e) {
1068 System.out.println(tr("Empty res directory purge failed"));
1069 e.printStackTrace();
1071 logger.log(logger.HIGH, "Leaving NeverNote.closeEvent");
1074 @SuppressWarnings("unused")
1075 private void closeNeverNote() {
1079 public void setMessage(String s) {
1080 logger.log(logger.HIGH, "Entering NeverNote.setMessage");
1083 logger.log(logger.HIGH, "Message: " +s);
1084 statusBar.showMessage(s);
1088 messageTimer.stop();
1089 messageTimer.setSingleShot(true);
1090 messageTimer.start();
1093 logger.log(logger.HIGH, "Leaving NeverNote.setMessage");
1096 private void clearMessage() {
1097 statusBar.clearMessage();
1101 private void waitCursor(boolean wait) {
1103 if (QApplication.overrideCursor() == null)
1104 QApplication.setOverrideCursor(new QCursor(Qt.CursorShape.WaitCursor));
1107 while (QApplication.overrideCursor() != null)
1108 QApplication.restoreOverrideCursor();
1110 listManager.refreshCounters();
1113 private void setupIndexListeners() {
1114 // indexRunner.noteSignal.noteIndexed.connect(this, "indexThreadComplete(String)");
1115 // indexRunner.resourceSignal.resourceIndexed.connect(this, "indexThreadComplete(String)");
1116 indexRunner.signal.indexStarted.connect(this, "indexStarted()");
1117 indexRunner.signal.indexFinished.connect(this, "indexComplete()");
1119 private void setupSyncSignalListeners() {
1120 syncRunner.tagSignal.listChanged.connect(this, "tagIndexUpdated()");
1121 syncRunner.searchSignal.listChanged.connect(this, "savedSearchIndexUpdated()");
1122 syncRunner.notebookSignal.listChanged.connect(this, "notebookIndexUpdated()");
1123 syncRunner.noteIndexSignal.listChanged.connect(this, "noteIndexUpdated(boolean)");
1124 syncRunner.noteSignal.quotaChanged.connect(this, "updateQuotaBar()");
1126 syncRunner.syncSignal.saveUploadAmount.connect(this,"saveUploadAmount(long)");
1127 syncRunner.syncSignal.saveUserInformation.connect(this,"saveUserInformation(User)");
1128 syncRunner.syncSignal.saveEvernoteUpdateCount.connect(this,"saveEvernoteUpdateCount(int)");
1130 syncRunner.noteSignal.guidChanged.connect(this, "noteGuidChanged(String, String)");
1131 syncRunner.noteSignal.noteChanged.connect(this, "invalidateNoteCache(String, String)");
1132 syncRunner.resourceSignal.resourceGuidChanged.connect(this, "noteResourceGuidChanged(String,String,String)");
1133 syncRunner.noteSignal.noteDownloaded.connect(listManager, "noteDownloaded(Note)");
1134 syncRunner.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1136 syncRunner.syncSignal.refreshLists.connect(this, "refreshLists()");
1139 private void setupBrowserSignalListeners() {
1140 setupBrowserWindowListeners(browserWindow, true);
1143 private void setupBrowserWindowListeners(BrowserWindow browser, boolean master) {
1144 browser.fileWatcher.fileChanged.connect(this, "externalFileEdited(String)");
1145 browser.noteSignal.tagsChanged.connect(this, "updateNoteTags(String, List)");
1146 browser.noteSignal.tagsChanged.connect(this, "updateListTags(String, List)");
1147 if (master) browser.noteSignal.noteChanged.connect(this, "setNoteDirty()");
1148 browser.noteSignal.titleChanged.connect(listManager, "updateNoteTitle(String, String)");
1149 browser.noteSignal.titleChanged.connect(this, "updateNoteTitle(String, String)");
1150 browser.noteSignal.notebookChanged.connect(this, "updateNoteNotebook(String, String)");
1151 browser.noteSignal.createdDateChanged.connect(listManager, "updateNoteCreatedDate(String, QDateTime)");
1152 browser.noteSignal.alteredDateChanged.connect(listManager, "updateNoteAlteredDate(String, QDateTime)");
1153 browser.noteSignal.subjectDateChanged.connect(listManager, "updateNoteSubjectDate(String, QDateTime)");
1154 browser.noteSignal.authorChanged.connect(listManager, "updateNoteAuthor(String, String)");
1155 browser.noteSignal.geoChanged.connect(listManager, "updateNoteGeoTag(String, Double,Double,Double)");
1156 browser.noteSignal.geoChanged.connect(this, "setNoteDirty()");
1157 browser.noteSignal.sourceUrlChanged.connect(listManager, "updateNoteSourceUrl(String, String)");
1158 browser.blockApplication.connect(this, "blockApplication(BrowserWindow)");
1159 browser.unblockApplication.connect(this, "unblockApplication()");
1160 if (master) browser.focusLost.connect(this, "saveNote()");
1161 browser.resourceSignal.contentChanged.connect(this, "externalFileEdited(String)");
1162 browser.evernoteLinkClicked.connect(this, "evernoteLinkClick(String, String)");
1165 //**************************************************
1167 //**************************************************
1168 private void setupShortcut(QShortcut action, String text) {
1169 if (!Global.shortcutKeys.containsAction(text))
1171 action.setKey(new QKeySequence(Global.shortcutKeys.getShortcut(text)));
1174 //***************************************************************
1175 //***************************************************************
1176 //* Settings and look & feel
1177 //***************************************************************
1178 //***************************************************************
1179 @SuppressWarnings("unused")
1180 private void settings() {
1181 logger.log(logger.HIGH, "Entering NeverNote.settings");
1182 saveNoteColumnPositions();
1183 saveNoteIndexWidth();
1185 ConfigDialog settings = new ConfigDialog(this);
1186 String dateFormat = Global.getDateFormat();
1187 String timeFormat = Global.getTimeFormat();
1189 indexTime = 1000*Global.getIndexThreadSleepInterval();
1190 indexTimer.start(indexTime); // reset indexing timer
1193 indexRunner.indexAttachmentsLocally = Global.indexAttachmentsLocally();
1194 indexRunner.indexNoteBody = Global.indexNoteBody();
1195 indexRunner.indexNoteTitle = Global.indexNoteTitle();
1196 indexRunner.specialIndexCharacters = Global.getSpecialIndexCharacters();
1197 indexRunner.indexImageRecognition = Global.indexImageRecognition();
1198 if (Global.showTrayIcon())
1203 if (menuBar.showEditorBar.isChecked())
1204 showEditorButtons(browserWindow);
1206 // Reset the save timer
1207 if (Global.getAutoSaveInterval() > 0)
1208 saveTimer.setInterval(1000*60*Global.getAutoSaveInterval());
1213 // Set special reloads
1214 if (settings.getDebugPage().reloadSharedNotebooksClicked()) {
1215 conn.executeSql("Delete from LinkedNotebook");
1216 conn.executeSql("delete from SharedNotebook");
1217 conn.executeSql("Delete from Notebook where linked=true");
1218 conn.executeSql("Insert into Sync (key, value) values ('FullLinkedNotebookSync', 'true')");
1219 conn.executeSql("Insert into Sync (key, value) values ('FullSharedNotebookSync', 'true')");
1224 readOnlyCache.clear();
1225 inkNoteCache.clear();
1226 noteIndexUpdated(true);
1228 logger.log(logger.HIGH, "Leaving NeverNote.settings");
1230 // Restore things to the way they were
1231 private void restoreWindowState(boolean mainWindow) {
1232 // We need to name things or this doesn't work.
1233 setObjectName("NeverNote");
1234 restoreState(Global.restoreState(objectName()));
1235 mainLeftRightSplitter.setObjectName("mainLeftRightSplitter");
1236 browserIndexSplitter.setObjectName("browserIndexSplitter");
1237 leftSplitter1.setObjectName("leftSplitter1");
1239 // Restore the actual positions.
1241 restoreGeometry(Global.restoreGeometry(objectName()));
1242 mainLeftRightSplitter.restoreState(Global.restoreState(mainLeftRightSplitter.objectName()));
1243 browserIndexSplitter.restoreState(Global.restoreState(browserIndexSplitter.objectName()));
1244 leftSplitter1.restoreState(Global.restoreState(leftSplitter1.objectName()));
1247 // Save window positions for the next start
1248 private void saveWindowState() {
1249 Global.saveGeometry(objectName(), saveGeometry());
1250 Global.saveState(mainLeftRightSplitter.objectName(), mainLeftRightSplitter.saveState());
1251 Global.saveState(browserIndexSplitter.objectName(), browserIndexSplitter.saveState());
1252 Global.saveState(leftSplitter1.objectName(), leftSplitter1.saveState());
1253 Global.saveState(objectName(), saveState());
1255 // Load the style sheet
1256 private void loadStyleSheet() {
1257 String styleSheetName = "default.qss";
1258 if (Global.getStyle().equalsIgnoreCase("cleanlooks"))
1259 styleSheetName = "default-cleanlooks.qss";
1260 String fileName = Global.getFileManager().getQssDirPathUser("default.qss");
1261 QFile file = new QFile(fileName);
1263 // If a user default.qss doesn't exist, we use the one shipped with NeverNote
1264 if (!file.exists()) {
1265 fileName = Global.getFileManager().getQssDirPath(styleSheetName);
1266 file = new QFile(fileName);
1268 file.open(OpenModeFlag.ReadOnly);
1269 String styleSheet = file.readAll().toString();
1271 setStyleSheet(styleSheet);
1273 // Save column positions for the next time
1274 private void saveNoteColumnPositions() {
1275 int position = noteTableView.header.visualIndex(Global.noteTableCreationPosition);
1276 Global.setColumnPosition("noteTableCreationPosition", position);
1277 position = noteTableView.header.visualIndex(Global.noteTableTagPosition);
1278 Global.setColumnPosition("noteTableTagPosition", position);
1279 position = noteTableView.header.visualIndex(Global.noteTableNotebookPosition);
1280 Global.setColumnPosition("noteTableNotebookPosition", position);
1281 position = noteTableView.header.visualIndex(Global.noteTableChangedPosition);
1282 Global.setColumnPosition("noteTableChangedPosition", position);
1283 position = noteTableView.header.visualIndex(Global.noteTableAuthorPosition);
1284 Global.setColumnPosition("noteTableAuthorPosition", position);
1285 position = noteTableView.header.visualIndex(Global.noteTableSourceUrlPosition);
1286 Global.setColumnPosition("noteTableSourceUrlPosition", position);
1287 position = noteTableView.header.visualIndex(Global.noteTableSubjectDatePosition);
1288 Global.setColumnPosition("noteTableSubjectDatePosition", position);
1289 position = noteTableView.header.visualIndex(Global.noteTableTitlePosition);
1290 Global.setColumnPosition("noteTableTitlePosition", position);
1291 position = noteTableView.header.visualIndex(Global.noteTableSynchronizedPosition);
1292 Global.setColumnPosition("noteTableSynchronizedPosition", position);
1293 position = noteTableView.header.visualIndex(Global.noteTableGuidPosition);
1294 Global.setColumnPosition("noteTableGuidPosition", position);
1295 position = noteTableView.header.visualIndex(Global.noteTableThumbnailPosition);
1296 Global.setColumnPosition("noteTableThumbnailPosition", position);
1299 // Save column widths for the next time
1300 private void saveNoteIndexWidth() {
1302 width = noteTableView.getColumnWidth(Global.noteTableCreationPosition);
1303 Global.setColumnWidth("noteTableCreationPosition", width);
1304 width = noteTableView.getColumnWidth(Global.noteTableChangedPosition);
1305 Global.setColumnWidth("noteTableChangedPosition", width);
1306 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1307 Global.setColumnWidth("noteTableGuidPosition", width);
1308 width = noteTableView.getColumnWidth(Global.noteTableNotebookPosition);
1309 Global.setColumnWidth("noteTableNotebookPosition", width);
1310 width = noteTableView.getColumnWidth(Global.noteTableTagPosition);
1311 Global.setColumnWidth("noteTableTagPosition", width);
1312 width = noteTableView.getColumnWidth(Global.noteTableTitlePosition);
1313 Global.setColumnWidth("noteTableTitlePosition", width);
1314 width = noteTableView.getColumnWidth(Global.noteTableSourceUrlPosition);
1315 Global.setColumnWidth("noteTableSourceUrlPosition", width);
1316 width = noteTableView.getColumnWidth(Global.noteTableAuthorPosition);
1317 Global.setColumnWidth("noteTableAuthorPosition", width);
1318 width = noteTableView.getColumnWidth(Global.noteTableSubjectDatePosition);
1319 Global.setColumnWidth("noteTableSubjectDatePosition", width);
1320 width = noteTableView.getColumnWidth(Global.noteTableSynchronizedPosition);
1321 Global.setColumnWidth("noteTableSynchronizedPosition", width);
1322 width = noteTableView.getColumnWidth(Global.noteTableThumbnailPosition);
1323 Global.setColumnWidth("noteTableThumbnailPosition", width);
1324 width = noteTableView.getColumnWidth(Global.noteTableGuidPosition);
1325 Global.setColumnWidth("noteTableGuidPosition", width);
1328 @SuppressWarnings("unused")
1329 private void toggleSearchWindow() {
1330 logger.log(logger.HIGH, "Entering NeverNote.toggleSearchWindow");
1331 searchLayout.toggleSearchField();
1332 menuBar.hideSearch.setChecked(searchField.isVisible());
1333 Global.saveWindowVisible("searchField", searchField.isVisible());
1334 logger.log(logger.HIGH, "Leaving NeverNote.toggleSearchWindow");
1336 @SuppressWarnings("unused")
1337 private void toggleQuotaWindow() {
1338 logger.log(logger.HIGH, "Entering NeverNote.toggleQuotaWindow");
1339 searchLayout.toggleQuotaBar();
1340 menuBar.hideQuota.setChecked(quotaBar.isVisible());
1341 Global.saveWindowVisible("quota", quotaBar.isVisible());
1342 logger.log(logger.HIGH, "Leaving NeverNote.toggleQuotaWindow");
1344 @SuppressWarnings("unused")
1345 private void toggleZoomWindow() {
1346 logger.log(logger.HIGH, "Entering NeverNote.toggleZoomWindow");
1347 searchLayout.toggleZoom();
1348 menuBar.hideZoom.setChecked(zoomSpinner.isVisible());
1349 Global.saveWindowVisible("zoom", zoomSpinner.isVisible());
1350 logger.log(logger.HIGH, "Leaving NeverNote.toggleZoomWindow");
1355 //***************************************************************
1356 //***************************************************************
1357 //** These functions deal with Notebook menu items
1358 //***************************************************************
1359 //***************************************************************
1360 // Setup the tree containing the user's notebooks.
1361 private void initializeNotebookTree() {
1362 logger.log(logger.HIGH, "Entering NeverNote.initializeNotebookTree");
1363 // notebookTree.itemClicked.connect(this, "notebookTreeSelection()");
1364 notebookTree.selectionSignal.connect(this, "notebookTreeSelection()");
1365 listManager.notebookSignal.refreshNotebookTreeCounts.connect(notebookTree, "updateCounts(List, List)");
1366 logger.log(logger.HIGH, "Leaving NeverNote.initializeNotebookTree");
1368 // Listener when a notebook is selected
1369 private void notebookTreeSelection() {
1370 logger.log(logger.HIGH, "Entering NeverNote.notebookTreeSelection");
1373 clearAttributeFilter();
1374 clearSavedSearchFilter();
1375 if (Global.mimicEvernoteInterface) {
1377 searchField.clear();
1379 menuBar.noteRestoreAction.setVisible(false);
1380 menuBar.notebookEditAction.setEnabled(true);
1381 menuBar.notebookDeleteAction.setEnabled(true);
1382 menuBar.notebookPublishAction.setEnabled(true);
1383 menuBar.notebookShareAction.setEnabled(true);
1384 menuBar.notebookIconAction.setEnabled(true);
1385 menuBar.notebookStackAction.setEnabled(true);
1386 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1387 selectedNotebookGUIDs.clear();
1389 String stackName = "";
1390 if (selections.size() > 0) {
1391 guid = (selections.get(0).text(2));
1392 stackName = selections.get(0).text(0);
1394 if (!Global.mimicEvernoteInterface) {
1395 // If no notebooks are selected, we make it look like the "all notebooks" one was selected
1396 if (selections.size()==0) {
1397 selectedNotebookGUIDs.clear();
1398 for (int i=0; i < listManager.getNotebookIndex().size(); i++) {
1399 selectedNotebookGUIDs.add(listManager.getNotebookIndex().get(i).getGuid());
1401 menuBar.notebookEditAction.setEnabled(false);
1402 menuBar.notebookDeleteAction.setEnabled(false);
1403 menuBar.notebookStackAction.setEnabled(false);
1404 menuBar.notebookIconAction.setEnabled(false);
1407 if (!guid.equals("") && !guid.equals("STACK")) {
1408 selectedNotebookGUIDs.add(guid);
1409 menuBar.notebookIconAction.setEnabled(true);
1411 menuBar.notebookIconAction.setEnabled(true);
1412 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1413 Notebook book = listManager.getNotebookIndex().get(j);
1414 if (book.getStack() != null && book.getStack().equalsIgnoreCase(stackName))
1415 selectedNotebookGUIDs.add(book.getGuid());
1418 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1419 listManager.loadNotesIndex();
1420 noteIndexUpdated(false);
1421 refreshEvernoteNote(true);
1422 listManager.refreshCounters = true;
1423 listManager.refreshCounters();
1424 logger.log(logger.HIGH, "Leaving NeverNote.notebookTreeSelection");
1427 private void clearNotebookFilter() {
1428 notebookTree.blockSignals(true);
1429 notebookTree.clearSelection();
1430 menuBar.noteRestoreAction.setVisible(false);
1431 menuBar.notebookEditAction.setEnabled(false);
1432 menuBar.notebookDeleteAction.setEnabled(false);
1433 selectedNotebookGUIDs.clear();
1434 listManager.setSelectedNotebooks(selectedNotebookGUIDs);
1435 notebookTree.blockSignals(false);
1437 // Triggered when the notebook DB has been updated
1438 private void notebookIndexUpdated() {
1439 logger.log(logger.HIGH, "Entering NeverNote.notebookIndexUpdated");
1441 // Get the possible icons
1442 HashMap<String, QIcon> icons = conn.getNotebookTable().getAllIcons();
1443 notebookTree.setIcons(icons);
1445 if (selectedNotebookGUIDs == null)
1446 selectedNotebookGUIDs = new ArrayList<String>();
1447 List<Notebook> books = conn.getNotebookTable().getAll();
1448 for (int i=books.size()-1; i>=0; i--) {
1449 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1450 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(books.get(i).getGuid())) {
1452 j=listManager.getArchiveNotebookIndex().size();
1458 listManager.countNotebookResults(listManager.getNoteIndex());
1459 notebookTree.blockSignals(true);
1460 notebookTree.load(books, listManager.getLocalNotebooks());
1461 for (int i=selectedNotebookGUIDs.size()-1; i>=0; i--) {
1462 boolean found = notebookTree.selectGuid(selectedNotebookGUIDs.get(i));
1464 selectedNotebookGUIDs.remove(i);
1466 listManager.refreshCounters = true;
1467 listManager.refreshCounters();
1468 notebookTree.blockSignals(false);
1470 logger.log(logger.HIGH, "Leaving NeverNote.notebookIndexUpdated");
1472 // Show/Hide note information
1473 @SuppressWarnings("unused")
1474 private void toggleNotebookWindow() {
1475 logger.log(logger.HIGH, "Entering NeverNote.toggleNotebookWindow");
1476 searchLayout.toggleNotebook();
1477 menuBar.hideNotebooks.setChecked(notebookTree.isVisible());
1478 Global.saveWindowVisible("notebookTree", notebookTree.isVisible());
1479 logger.log(logger.HIGH, "Leaving NeverNote.toggleNotebookWindow");
1481 // Add a new notebook
1482 @SuppressWarnings("unused")
1483 private void addNotebook() {
1484 logger.log(logger.HIGH, "Inside NeverNote.addNotebook");
1485 NotebookEdit edit = new NotebookEdit();
1486 edit.setNotebooks(listManager.getNotebookIndex());
1489 if (!edit.okPressed())
1492 Calendar currentTime = new GregorianCalendar();
1493 Long l = new Long(currentTime.getTimeInMillis());
1494 String randint = new String(Long.toString(l));
1496 Notebook newBook = new Notebook();
1497 newBook.setUpdateSequenceNum(0);
1498 newBook.setGuid(randint);
1499 newBook.setName(edit.getNotebook());
1500 newBook.setServiceCreated(new Date().getTime());
1501 newBook.setServiceUpdated(new Date().getTime());
1502 newBook.setDefaultNotebook(false);
1503 newBook.setPublished(false);
1505 listManager.getNotebookIndex().add(newBook);
1507 listManager.getLocalNotebooks().add(newBook.getGuid());
1508 conn.getNotebookTable().addNotebook(newBook, true, edit.isLocal());
1509 notebookIndexUpdated();
1510 listManager.countNotebookResults(listManager.getNoteIndex());
1511 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1512 logger.log(logger.HIGH, "Leaving NeverNote.addNotebook");
1514 // Edit an existing notebook
1515 @SuppressWarnings("unused")
1516 private void stackNotebook() {
1517 logger.log(logger.HIGH, "Entering NeverNote.stackNotebook");
1518 StackNotebook edit = new StackNotebook();
1520 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1521 QTreeWidgetItem currentSelection;
1522 for (int i=0; i<selections.size(); i++) {
1523 currentSelection = selections.get(0);
1524 String guid = currentSelection.text(2);
1525 if (guid.equalsIgnoreCase("")) {
1526 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack the \"All Notebooks\" item."));
1529 if (guid.equalsIgnoreCase("STACK")) {
1530 QMessageBox.critical(this, tr("Unable To Stack") ,tr("You can't stack a stack."));
1535 edit.setStackNames(conn.getNotebookTable().getAllStackNames());
1540 if (!edit.okPressed())
1543 String stack = edit.getStackName();
1545 for (int i=0; i<selections.size(); i++) {
1546 currentSelection = selections.get(i);
1547 String guid = currentSelection.text(2);
1548 listManager.updateNotebookStack(guid, stack);
1550 notebookIndexUpdated();
1551 logger.log(logger.HIGH, "Leaving NeverNote.stackNotebook");
1553 // Edit an existing notebook
1554 @SuppressWarnings("unused")
1555 private void editNotebook() {
1556 logger.log(logger.HIGH, "Entering NeverNote.editNotebook");
1557 NotebookEdit edit = new NotebookEdit();
1559 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1560 QTreeWidgetItem currentSelection;
1561 currentSelection = selections.get(0);
1562 edit.setNotebook(currentSelection.text(0));
1564 String guid = currentSelection.text(2);
1565 if (!guid.equalsIgnoreCase("STACK")) {
1566 edit.setTitle(tr("Edit Notebook"));
1567 edit.setNotebooks(listManager.getNotebookIndex());
1568 edit.setLocalCheckboxEnabled(false);
1569 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1570 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1571 edit.setDefaultNotebook(listManager.getNotebookIndex().get(i).isDefaultNotebook());
1572 i=listManager.getNotebookIndex().size();
1576 edit.setTitle(tr("Edit Stack"));
1577 edit.setStacks(conn.getNotebookTable().getAllStackNames());
1578 edit.hideLocalCheckbox();
1579 edit.hideDefaultCheckbox();
1584 if (!edit.okPressed())
1588 if (guid.equalsIgnoreCase("STACK")) {
1589 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1590 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1591 if (listManager.getNotebookIndex().get(j).getStack() != null &&
1592 listManager.getNotebookIndex().get(j).getStack().equalsIgnoreCase(currentSelection.text(0)))
1593 listManager.getNotebookIndex().get(j).setStack(edit.getNotebook());
1595 conn.getNotebookTable().renameStacks(currentSelection.text(0), edit.getNotebook());
1596 currentSelection.setText(0, edit.getNotebook());
1600 updateListNotebookName(currentSelection.text(0), edit.getNotebook());
1601 currentSelection.setText(0, edit.getNotebook());
1603 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1604 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1605 listManager.getNotebookIndex().get(i).setName(edit.getNotebook());
1606 if (!listManager.getNotebookIndex().get(i).isDefaultNotebook() && edit.isDefaultNotebook()) {
1607 for (int j=0; j<listManager.getNotebookIndex().size(); j++)
1608 listManager.getNotebookIndex().get(j).setDefaultNotebook(false);
1609 listManager.getNotebookIndex().get(i).setDefaultNotebook(true);
1610 conn.getNotebookTable().setDefaultNotebook(listManager.getNotebookIndex().get(i).getGuid());
1612 conn.getNotebookTable().updateNotebook(listManager.getNotebookIndex().get(i), true);
1613 if (conn.getNotebookTable().isLinked(listManager.getNotebookIndex().get(i).getGuid())) {
1614 LinkedNotebook linkedNotebook = conn.getLinkedNotebookTable().getByNotebookGuid(listManager.getNotebookIndex().get(i).getGuid());
1615 linkedNotebook.setShareName(edit.getNotebook());
1616 conn.getLinkedNotebookTable().updateNotebook(linkedNotebook, true);
1618 i=listManager.getNotebookIndex().size();
1622 // Build a list of non-closed notebooks
1623 List<Notebook> nbooks = new ArrayList<Notebook>();
1624 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1625 boolean found=false;
1626 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1627 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1631 nbooks.add(listManager.getNotebookIndex().get(i));
1635 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1636 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1637 browserWindow.setNotebookList(filteredBooks);
1638 Iterator<String> set = externalWindows.keySet().iterator();
1639 while(set.hasNext())
1640 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1641 logger.log(logger.HIGH, "Leaving NeverNote.editNotebook");
1643 // Publish a notebook
1644 @SuppressWarnings("unused")
1645 private void publishNotebook() {
1646 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1647 QTreeWidgetItem currentSelection;
1648 currentSelection = selections.get(0);
1649 String guid = currentSelection.text(2);
1651 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1656 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1657 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1658 n = listManager.getNotebookIndex().get(i);
1660 i = listManager.getNotebookIndex().size();
1666 PublishNotebook publish = new PublishNotebook(Global.username, Global.getServer(), n);
1669 if (!publish.okClicked())
1672 Publishing p = publish.getPublishing();
1673 boolean isPublished = !publish.isStopPressed();
1674 conn.getNotebookTable().setPublishing(n.getGuid(), isPublished, p);
1675 n.setPublished(isPublished);
1677 listManager.getNotebookIndex().set(position, n);
1678 notebookIndexUpdated();
1680 // Publish a notebook
1681 @SuppressWarnings("unused")
1682 private void shareNotebook() {
1683 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1684 QTreeWidgetItem currentSelection;
1685 currentSelection = selections.get(0);
1686 String guid = currentSelection.text(2);
1688 if (guid.equalsIgnoreCase("STACK") || guid.equalsIgnoreCase(""))
1692 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1693 if (guid.equals(listManager.getNotebookIndex().get(i).getGuid())) {
1694 n = listManager.getNotebookIndex().get(i);
1695 i = listManager.getNotebookIndex().size();
1699 String authToken = null;
1700 if (syncRunner.isConnected)
1701 authToken = syncRunner.authToken;
1702 ShareNotebook share = new ShareNotebook(n.getName(), conn, n, syncRunner);
1707 // Delete an existing notebook
1708 @SuppressWarnings("unused")
1709 private void deleteNotebook() {
1710 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1711 boolean stacksFound = false;
1712 boolean notebooksFound = false;
1713 boolean assigned = false;
1714 // Check if any notes have this notebook
1715 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1716 for (int i=0; i<selections.size(); i++) {
1717 QTreeWidgetItem currentSelection;
1718 currentSelection = selections.get(i);
1719 String guid = currentSelection.text(2);
1720 if (!guid.equalsIgnoreCase("STACK")) {
1721 notebooksFound = true;
1722 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
1723 String noteGuid = listManager.getNoteIndex().get(j).getNotebookGuid();
1724 if (noteGuid.equals(guid)) {
1726 j=listManager.getNoteIndex().size();
1727 i=selections.size();
1735 QMessageBox.information(this, tr("Unable to Delete"), tr("Some of the selected notebook(s) contain notes.\n"+
1736 "Please delete the notes or move them to another notebook before deleting any notebooks."));
1740 if (conn.getNotebookTable().getAll().size() == 1) {
1741 QMessageBox.information(this, tr("Unable to Delete"), tr("You must have at least one notebook."));
1745 // If all notebooks are clear, verify the delete
1746 String msg1 = new String(tr("Delete selected notebooks?"));
1747 String msg2 = new String(tr("Remove selected stacks (notebooks will not be deleted)?"));
1748 String msg3 = new String(tr("Delete selected notebooks & remove stacks? Notebooks under the stacks are" +
1749 " not deleted unless selected?"));
1751 if (stacksFound && notebooksFound)
1753 if (!stacksFound && notebooksFound)
1755 if (stacksFound && !notebooksFound)
1757 if (QMessageBox.question(this, tr("Confirmation"), msg,
1758 QMessageBox.StandardButton.Yes,
1759 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
1763 // If confirmed, delete the notebook
1764 for (int i=selections.size()-1; i>=0; i--) {
1765 QTreeWidgetItem currentSelection;
1766 currentSelection = selections.get(i);
1767 String guid = currentSelection.text(2);
1768 if (currentSelection.text(2).equalsIgnoreCase("STACK")) {
1769 conn.getNotebookTable().renameStacks(currentSelection.text(0), "");
1770 listManager.renameStack(currentSelection.text(0), "");
1772 conn.getNotebookTable().expungeNotebook(guid, true);
1773 listManager.deleteNotebook(guid);
1777 notebookIndexUpdated();
1778 // notebookTreeSelection();
1779 // notebookTree.load(listManager.getNotebookIndex(), listManager.getLocalNotebooks());
1780 // listManager.countNotebookResults(listManager.getNoteIndex());
1781 logger.log(logger.HIGH, "Entering NeverNote.deleteNotebook");
1783 // A note's notebook has been updated
1784 @SuppressWarnings("unused")
1785 private void updateNoteNotebook(String guid, String notebookGuid) {
1787 // Update the list manager
1788 listManager.updateNoteNotebook(guid, notebookGuid);
1789 listManager.countNotebookResults(listManager.getNoteIndex());
1790 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
1792 // Find the name of the notebook
1793 String notebookName = null;
1794 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1795 if (listManager.getNotebookIndex().get(i).getGuid().equals(notebookGuid)) {
1796 notebookName = listManager.getNotebookIndex().get(i).getName();
1801 // If we found the name, update the browser window
1802 if (notebookName != null) {
1803 updateListNoteNotebook(guid, notebookName);
1804 if (guid.equals(currentNoteGuid)) {
1805 int pos = browserWindow.notebookBox.findText(notebookName);
1807 browserWindow.notebookBox.setCurrentIndex(pos);
1811 // If we're dealing with the current note, then we need to be sure and update the notebook there
1812 if (guid.equals(currentNoteGuid)) {
1813 if (currentNote != null) {
1814 currentNote.setNotebookGuid(notebookGuid);
1818 // Open/close notebooks
1819 @SuppressWarnings("unused")
1820 private void closeNotebooks() {
1821 NotebookArchive na = new NotebookArchive(listManager.getNotebookIndex(), listManager.getArchiveNotebookIndex());
1823 if (!na.okClicked())
1827 listManager.getArchiveNotebookIndex().clear();
1829 for (int i=na.getClosedBookList().count()-1; i>=0; i--) {
1830 String text = na.getClosedBookList().takeItem(i).text();
1831 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1832 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1833 Notebook n = listManager.getNotebookIndex().get(j);
1834 conn.getNotebookTable().setArchived(n.getGuid(),true);
1835 listManager.getArchiveNotebookIndex().add(n);
1836 j=listManager.getNotebookIndex().size();
1841 for (int i=na.getOpenBookList().count()-1; i>=0; i--) {
1842 String text = na.getOpenBookList().takeItem(i).text();
1843 for (int j=0; j<listManager.getNotebookIndex().size(); j++) {
1844 if (listManager.getNotebookIndex().get(j).getName().equalsIgnoreCase(text)) {
1845 Notebook n = listManager.getNotebookIndex().get(j);
1846 conn.getNotebookTable().setArchived(n.getGuid(),false);
1847 j=listManager.getNotebookIndex().size();
1851 notebookTreeSelection();
1852 listManager.loadNotesIndex();
1853 notebookIndexUpdated();
1854 noteIndexUpdated(false);
1855 reloadTagTree(true);
1856 // noteIndexUpdated(false);
1858 // Build a list of non-closed notebooks
1859 List<Notebook> nbooks = new ArrayList<Notebook>();
1860 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
1861 boolean found=false;
1862 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
1863 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
1867 nbooks.add(listManager.getNotebookIndex().get(i));
1870 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
1871 List<Notebook> filteredBooks = notebookFilter.getValidNotebooks(currentNote, listManager.getNotebookIndex());
1872 browserWindow.setNotebookList(filteredBooks);
1874 // Update any external windows
1875 Iterator<String> set = externalWindows.keySet().iterator();
1876 while(set.hasNext())
1877 externalWindows.get(set.next()).getBrowserWindow().setNotebookList(filteredBooks);
1881 // Change the notebook's icon
1882 @SuppressWarnings("unused")
1883 private void setNotebookIcon() {
1884 boolean stackSelected = false;
1885 boolean allNotebookSelected = false;
1887 QTreeWidgetItem currentSelection;
1888 List<QTreeWidgetItem> selections = notebookTree.selectedItems();
1889 if (selections.size() == 0)
1892 currentSelection = selections.get(0);
1893 String guid = currentSelection.text(2);
1894 if (guid.equalsIgnoreCase(""))
1895 allNotebookSelected = true;
1896 if (guid.equalsIgnoreCase("STACK"))
1897 stackSelected = true;
1899 QIcon currentIcon = currentSelection.icon(0);
1903 if (!stackSelected && !allNotebookSelected) {
1904 icon = conn.getNotebookTable().getIcon(guid);
1906 dialog = new SetIcon(currentIcon, saveLastPath);
1907 dialog.setUseDefaultIcon(true);
1909 dialog = new SetIcon(icon, saveLastPath);
1910 dialog.setUseDefaultIcon(false);
1913 if (stackSelected) {
1914 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "STACK");
1916 icon = conn.getSystemIconTable().getIcon(currentSelection.text(0), "ALLNOTEBOOK");
1919 dialog = new SetIcon(currentIcon, saveLastPath);
1920 dialog.setUseDefaultIcon(true);
1922 dialog = new SetIcon(icon, saveLastPath);
1923 dialog.setUseDefaultIcon(false);
1927 if (dialog.okPressed()) {
1928 saveLastPath = dialog.getPath();
1930 QIcon newIcon = dialog.getIcon();
1931 if (stackSelected) {
1932 conn.getSystemIconTable().setIcon(currentSelection.text(0), "STACK", newIcon, dialog.getFileType());
1933 if (newIcon == null) {
1934 newIcon = new QIcon(iconPath+"books2.png");
1936 currentSelection.setIcon(0,newIcon);
1939 if (allNotebookSelected) {
1940 conn.getSystemIconTable().setIcon(currentSelection.text(0), "ALLNOTEBOOK", newIcon, dialog.getFileType());
1941 if (newIcon == null) {
1942 newIcon = new QIcon(iconPath+"notebook-green.png");
1944 currentSelection.setIcon(0,newIcon);
1947 conn.getNotebookTable().setIcon(guid, newIcon, dialog.getFileType());
1948 if (newIcon == null) {
1949 boolean isPublished = false;;
1950 boolean found = false;
1951 for (int i=0; i<listManager.getNotebookIndex().size() && !found; i++) {
1952 if (listManager.getNotebookIndex().get(i).getGuid().equals(guid)) {
1953 isPublished = listManager.getNotebookIndex().get(i).isPublished();
1957 newIcon = notebookTree.findDefaultIcon(guid, currentSelection.text(1), listManager.getLocalNotebooks(), isPublished);
1959 currentSelection.setIcon(0, newIcon);
1965 //***************************************************************
1966 //***************************************************************
1967 //** These functions deal with Tag menu items
1968 //***************************************************************
1969 //***************************************************************
1970 // Add a new notebook
1971 @SuppressWarnings("unused")
1972 private void addTag() {
1973 logger.log(logger.HIGH, "Inside NeverNote.addTag");
1974 TagEdit edit = new TagEdit();
1975 edit.setTagList(listManager.getTagIndex());
1977 List<QTreeWidgetItem> selections = tagTree.selectedItems();
1978 QTreeWidgetItem currentSelection = null;
1979 if (selections.size() > 0) {
1980 currentSelection = selections.get(0);
1981 edit.setParentTag(currentSelection.text(0));
1986 if (!edit.okPressed())
1989 Calendar currentTime = new GregorianCalendar();
1990 Long l = new Long(currentTime.getTimeInMillis());
1991 String randint = new String(Long.toString(l));
1993 Tag newTag = new Tag();
1994 newTag.setUpdateSequenceNum(0);
1995 newTag.setGuid(randint);
1996 newTag.setName(edit.getTag());
1997 if (edit.getParentTag().isChecked()) {
1998 newTag.setParentGuid(currentSelection.text(2));
1999 newTag.setParentGuidIsSet(true);
2000 currentSelection.setExpanded(true);
2002 conn.getTagTable().addTag(newTag, true);
2003 listManager.getTagIndex().add(newTag);
2004 reloadTagTree(true);
2006 logger.log(logger.HIGH, "Leaving NeverNote.addTag");
2008 @SuppressWarnings("unused")
2009 private void reloadTagTree() {
2010 reloadTagTree(false);
2012 private void reloadTagTree(boolean reload) {
2013 logger.log(logger.HIGH, "Entering NeverNote.reloadTagTree");
2014 tagIndexUpdated(reload);
2015 boolean filter = false;
2017 listManager.countTagResults(listManager.getNoteIndex());
2018 if (notebookTree.selectedItems().size() > 0
2019 && !notebookTree.selectedItems().get(0).text(0).equalsIgnoreCase("All Notebooks"))
2021 if (tagTree.selectedItems().size() > 0)
2023 tagTree.showAllTags(!filter);
2024 logger.log(logger.HIGH, "Leaving NeverNote.reloadTagTree");
2026 // Edit an existing tag
2027 @SuppressWarnings("unused")
2028 private void editTag() {
2029 logger.log(logger.HIGH, "Entering NeverNote.editTag");
2030 TagEdit edit = new TagEdit();
2031 edit.setTitle("Edit Tag");
2032 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2033 QTreeWidgetItem currentSelection;
2034 currentSelection = selections.get(0);
2035 edit.setTag(currentSelection.text(0));
2036 edit.setTagList(listManager.getTagIndex());
2039 if (!edit.okPressed())
2042 String guid = currentSelection.text(2);
2043 currentSelection.setText(0,edit.getTag());
2045 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2046 if (listManager.getTagIndex().get(i).getGuid().equals(guid)) {
2047 listManager.getTagIndex().get(i).setName(edit.getTag());
2048 conn.getTagTable().updateTag(listManager.getTagIndex().get(i), true);
2049 updateListTagName(guid);
2050 if (currentNote != null && currentNote.getTagGuids().contains(guid))
2051 browserWindow.setTag(getTagNamesForNote(currentNote));
2052 logger.log(logger.HIGH, "Leaving NeverNote.editTag");
2056 browserWindow.setTag(getTagNamesForNote(currentNote));
2057 logger.log(logger.HIGH, "Leaving NeverNote.editTag...");
2059 // Delete an existing tag
2060 @SuppressWarnings("unused")
2061 private void deleteTag() {
2062 logger.log(logger.HIGH, "Entering NeverNote.deleteTag");
2064 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected tags?"),
2065 QMessageBox.StandardButton.Yes,
2066 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2070 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2071 for (int i=selections.size()-1; i>=0; i--) {
2072 QTreeWidgetItem currentSelection;
2073 currentSelection = selections.get(i);
2074 removeTagItem(currentSelection.text(2));
2076 tagIndexUpdated(true);
2078 listManager.countTagResults(listManager.getNoteIndex());
2079 // tagTree.updateCounts(listManager.getTagCounter());
2080 logger.log(logger.HIGH, "Leaving NeverNote.deleteTag");
2082 // Remove a tag tree item. Go recursively down & remove the children too
2083 private void removeTagItem(String guid) {
2084 for (int j=listManager.getTagIndex().size()-1; j>=0; j--) {
2085 String parent = listManager.getTagIndex().get(j).getParentGuid();
2086 if (parent != null && parent.equals(guid)) {
2087 //Remove this tag's children
2088 removeTagItem(listManager.getTagIndex().get(j).getGuid());
2091 //Now, remove this tag
2092 removeListTagName(guid);
2093 conn.getTagTable().expungeTag(guid, true);
2094 for (int a=0; a<listManager.getTagIndex().size(); a++) {
2095 if (listManager.getTagIndex().get(a).getGuid().equals(guid)) {
2096 listManager.getTagIndex().remove(a);
2101 // Setup the tree containing the user's tags
2102 private void initializeTagTree() {
2103 logger.log(logger.HIGH, "Entering NeverNote.initializeTagTree");
2104 // tagTree.itemSelectionChanged.connect(this, "tagTreeSelection()");
2105 // tagTree.itemClicked.connect(this, "tagTreeSelection()");
2106 tagTree.selectionSignal.connect(this, "tagTreeSelection()");
2107 listManager.tagSignal.refreshTagTreeCounts.connect(tagTree, "updateCounts(List)");
2108 logger.log(logger.HIGH, "Leaving NeverNote.initializeTagTree");
2110 // Listener when a tag is selected
2111 private void tagTreeSelection() {
2112 logger.log(logger.HIGH, "Entering NeverNote.tagTreeSelection");
2115 clearAttributeFilter();
2116 clearSavedSearchFilter();
2118 menuBar.noteRestoreAction.setVisible(false);
2120 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2121 QTreeWidgetItem currentSelection;
2122 selectedTagGUIDs.clear();
2123 for (int i=0; i<selections.size(); i++) {
2124 currentSelection = selections.get(i);
2125 selectedTagGUIDs.add(currentSelection.text(2));
2127 if (selections.size() > 0) {
2128 menuBar.tagEditAction.setEnabled(true);
2129 menuBar.tagDeleteAction.setEnabled(true);
2130 menuBar.tagIconAction.setEnabled(true);
2133 menuBar.tagEditAction.setEnabled(false);
2134 menuBar.tagDeleteAction.setEnabled(false);
2135 menuBar.tagIconAction.setEnabled(true);
2137 if (selections.size() > 1)
2138 menuBar.tagMergeAction.setEnabled(true);
2140 menuBar.tagMergeAction.setEnabled(false);
2141 listManager.setSelectedTags(selectedTagGUIDs);
2142 listManager.loadNotesIndex();
2143 noteIndexUpdated(false);
2144 refreshEvernoteNote(true);
2145 listManager.refreshCounters = true;
2146 listManager.refreshCounters();
2147 logger.log(logger.HIGH, "Leaving NeverNote.tagTreeSelection");
2149 // trigger the tag index to be refreshed
2150 @SuppressWarnings("unused")
2151 private void tagIndexUpdated() {
2152 tagIndexUpdated(true);
2154 private void tagIndexUpdated(boolean reload) {
2155 logger.log(logger.HIGH, "Entering NeverNote.tagIndexUpdated");
2156 if (selectedTagGUIDs == null)
2157 selectedTagGUIDs = new ArrayList<String>();
2159 listManager.reloadTagIndex();
2161 tagTree.blockSignals(true);
2163 tagTree.setIcons(conn.getTagTable().getAllIcons());
2164 tagTree.load(listManager.getTagIndex());
2167 for (int i=selectedTagGUIDs.size()-1; i>=0; i--) {
2168 boolean found = tagTree.selectGuid(selectedTagGUIDs.get(i));
2170 selectedTagGUIDs.remove(i);
2172 tagTree.blockSignals(false);
2174 browserWindow.setTag(getTagNamesForNote(currentNote));
2175 logger.log(logger.HIGH, "Leaving NeverNote.tagIndexUpdated");
2177 // Show/Hide note information
2178 @SuppressWarnings("unused")
2179 private void toggleTagWindow() {
2180 logger.log(logger.HIGH, "Entering NeverNote.toggleTagWindow");
2181 if (tagTree.isVisible())
2185 menuBar.hideTags.setChecked(tagTree.isVisible());
2186 Global.saveWindowVisible("tagTree", tagTree.isVisible());
2187 logger.log(logger.HIGH, "Leaving NeverNote.toggleTagWindow");
2189 // A note's tags have been updated
2190 @SuppressWarnings("unused")
2191 private void updateNoteTags(String guid, List<String> tags) {
2192 // Save any new tags. We'll need them later.
2193 List<String> newTags = new ArrayList<String>();
2194 for (int i=0; i<tags.size(); i++) {
2195 if (conn.getTagTable().findTagByName(tags.get(i))==null)
2196 newTags.add(tags.get(i));
2199 listManager.saveNoteTags(guid, tags);
2200 listManager.countTagResults(listManager.getNoteIndex());
2201 StringBuffer names = new StringBuffer("");
2202 for (int i=0; i<tags.size(); i++) {
2203 names = names.append(tags.get(i));
2204 if (i<tags.size()-1) {
2205 names.append(Global.tagDelimeter + " ");
2208 browserWindow.setTag(names.toString());
2211 // Now, we need to add any new tags to the tag tree
2212 for (int i=0; i<newTags.size(); i++)
2213 tagTree.insertTag(newTags.get(i), conn.getTagTable().findTagByName(newTags.get(i)));
2215 // Get a string containing all tag names for a note
2216 private String getTagNamesForNote(Note n) {
2217 logger.log(logger.HIGH, "Entering NeverNote.getTagNamesForNote");
2218 if (n==null || n.getGuid() == null || n.getGuid().equals(""))
2220 StringBuffer buffer = new StringBuffer(100);
2221 Vector<String> v = new Vector<String>();
2222 List<String> guids = n.getTagGuids();
2227 for (int i=0; i<guids.size(); i++) {
2228 v.add(listManager.getTagNameByGuid(guids.get(i)));
2230 Comparator<String> comparator = Collections.reverseOrder();
2231 Collections.sort(v,comparator);
2232 Collections.reverse(v);
2234 for (int i = 0; i<v.size(); i++) {
2236 buffer.append(", ");
2237 buffer.append(v.get(i));
2240 logger.log(logger.HIGH, "Leaving NeverNote.getTagNamesForNote");
2241 return buffer.toString();
2243 // Tags were added via dropping notes from the note list
2244 @SuppressWarnings("unused")
2245 private void tagsAdded(String noteGuid, String tagGuid) {
2246 String tagName = null;
2247 for (int i=0; i<listManager.getTagIndex().size(); i++) {
2248 if (listManager.getTagIndex().get(i).getGuid().equals(tagGuid)) {
2249 tagName = listManager.getTagIndex().get(i).getName();
2250 i=listManager.getTagIndex().size();
2253 if (tagName == null)
2256 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
2257 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(noteGuid)) {
2258 List<String> tagNames = new ArrayList<String>();
2259 tagNames.add(new String(tagName));
2260 Note n = listManager.getMasterNoteIndex().get(i);
2261 for (int j=0; j<n.getTagNames().size(); j++) {
2262 tagNames.add(new String(n.getTagNames().get(j)));
2264 listManager.getNoteTableModel().updateNoteTags(noteGuid, n.getTagGuids(), tagNames);
2265 if (n.getGuid().equals(currentNoteGuid)) {
2266 Collections.sort(tagNames);
2267 String display = "";
2268 for (int j=0; j<tagNames.size(); j++) {
2269 display = display+tagNames.get(j);
2270 if (j+2<tagNames.size())
2271 display = display+Global.tagDelimeter+" ";
2273 browserWindow.setTag(display);
2275 i=listManager.getMasterNoteIndex().size();
2280 listManager.getNoteTableModel().updateNoteSyncStatus(noteGuid, false);
2282 private void clearTagFilter() {
2283 tagTree.blockSignals(true);
2284 tagTree.clearSelection();
2285 menuBar.noteRestoreAction.setVisible(false);
2286 menuBar.tagEditAction.setEnabled(false);
2287 menuBar.tagMergeAction.setEnabled(false);
2288 menuBar.tagDeleteAction.setEnabled(false);
2289 menuBar.tagIconAction.setEnabled(false);
2290 selectedTagGUIDs.clear();
2291 listManager.setSelectedTags(selectedTagGUIDs);
2292 tagTree.blockSignals(false);
2294 // Change the icon for a tag
2295 @SuppressWarnings("unused")
2296 private void setTagIcon() {
2297 QTreeWidgetItem currentSelection;
2298 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2299 if (selections.size() == 0)
2302 currentSelection = selections.get(0);
2303 String guid = currentSelection.text(2);
2305 QIcon currentIcon = currentSelection.icon(0);
2306 QIcon icon = conn.getTagTable().getIcon(guid);
2309 dialog = new SetIcon(currentIcon, saveLastPath);
2310 dialog.setUseDefaultIcon(true);
2312 dialog = new SetIcon(icon, saveLastPath);
2313 dialog.setUseDefaultIcon(false);
2316 if (dialog.okPressed()) {
2317 saveLastPath = dialog.getPath();
2318 QIcon newIcon = dialog.getIcon();
2319 conn.getTagTable().setIcon(guid, newIcon, dialog.getFileType());
2320 if (newIcon == null)
2321 newIcon = new QIcon(iconPath+"tag.png");
2322 currentSelection.setIcon(0, newIcon);
2327 @SuppressWarnings("unused")
2328 private void mergeTags() {
2329 List<Tag> tags = new ArrayList<Tag>();
2330 List<QTreeWidgetItem> selections = tagTree.selectedItems();
2331 for (int i=0; i<selections.size(); i++) {
2332 Tag record = new Tag();
2333 record.setGuid(selections.get(i).text(2));
2334 record.setName(selections.get(i).text(0));
2338 TagMerge mergeDialog = new TagMerge(tags);
2340 if (!mergeDialog.okClicked())
2342 String newGuid = mergeDialog.getNewTagGuid();
2344 for (int i=0; i<tags.size(); i++) {
2345 if (!tags.get(i).getGuid().equals(newGuid)) {
2346 List<String> noteGuids = conn.getNoteTable().noteTagsTable.getTagNotes(tags.get(i).getGuid());
2347 for (int j=0; j<noteGuids.size(); j++) {
2348 String noteGuid = noteGuids.get(j);
2349 conn.getNoteTable().noteTagsTable.deleteNoteTag(noteGuid);
2350 if (!conn.getNoteTable().noteTagsTable.checkNoteNoteTags(noteGuid, newGuid))
2351 conn.getNoteTable().noteTagsTable.saveNoteTag(noteGuid, newGuid);
2355 listManager.reloadIndexes();
2358 //***************************************************************
2359 //***************************************************************
2360 //** These functions deal with Saved Search menu items
2361 //***************************************************************
2362 //***************************************************************
2363 // Add a new notebook
2364 @SuppressWarnings("unused")
2365 private void addSavedSearch() {
2366 logger.log(logger.HIGH, "Inside NeverNote.addSavedSearch");
2367 SavedSearchEdit edit = new SavedSearchEdit();
2368 edit.setSearchList(listManager.getSavedSearchIndex());
2371 if (!edit.okPressed())
2374 Calendar currentTime = new GregorianCalendar();
2375 Long l = new Long(currentTime.getTimeInMillis());
2376 String randint = new String(Long.toString(l));
2378 SavedSearch search = new SavedSearch();
2379 search.setUpdateSequenceNum(0);
2380 search.setGuid(randint);
2381 search.setName(edit.getName());
2382 search.setQuery(edit.getQuery());
2383 search.setFormat(QueryFormat.USER);
2384 listManager.getSavedSearchIndex().add(search);
2385 conn.getSavedSearchTable().addSavedSearch(search, true);
2386 savedSearchIndexUpdated();
2387 logger.log(logger.HIGH, "Leaving NeverNote.addSavedSearch");
2389 // Edit an existing tag
2390 @SuppressWarnings("unused")
2391 private void editSavedSearch() {
2392 logger.log(logger.HIGH, "Entering NeverNote.editSavedSearch");
2393 SavedSearchEdit edit = new SavedSearchEdit();
2394 edit.setTitle(tr("Edit Search"));
2395 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2396 QTreeWidgetItem currentSelection;
2397 currentSelection = selections.get(0);
2398 String guid = currentSelection.text(1);
2399 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(guid);
2400 edit.setName(currentSelection.text(0));
2401 edit.setQuery(s.getQuery());
2402 edit.setSearchList(listManager.getSavedSearchIndex());
2405 if (!edit.okPressed())
2408 List<SavedSearch> list = listManager.getSavedSearchIndex();
2409 SavedSearch search = null;
2410 boolean found = false;
2411 for (int i=0; i<list.size(); i++) {
2412 search = list.get(i);
2413 if (search.getGuid().equals(guid)) {
2420 search.setName(edit.getName());
2421 search.setQuery(edit.getQuery());
2422 conn.getSavedSearchTable().updateSavedSearch(search, true);
2423 savedSearchIndexUpdated();
2424 logger.log(logger.HIGH, "Leaving NeverNote.editSavedSearch");
2426 // Delete an existing tag
2427 @SuppressWarnings("unused")
2428 private void deleteSavedSearch() {
2429 logger.log(logger.HIGH, "Entering NeverNote.deleteSavedSearch");
2431 if (QMessageBox.question(this, tr("Confirmation"), tr("Delete the selected search?"),
2432 QMessageBox.StandardButton.Yes,
2433 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
2437 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2438 for (int i=selections.size()-1; i>=0; i--) {
2439 QTreeWidgetItem currentSelection;
2440 currentSelection = selections.get(i);
2441 for (int j=0; j<listManager.getSavedSearchIndex().size(); j++) {
2442 if (listManager.getSavedSearchIndex().get(j).getGuid().equals(currentSelection.text(1))) {
2443 conn.getSavedSearchTable().expungeSavedSearch(listManager.getSavedSearchIndex().get(j).getGuid(), true);
2444 listManager.getSavedSearchIndex().remove(j);
2445 j=listManager.getSavedSearchIndex().size()+1;
2448 selections.remove(i);
2450 savedSearchIndexUpdated();
2451 logger.log(logger.HIGH, "Leaving NeverNote.deleteSavedSearch");
2453 // Setup the tree containing the user's tags
2454 private void initializeSavedSearchTree() {
2455 logger.log(logger.HIGH, "Entering NeverNote.initializeSavedSearchTree");
2456 savedSearchTree.itemSelectionChanged.connect(this, "savedSearchTreeSelection()");
2457 logger.log(logger.HIGH, "Leaving NeverNote.initializeSavedSearchTree");
2459 // Listener when a tag is selected
2460 @SuppressWarnings("unused")
2461 private void savedSearchTreeSelection() {
2462 logger.log(logger.HIGH, "Entering NeverNote.savedSearchTreeSelection");
2464 clearNotebookFilter();
2467 clearAttributeFilter();
2469 String currentGuid = selectedSavedSearchGUID;
2470 menuBar.savedSearchEditAction.setEnabled(true);
2471 menuBar.savedSearchDeleteAction.setEnabled(true);
2472 menuBar.savedSearchIconAction.setEnabled(true);
2473 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2474 QTreeWidgetItem currentSelection;
2475 selectedSavedSearchGUID = "";
2476 for (int i=0; i<selections.size(); i++) {
2477 currentSelection = selections.get(i);
2478 if (currentSelection.text(1).equals(currentGuid)) {
2479 currentSelection.setSelected(false);
2481 selectedSavedSearchGUID = currentSelection.text(1);
2483 // i = selections.size() +1;
2486 // There is the potential for no notebooks to be selected if this
2487 // happens then we make it look like all notebooks were selecetd.
2488 // If that happens, just select the "all notebooks"
2489 if (selections.size()==0) {
2490 clearSavedSearchFilter();
2492 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2494 logger.log(logger.HIGH, "Leaving NeverNote.savedSearchTreeSelection");
2496 private void clearSavedSearchFilter() {
2497 menuBar.savedSearchEditAction.setEnabled(false);
2498 menuBar.savedSearchDeleteAction.setEnabled(false);
2499 menuBar.savedSearchIconAction.setEnabled(false);
2500 savedSearchTree.blockSignals(true);
2501 savedSearchTree.clearSelection();
2502 savedSearchTree.blockSignals(false);
2503 selectedSavedSearchGUID = "";
2504 searchField.setEditText("");
2505 searchPerformed = false;
2506 listManager.setSelectedSavedSearch(selectedSavedSearchGUID);
2508 // trigger the tag index to be refreshed
2509 private void savedSearchIndexUpdated() {
2510 if (selectedSavedSearchGUID == null)
2511 selectedSavedSearchGUID = new String();
2512 savedSearchTree.blockSignals(true);
2513 savedSearchTree.setIcons(conn.getSavedSearchTable().getAllIcons());
2514 savedSearchTree.load(listManager.getSavedSearchIndex());
2515 savedSearchTree.selectGuid(selectedSavedSearchGUID);
2516 savedSearchTree.blockSignals(false);
2518 // trigger when the saved search selection changes
2519 @SuppressWarnings("unused")
2520 private void updateSavedSearchSelection() {
2521 logger.log(logger.HIGH, "Entering NeverNote.updateSavedSearchSelection()");
2523 menuBar.savedSearchEditAction.setEnabled(true);
2524 menuBar.savedSearchDeleteAction.setEnabled(true);
2525 menuBar.savedSearchIconAction.setEnabled(true);
2526 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2528 if (selections.size() > 0) {
2529 menuBar.savedSearchEditAction.setEnabled(true);
2530 menuBar.savedSearchDeleteAction.setEnabled(true);
2531 menuBar.savedSearchIconAction.setEnabled(true);
2532 selectedSavedSearchGUID = selections.get(0).text(1);
2533 SavedSearch s = conn.getSavedSearchTable().getSavedSearch(selectedSavedSearchGUID);
2534 searchField.setEditText(s.getQuery());
2536 menuBar.savedSearchEditAction.setEnabled(false);
2537 menuBar.savedSearchDeleteAction.setEnabled(false);
2538 menuBar.savedSearchIconAction.setEnabled(false);
2539 selectedSavedSearchGUID = "";
2540 searchField.setEditText("");
2542 searchFieldChanged();
2544 logger.log(logger.HIGH, "Leaving NeverNote.updateSavedSearchSelection()");
2548 // Show/Hide note information
2549 @SuppressWarnings("unused")
2550 private void toggleSavedSearchWindow() {
2551 logger.log(logger.HIGH, "Entering NeverNote.toggleSavedSearchWindow");
2552 if (savedSearchTree.isVisible())
2553 savedSearchTree.hide();
2555 savedSearchTree.show();
2556 menuBar.hideSavedSearches.setChecked(savedSearchTree.isVisible());
2558 Global.saveWindowVisible("savedSearchTree", savedSearchTree.isVisible());
2559 logger.log(logger.HIGH, "Leaving NeverNote.toggleSavedSearchWindow");
2561 // Change the icon for a saved search
2562 @SuppressWarnings("unused")
2563 private void setSavedSearchIcon() {
2564 QTreeWidgetItem currentSelection;
2565 List<QTreeWidgetItem> selections = savedSearchTree.selectedItems();
2566 if (selections.size() == 0)
2569 currentSelection = selections.get(0);
2570 String guid = currentSelection.text(1);
2572 QIcon currentIcon = currentSelection.icon(0);
2573 QIcon icon = conn.getSavedSearchTable().getIcon(guid);
2576 dialog = new SetIcon(currentIcon, saveLastPath);
2577 dialog.setUseDefaultIcon(true);
2579 dialog = new SetIcon(icon, saveLastPath);
2580 dialog.setUseDefaultIcon(false);
2583 if (dialog.okPressed()) {
2584 saveLastPath = dialog.getPath();
2585 QIcon newIcon = dialog.getIcon();
2586 conn.getSavedSearchTable().setIcon(guid, newIcon, dialog.getFileType());
2587 if (newIcon == null)
2588 newIcon = new QIcon(iconPath+"search.png");
2589 currentSelection.setIcon(0, newIcon);
2597 //***************************************************************
2598 //***************************************************************
2599 //** These functions deal with Help menu & tool menu items
2600 //***************************************************************
2601 //***************************************************************
2602 // Show database status
2603 @SuppressWarnings("unused")
2604 private void databaseStatus() {
2606 indexRunner.interrupt = true;
2607 int dirty = conn.getNoteTable().getDirtyCount();
2608 int unindexed = conn.getNoteTable().getUnindexedCount();
2609 DatabaseStatus status = new DatabaseStatus();
2610 status.setUnsynchronized(dirty);
2611 status.setUnindexed(unindexed);
2612 status.setNoteCount(conn.getNoteTable().getNoteCount());
2613 status.setNotebookCount(listManager.getNotebookIndex().size());
2614 status.setUnindexedResourceCount(conn.getNoteTable().noteResourceTable.getUnindexedCount());
2615 status.setSavedSearchCount(listManager.getSavedSearchIndex().size());
2616 status.setTagCount(listManager.getTagIndex().size());
2617 status.setResourceCount(conn.getNoteTable().noteResourceTable.getResourceCount());
2618 status.setWordCount(conn.getWordsTable().getWordCount());
2622 // Compact the database
2623 @SuppressWarnings("unused")
2624 private void compactDatabase() {
2625 logger.log(logger.HIGH, "Entering NeverNote.compactDatabase");
2626 if (QMessageBox.question(this, tr("Confirmation"), tr("This will free unused space in the database, "+
2627 "but please be aware that depending upon the size of your database this can be time consuming " +
2628 "and NeverNote will be unresponsive until it is complete. Do you wish to continue?"),
2629 QMessageBox.StandardButton.Yes,
2630 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
2633 setMessage("Compacting database.");
2635 listManager.compactDatabase();
2637 setMessage("Database compact is complete.");
2638 logger.log(logger.HIGH, "Leaving NeverNote.compactDatabase");
2640 @SuppressWarnings("unused")
2641 private void accountInformation() {
2642 logger.log(logger.HIGH, "Entering NeverNote.accountInformation");
2643 AccountDialog dialog = new AccountDialog();
2645 logger.log(logger.HIGH, "Leaving NeverNote.accountInformation");
2647 @SuppressWarnings("unused")
2648 private void releaseNotes() {
2649 logger.log(logger.HIGH, "Entering NeverNote.releaseNotes");
2650 QDialog dialog = new QDialog(this);
2651 QHBoxLayout layout = new QHBoxLayout();
2652 QTextEdit textBox = new QTextEdit();
2653 layout.addWidget(textBox);
2654 textBox.setReadOnly(true);
2655 QFile file = new QFile(Global.getFileManager().getHomeDirPath("release.txt"));
2656 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly,
2657 QIODevice.OpenModeFlag.Text)))
2659 textBox.setText(file.readAll().toString());
2661 dialog.setWindowTitle(tr("Release Notes"));
2662 dialog.setLayout(layout);
2664 logger.log(logger.HIGH, "Leaving NeverNote.releaseNotes");
2666 // Called when user picks Log from the help menu
2667 @SuppressWarnings("unused")
2668 private void logger() {
2669 logger.log(logger.HIGH, "Entering NeverNote.logger");
2670 LogFileDialog dialog = new LogFileDialog(emitLog);
2672 logger.log(logger.HIGH, "Leaving NeverNote.logger");
2674 // Menu option "help/about" was selected
2675 @SuppressWarnings("unused")
2676 private void about() {
2677 logger.log(logger.HIGH, "Entering NeverNote.about");
2678 QMessageBox.about(this,
2679 tr("About NeverNote"),
2680 tr("<h4><center><b>NeverNote</b></center></h4><hr><center>Version ")
2682 +tr("<hr></center>Evernote"
2683 +"An Open Source Evernote Client.<br><br>"
2684 +"Licensed under GPL v2. <br><hr><br>"
2685 +"Evernote is copyright 2001-2010 by Evernote Corporation<br>"
2686 +"Jambi and QT are the licensed trademark of Nokia Corporation<br>"
2687 +"PDFRenderer is licened under the LGPL<br>"
2688 +"JTidy is copyrighted under the World Wide Web Consortium<br>"
2689 +"Apache Common Utilities licensed under the Apache License Version 2.0<br>"
2690 +"Jazzy is licened under the LGPL<br>"
2691 +"Java is a registered trademark of Oracle Corporation.<br><hr>"
2692 +"Special thanks to:<br>BitRock InstallBuilder for the Windows installer"
2693 +"<br>CodeCogs (www.codecogs.com) for the LaTeX image rendering."));
2694 logger.log(logger.HIGH, "Leaving NeverNote.about");
2696 // Hide the entire left hand side
2697 @SuppressWarnings("unused")
2698 private void toggleLeftSide() {
2701 hidden = !menuBar.hideLeftSide.isChecked();
2702 menuBar.hideLeftSide.setChecked(!hidden);
2705 leftSplitter1.setHidden(true);
2707 leftSplitter1.setHidden(false);
2709 Global.saveWindowVisible("leftPanel", hidden);
2712 public void checkForUpdates() {
2713 // Send off thread to check for a new version
2714 versionChecker = new QNetworkAccessManager(this);
2715 versionChecker.finished.connect(this, "upgradeFileRead(QNetworkReply)");
2716 QNetworkRequest request = new QNetworkRequest();
2717 request.setUrl(new QUrl(Global.getUpdatesAvailableUrl()));
2718 versionChecker.get(request);
2720 @SuppressWarnings("unused")
2721 private void upgradeFileRead(QNetworkReply reply) {
2722 if (!reply.isReadable())
2725 String winVersion = Global.version;
2726 String osxVersion = Global.version;
2727 String linuxVersion = Global.version;
2728 String linux64Version = Global.version;
2729 String version = Global.version;
2731 // Determine the versions available
2732 QByteArray data = reply.readLine();
2733 while (data != null && !reply.atEnd()) {
2734 String line = data.toString();
2736 if (line.contains(":"))
2737 lineVersion = line.substring(line.indexOf(":")+1).replace(" ", "").replace("\n", "");
2740 if (line.toLowerCase().contains("windows"))
2741 winVersion = lineVersion;
2742 else if (line.toLowerCase().contains("os-x"))
2743 osxVersion = lineVersion;
2744 else if (line.toLowerCase().contains("linux amd64"))
2745 linux64Version = lineVersion;
2746 else if (line.toLowerCase().contains("linux i386"))
2747 linuxVersion = lineVersion;
2748 else if (line.toLowerCase().contains("default"))
2749 version = lineVersion;
2751 // Read the next line
2752 data = reply.readLine();
2755 // Now we need to determine what system we are on.
2756 if (System.getProperty("os.name").toLowerCase().contains("windows"))
2757 version = winVersion;
2758 if (System.getProperty("os.name").toLowerCase().contains("mac os"))
2759 version = osxVersion;
2760 if (System.getProperty("os.name").toLowerCase().contains("Linux")) {
2761 if (System.getProperty("os.arch").contains("amd64") ||
2762 System.getProperty("os.arch").contains("x86_64"))
2763 version = linux64Version;
2765 version = linuxVersion;
2769 for (String validVersion : Global.validVersions) {
2770 if (version.equals(validVersion))
2774 UpgradeAvailableDialog dialog = new UpgradeAvailableDialog();
2776 if (dialog.remindMe())
2777 Global.setCheckVersionUpgrade(true);
2779 Global.setCheckVersionUpgrade(false);
2783 //***************************************************************
2784 //***************************************************************
2785 //** These functions deal with the Toolbar
2786 //***************************************************************
2787 //***************************************************************
2788 @SuppressWarnings("unused")
2789 private void focusSearch() {
2790 searchField.setFocus();
2793 // Text in the search bar has been cleared
2794 private void searchFieldCleared() {
2797 // This is done because we want to force a reload of
2798 // images. Some images we may want to highlight the text.
2799 readOnlyCache.clear();
2800 inkNoteCache.clear();
2802 QWebSettings.setMaximumPagesInCache(0);
2803 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2805 searchField.setEditText("");
2806 saveNoteColumnPositions();
2807 saveNoteIndexWidth();
2808 noteIndexUpdated(true);
2809 if (currentNote == null && listManager.getNoteIndex().size() > 0) {
2810 currentNote = listManager.getNoteIndex().get(0);
2811 currentNoteGuid = currentNote.getGuid();
2813 refreshEvernoteNote(true);
2814 if (currentNote != null)
2815 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
2817 // text in the search bar changed. We only use this to tell if it was cleared,
2818 // otherwise we trigger off searchFieldChanged.
2819 @SuppressWarnings("unused")
2820 private void searchFieldTextChanged(String text) {
2821 QWebSettings.setMaximumPagesInCache(0);
2822 QWebSettings.setObjectCacheCapacities(0, 0, 0);
2824 if (text.trim().equals("")) {
2825 searchFieldCleared();
2826 if (searchPerformed) {
2828 // This is done because we want to force a reload of
2829 // images. Some images we may want to highlight the text.
2831 readOnlyCache.clear();
2832 inkNoteCache.clear();
2834 listManager.setEnSearch("");
2835 listManager.loadNotesIndex();
2836 refreshEvernoteNote(true);
2837 noteIndexUpdated(false);
2838 refreshEvernoteNote(true);
2840 searchPerformed = false;
2843 // Text in the toolbar has changed
2844 private void searchFieldChanged() {
2845 logger.log(logger.HIGH, "Entering NeverNote.searchFieldChanged");
2847 readOnlyCache.clear();
2848 inkNoteCache.clear();
2849 saveNoteColumnPositions();
2850 saveNoteIndexWidth();
2851 String text = searchField.currentText();
2852 listManager.setEnSearch(text.trim());
2853 listManager.loadNotesIndex();
2854 noteIndexUpdated(false);
2855 refreshEvernoteNote(true);
2856 searchPerformed = true;
2857 logger.log(logger.HIGH, "Leaving NeverNote.searchFieldChanged");
2860 // Build the window tool bar
2861 private void setupToolBar() {
2862 logger.log(logger.HIGH, "Entering NeverNote.setupToolBar");
2863 toolBar = addToolBar(tr("Tool Bar"));
2864 toolBar.setObjectName("toolBar");
2865 menuBar.setupToolBarVisible();
2866 if (!Global.isWindowVisible("toolBar"))
2867 toolBar.setVisible(false);
2869 toolBar.setVisible(true);
2871 // toolBar.addWidget(menuBar);
2872 // menuBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2873 // toolBar.addSeparator();
2874 prevButton = toolBar.addAction(tr("Previous"));
2875 QIcon prevIcon = new QIcon(iconPath+"back.png");
2876 prevButton.setIcon(prevIcon);
2877 prevButton.triggered.connect(this, "previousViewedAction()");
2878 togglePrevArrowButton(Global.isToolbarButtonVisible("prevArrow"));
2880 nextButton = toolBar.addAction(tr("Next"));
2881 QIcon nextIcon = new QIcon(iconPath+"forward.png");
2882 nextButton.setIcon(nextIcon);
2883 nextButton.triggered.connect(this, "nextViewedAction()");
2884 toggleNextArrowButton(Global.isToolbarButtonVisible("nextArrow"));
2886 upButton = toolBar.addAction(tr("Up"));
2887 QIcon upIcon = new QIcon(iconPath+"up.png");
2888 upButton.setIcon(upIcon);
2889 upButton.triggered.connect(this, "upAction()");
2890 toggleUpArrowButton(Global.isToolbarButtonVisible("upArrow"));
2893 downButton = toolBar.addAction(tr("Down"));
2894 QIcon downIcon = new QIcon(iconPath+"down.png");
2895 downButton.setIcon(downIcon);
2896 downButton.triggered.connect(this, "downAction()");
2897 toggleDownArrowButton(Global.isToolbarButtonVisible("downArrow"));
2899 synchronizeButton = toolBar.addAction(tr("Synchronize"));
2900 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
2901 synchronizeIconAngle = 0;
2902 synchronizeButton.triggered.connect(this, "evernoteSync()");
2903 toggleSynchronizeButton(Global.isToolbarButtonVisible("synchronize"));
2905 printButton = toolBar.addAction(tr("Print"));
2906 QIcon printIcon = new QIcon(iconPath+"print.png");
2907 printButton.setIcon(printIcon);
2908 printButton.triggered.connect(this, "printNote()");
2909 togglePrintButton(Global.isToolbarButtonVisible("print"));
2911 tagButton = toolBar.addAction(tr("Tag"));
2912 QIcon tagIcon = new QIcon(iconPath+"tag.png");
2913 tagButton.setIcon(tagIcon);
2914 tagButton.triggered.connect(browserWindow, "modifyTags()");
2915 toggleTagButton(Global.isToolbarButtonVisible("tag"));
2917 attributeButton = toolBar.addAction(tr("Attributes"));
2918 QIcon attributeIcon = new QIcon(iconPath+"attribute.png");
2919 attributeButton.setIcon(attributeIcon);
2920 attributeButton.triggered.connect(this, "toggleNoteInformation()");
2921 toggleAttributeButton(Global.isToolbarButtonVisible("attribute"));
2923 emailButton = toolBar.addAction(tr("Email"));
2924 QIcon emailIcon = new QIcon(iconPath+"email.png");
2925 emailButton.setIcon(emailIcon);
2926 emailButton.triggered.connect(this, "emailNote()");
2927 toggleEmailButton(Global.isToolbarButtonVisible("email"));
2929 deleteButton = toolBar.addAction(tr("Delete"));
2930 QIcon deleteIcon = new QIcon(iconPath+"delete.png");
2931 deleteButton.setIcon(deleteIcon);
2932 deleteButton.triggered.connect(this, "deleteNote()");
2933 toggleDeleteButton(Global.isToolbarButtonVisible("delete"));
2935 newButton = toolBar.addAction(tr("New"));
2936 QIcon newIcon = new QIcon(iconPath+"new.png");
2937 newButton.triggered.connect(this, "addNote()");
2938 newButton.setIcon(newIcon);
2939 toggleNewButton(Global.isToolbarButtonVisible("new"));
2941 allNotesButton = toolBar.addAction(tr("All Notes"));
2942 QIcon allIcon = new QIcon(iconPath+"books.png");
2943 allNotesButton.triggered.connect(this, "allNotes()");
2944 allNotesButton.setIcon(allIcon);
2945 toggleAllNotesButton(Global.isToolbarButtonVisible("allNotes"));
2947 //toolBar.addSeparator();
2948 //toolBar.addWidget(new QLabel(tr("Quota:")));
2949 //toolBar.addWidget(quotaBar);
2950 //quotaBar.setSizePolicy(Policy.Minimum, Policy.Minimum);
2952 //toolBar.addSeparator();
2954 //toolBar.addWidget(new QLabel(tr("Zoom")));
2955 //toolBar.addWidget(zoomSpinner);
2957 //toolBar.addWidget(new QLabel(" "));
2958 //toolBar.addSeparator();
2959 //toolBar.addWidget(new QLabel(tr(" Search:")));
2960 //toolBar.addWidget(searchField);
2961 QSizePolicy sizePolicy = new QSizePolicy();
2962 sizePolicy.setHorizontalPolicy(Policy.MinimumExpanding);
2963 QLabel spacer = new QLabel("");
2964 spacer.setSizePolicy(sizePolicy);
2965 toolBar.addWidget(spacer);
2966 //searchField.setInsertPolicy(InsertPolicy.InsertAtTop);
2968 //searchClearButton = toolBar.addAction("Search Clear");
2969 //QIcon searchClearIcon = new QIcon(iconPath+"searchclear.png");
2970 //searchClearButton.setIcon(searchClearIcon);
2971 //searchClearButton.triggered.connect(this, "searchFieldCleared()");
2972 //toggleSearchClearButton(Global.isToolbarButtonVisible("searchClear"));
2974 logger.log(logger.HIGH, "Leaving NeverNote.setupToolBar");
2976 // Update the sychronize button picture
2978 public QMenu createPopupMenu() {
2979 QMenu contextMenu = super.createPopupMenu();
2981 contextMenu.addSeparator();
2982 QAction prevAction = addContextAction("prevArrow", tr("Previous Arrow"));
2983 contextMenu.addAction(prevAction);
2984 prevAction.triggered.connect(this, "togglePrevArrowButton(Boolean)");
2986 QAction nextAction = addContextAction("nextArrow", tr("Next Arrow"));
2987 contextMenu.addAction(nextAction);
2988 nextAction.triggered.connect(this, "toggleNextArrowButton(Boolean)");
2990 QAction upAction = addContextAction("upArrow", tr("Up Arrow"));
2991 contextMenu.addAction(upAction);
2992 upAction.triggered.connect(this, "toggleUpArrowButton(Boolean)");
2994 QAction downAction = addContextAction("downArrow", tr("Down Arrow"));
2995 contextMenu.addAction(downAction);
2996 downAction.triggered.connect(this, "toggleDownArrowButton(Boolean)");
2998 QAction synchronizeAction = addContextAction("synchronize", tr("Synchronize"));
2999 contextMenu.addAction(synchronizeAction);
3000 synchronizeAction.triggered.connect(this, "toggleSynchronizeButton(Boolean)");
3002 QAction printAction = addContextAction("print", tr("Print"));
3003 contextMenu.addAction(printAction);
3004 printAction.triggered.connect(this, "togglePrintButton(Boolean)");
3006 QAction tagAction = addContextAction("tag", tr("Tag"));
3007 contextMenu.addAction(tagAction);
3008 tagAction.triggered.connect(this, "toggleTagButton(Boolean)");
3010 QAction attributeAction = addContextAction("attribute", tr("Attribute"));
3011 contextMenu.addAction(attributeAction);
3012 attributeAction.triggered.connect(this, "toggleAttributeButton(Boolean)");
3014 QAction emailAction = addContextAction("email", tr("Email"));
3015 contextMenu.addAction(emailAction);
3016 emailAction.triggered.connect(this, "toggleEmailButton(Boolean)");
3018 QAction deleteAction = addContextAction("delete", tr("Delete"));
3019 contextMenu.addAction(deleteAction);
3020 deleteAction.triggered.connect(this, "toggleDeleteButton(Boolean)");
3022 QAction newAction = addContextAction("new", tr("Add"));
3023 contextMenu.addAction(newAction);
3024 newAction.triggered.connect(this, "toggleNewButton(Boolean)");
3026 QAction allNotesAction = addContextAction("allNotes", tr("All Notes"));
3027 contextMenu.addAction(allNotesAction);
3028 allNotesAction.triggered.connect(this, "toggleAllNotesButton(Boolean)");
3030 QAction searchClearAction = addContextAction("searchClear", tr("Search Clear"));
3031 contextMenu.addAction(searchClearAction);
3032 searchClearAction.triggered.connect(this, "toggleSearchClearButton(Boolean)");
3037 private QAction addContextAction(String config, String name) {
3038 QAction newAction = new QAction(this);
3039 newAction.setText(name);
3040 newAction.setCheckable(true);
3041 newAction.setChecked(Global.isToolbarButtonVisible(config));
3044 private void togglePrevArrowButton(Boolean toggle) {
3045 prevButton.setVisible(toggle);
3046 Global.saveToolbarButtonsVisible("prevArrow", toggle);
3048 private void toggleNextArrowButton(Boolean toggle) {
3049 nextButton.setVisible(toggle);
3050 Global.saveToolbarButtonsVisible("nextArrow", toggle);
3052 private void toggleUpArrowButton(Boolean toggle) {
3053 upButton.setVisible(toggle);
3054 Global.saveToolbarButtonsVisible("upArrow", toggle);
3056 private void toggleDownArrowButton(Boolean toggle) {
3057 downButton.setVisible(toggle);
3058 Global.saveToolbarButtonsVisible("downArrow", toggle);
3060 private void toggleSynchronizeButton(Boolean toggle) {
3061 synchronizeButton.setVisible(toggle);
3062 Global.saveToolbarButtonsVisible("synchronize", toggle);
3064 private void togglePrintButton(Boolean toggle) {
3065 printButton.setVisible(toggle);
3066 Global.saveToolbarButtonsVisible("print", toggle);
3068 private void toggleTagButton(Boolean toggle) {
3069 tagButton.setVisible(toggle);
3070 Global.saveToolbarButtonsVisible("tag", toggle);
3072 private void toggleAttributeButton(Boolean toggle) {
3073 attributeButton.setVisible(toggle);
3074 Global.saveToolbarButtonsVisible("attribute", toggle);
3076 private void toggleEmailButton(Boolean toggle) {
3077 emailButton.setVisible(toggle);
3078 Global.saveToolbarButtonsVisible("email", toggle);
3080 private void toggleDeleteButton(Boolean toggle) {
3081 deleteButton.setVisible(toggle);
3082 Global.saveToolbarButtonsVisible("delete", toggle);
3084 private void toggleNewButton(Boolean toggle) {
3085 newButton.setVisible(toggle);
3086 Global.saveToolbarButtonsVisible("new", toggle);
3088 private void toggleAllNotesButton(Boolean toggle) {
3089 allNotesButton.setVisible(toggle);
3090 Global.saveToolbarButtonsVisible("allNotes", toggle);
3092 @SuppressWarnings("unused")
3093 private void toggleSearchClearButton(Boolean toggle) {
3094 searchClearButton.setVisible(toggle);
3095 Global.saveToolbarButtonsVisible("searchClear", toggle);
3102 @SuppressWarnings("unused")
3103 private void updateSyncButton() {
3105 if (syncIcons == null) {
3106 syncIcons = new ArrayList<QPixmap>();
3108 synchronizeIconAngle = 0;
3109 QPixmap pix = new QPixmap(iconPath+"synchronize.png");
3111 for (int i=0; i<=360; i++) {
3112 QPixmap rotatedPix = new QPixmap(pix.size());
3113 QPainter p = new QPainter(rotatedPix);
3114 rotatedPix.fill(toolBar.palette().color(ColorRole.Button));
3115 QSize size = pix.size();
3116 p.translate(size.width()/2, size.height()/2);
3119 p.setBackgroundMode(BGMode.OpaqueMode);
3120 p.translate(-size.width()/2, -size.height()/2);
3121 p.drawPixmap(0,0, pix);
3123 syncIcons.add(rotatedPix);
3127 synchronizeIconAngle++;
3128 if (synchronizeIconAngle > 359)
3129 synchronizeIconAngle=0;
3130 synchronizeButton.setIcon(syncIcons.get(synchronizeIconAngle));
3133 // Synchronize with Evernote
3135 private void evernoteSync() {
3136 logger.log(logger.HIGH, "Entering NeverNote.evernoteSync");
3137 if (!Global.isConnected)
3139 if (Global.isConnected)
3140 synchronizeAnimationTimer.start(5);
3141 // synchronizeAnimationTimer.start(200);
3143 logger.log(logger.HIGH, "Leaving NeverNote.evernoteSync");
3145 private void updateQuotaBar() {
3146 long limit = Global.getUploadLimit();
3147 long amount = Global.getUploadAmount();
3148 if (amount>0 && limit>0) {
3149 int percent =(int)(amount*100/limit);
3150 quotaBar.setValue(percent);
3152 quotaBar.setValue(0);
3155 @SuppressWarnings("unused")
3156 private void zoomChanged() {
3157 browserWindow.getBrowser().setZoomFactor(new Double(zoomSpinner.value())/100);
3160 //****************************************************************
3161 //****************************************************************
3162 //* System Tray functions
3163 //****************************************************************
3164 //****************************************************************
3165 private void trayToggleVisible() {
3170 if (windowMaximized)
3177 @SuppressWarnings("unused")
3178 private void trayActivated(QSystemTrayIcon.ActivationReason reason) {
3179 if (reason == QSystemTrayIcon.ActivationReason.DoubleClick) {
3180 String name = QSystemTrayIcon.MessageIcon.resolve(reason.value()).name();
3181 trayToggleVisible();
3186 //***************************************************************
3187 //***************************************************************
3188 //** These functions deal with the trash tree
3189 //***************************************************************
3190 //***************************************************************
3191 // Setup the tree containing the trash.
3192 @SuppressWarnings("unused")
3193 private void trashTreeSelection() {
3194 logger.log(logger.HIGH, "Entering NeverNote.trashTreeSelection");
3196 clearNotebookFilter();
3198 clearAttributeFilter();
3199 clearSavedSearchFilter();
3201 String tempGuid = currentNoteGuid;
3203 // currentNoteGuid = "";
3204 currentNote = new Note();
3205 selectedNoteGUIDs.clear();
3206 listManager.getSelectedNotebooks().clear();
3207 listManager.getSelectedTags().clear();
3208 listManager.setSelectedSavedSearch("");
3209 browserWindow.clear();
3211 // toggle the add buttons
3212 newButton.setEnabled(!newButton.isEnabled());
3213 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3214 menuBar.noteAdd.setVisible(true);
3216 List<QTreeWidgetItem> selections = trashTree.selectedItems();
3217 if (selections.size() == 0) {
3218 currentNoteGuid = trashNoteGuid;
3219 trashNoteGuid = tempGuid;
3220 Global.showDeleted = false;
3221 menuBar.noteRestoreAction.setEnabled(false);
3222 menuBar.noteRestoreAction.setVisible(false);
3225 currentNoteGuid = trashNoteGuid;
3226 trashNoteGuid = tempGuid;
3227 menuBar.noteRestoreAction.setEnabled(true);
3228 menuBar.noteRestoreAction.setVisible(true);
3229 Global.showDeleted = true;
3231 listManager.loadNotesIndex();
3232 noteIndexUpdated(false);
3233 //// browserWindow.setEnabled(newButton.isEnabled());
3234 browserWindow.setReadOnly(!newButton.isEnabled());
3235 logger.log(logger.HIGH, "Leaving NeverNote.trashTreeSelection");
3237 // Empty the trash file
3238 @SuppressWarnings("unused")
3239 private void emptyTrash() {
3240 // browserWindow.clear();
3241 logger.log(logger.EXTREME, "Emptying Trash");
3242 listManager.emptyTrash();
3243 logger.log(logger.EXTREME, "Resetting view after trash empty");
3244 if (trashTree.selectedItems().size() > 0) {
3245 listManager.getSelectedNotebooks().clear();
3246 listManager.getSelectedTags().clear();
3247 listManager.setSelectedSavedSearch("");
3248 newButton.setEnabled(!newButton.isEnabled());
3249 menuBar.noteAdd.setEnabled(newButton.isEnabled());
3250 menuBar.noteAdd.setVisible(true);
3251 browserWindow.clear();
3254 clearNotebookFilter();
3255 clearSavedSearchFilter();
3256 clearAttributeFilter();
3258 Global.showDeleted = false;
3259 menuBar.noteRestoreAction.setEnabled(false);
3260 menuBar.noteRestoreAction.setVisible(false);
3262 listManager.loadNotesIndex();
3263 noteIndexUpdated(false);
3266 // Show/Hide trash window
3267 @SuppressWarnings("unused")
3268 private void toggleTrashWindow() {
3269 logger.log(logger.HIGH, "Entering NeverNote.toggleTrashWindow");
3270 if (trashTree.isVisible())
3274 menuBar.hideTrash.setChecked(trashTree.isVisible());
3276 Global.saveWindowVisible("trashTree", trashTree.isVisible());
3277 logger.log(logger.HIGH, "Leaving NeverNote.trashWindow");
3279 private void clearTrashFilter() {
3280 Global.showDeleted = false;
3281 newButton.setEnabled(true);
3282 menuBar.noteAdd.setEnabled(true);
3283 menuBar.noteAdd.setVisible(true);
3284 trashTree.blockSignals(true);
3285 trashTree.clearSelection();
3286 trashTree.blockSignals(false);
3291 //***************************************************************
3292 //***************************************************************
3293 //** These functions deal with connection settings
3294 //***************************************************************
3295 //***************************************************************
3296 // SyncRunner had a problem and things are disconnected
3297 @SuppressWarnings("unused")
3298 private void remoteErrorDisconnect() {
3299 menuBar.connectAction.setText(tr("Connect"));
3300 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3301 menuBar.synchronizeAction.setEnabled(false);
3302 Global.isConnected = false;
3303 synchronizeAnimationTimer.stop();
3306 // Do a manual connect/disconnect
3307 private void remoteConnect() {
3308 logger.log(logger.HIGH, "Entering NeverNote.remoteConnect");
3310 if (Global.isConnected) {
3311 Global.isConnected = false;
3312 syncRunner.enDisconnect();
3313 setupConnectMenuOptions();
3318 AESEncrypter aes = new AESEncrypter();
3320 aes.decrypt(new FileInputStream(Global.getFileManager().getHomeDirFile("secure.txt")));
3321 } catch (FileNotFoundException e) {
3322 // File not found, so we'll just get empty strings anyway.
3325 if (Global.getProxyValue("url").equals("")) {
3326 System.setProperty("http.proxyHost","") ;
3327 System.setProperty("http.proxyPort", "") ;
3328 System.setProperty("https.proxyHost","") ;
3329 System.setProperty("https.proxyPort", "") ;
3332 System.setProperty("http.proxyHost",Global.getProxyValue("url")) ;
3333 System.setProperty("http.proxyPort", Global.getProxyValue("port")) ;
3334 System.setProperty("https.proxyHost",Global.getProxyValue("url")) ;
3335 System.setProperty("https.proxyPort", Global.getProxyValue("port")) ;
3337 if (Global.getProxyValue("userid").equals("")) {
3338 Authenticator.setDefault(new Authenticator() {
3340 protected PasswordAuthentication getPasswordAuthentication() {
3342 PasswordAuthentication(Global.getProxyValue("userid"),Global.getProxyValue("password").toCharArray());
3348 syncRunner.userStoreUrl = Global.userStoreUrl;
3349 syncRunner.noteStoreUrl = Global.noteStoreUrl;
3350 syncRunner.noteStoreUrlBase = Global.noteStoreUrlBase;
3352 String userid = aes.getUserid();
3353 String password = aes.getPassword();
3354 if (!userid.equals("") && !password.equals("")) {
3355 Global.username = userid;
3356 Global.password = password;
3357 syncRunner.username = Global.username;
3358 syncRunner.password = Global.password;
3359 syncRunner.enConnect();
3362 Global.isConnected = syncRunner.isConnected;
3364 if (!Global.isConnected) {
3365 // Show the login dialog box
3366 if (!Global.automaticLogin() || userid.equals("")|| password.equals("")) {
3367 LoginDialog login = new LoginDialog();
3370 if (!login.okPressed()) {
3374 Global.username = login.getUserid();
3375 Global.password = login.getPassword();
3377 syncRunner.username = Global.username;
3378 syncRunner.password = Global.password;
3379 syncRunner.enConnect();
3380 Global.isConnected = syncRunner.isConnected;
3383 if (!Global.isConnected)
3386 setupConnectMenuOptions();
3387 logger.log(logger.HIGH, "Leaving NeverNote.remoteConnect");
3389 private void setupConnectMenuOptions() {
3390 logger.log(logger.HIGH, "entering NeverNote.setupConnectMenuOptions");
3391 if (!Global.isConnected) {
3392 menuBar.connectAction.setText(tr("Connect"));
3393 menuBar.connectAction.setToolTip(tr("Connect to Evernote"));
3394 menuBar.synchronizeAction.setEnabled(false);
3396 menuBar.connectAction.setText(tr("Disconnect"));
3397 menuBar.connectAction.setToolTip(tr("Disconnect from Evernote"));
3398 menuBar.synchronizeAction.setEnabled(true);
3400 logger.log(logger.HIGH, "Leaving NeverNote.setupConnectionMenuOptions");
3405 //***************************************************************
3406 //***************************************************************
3407 //** These functions deal with the GUI Attribute tree
3408 //***************************************************************
3409 //***************************************************************
3410 @SuppressWarnings("unused")
3411 private void attributeTreeClicked(QTreeWidgetItem item, Integer integer) {
3413 // clearTagFilter();
3414 // clearNotebookFilter();
3416 // clearSavedSearchFilter();
3418 if (attributeTreeSelected == null || item.nativeId() != attributeTreeSelected.nativeId()) {
3419 if (item.childCount() > 0) {
3420 item.setSelected(false);
3422 Global.createdBeforeFilter.reset();
3423 Global.createdSinceFilter.reset();
3424 Global.changedBeforeFilter.reset();
3425 Global.changedSinceFilter.reset();
3426 Global.containsFilter.reset();
3427 attributeTreeSelected = item;
3428 DateAttributeFilterTable f = null;
3429 f = findDateAttributeFilterTable(item.parent());
3431 f.select(item.parent().indexOfChild(item));
3433 Global.containsFilter.select(item.parent().indexOfChild(item));
3436 listManager.loadNotesIndex();
3437 noteIndexUpdated(false);
3440 attributeTreeSelected = null;
3441 item.setSelected(false);
3442 Global.createdBeforeFilter.reset();
3443 Global.createdSinceFilter.reset();
3444 Global.changedBeforeFilter.reset();
3445 Global.changedSinceFilter.reset();
3446 Global.containsFilter.reset();
3447 listManager.loadNotesIndex();
3448 noteIndexUpdated(false);
3450 // This determines what attribute filter we need, depending upon the selection
3451 private DateAttributeFilterTable findDateAttributeFilterTable(QTreeWidgetItem w) {
3452 if (w.parent() != null && w.childCount() > 0) {
3453 QTreeWidgetItem parent = w.parent();
3454 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3455 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3456 return Global.createdSinceFilter;
3457 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Created &&
3458 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3459 return Global.createdBeforeFilter;
3460 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3461 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Since)
3462 return Global.changedSinceFilter;
3463 if (parent.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.LastModified &&
3464 w.data(0,ItemDataRole.UserRole)==AttributeTreeWidget.Attributes.Before)
3465 return Global.changedBeforeFilter;
3470 // Show/Hide attribute search window
3471 @SuppressWarnings("unused")
3472 private void toggleAttributesWindow() {
3473 logger.log(logger.HIGH, "Entering NeverNote.toggleAttributesWindow");
3474 if (attributeTree.isVisible())
3475 attributeTree.hide();
3477 attributeTree.show();
3478 menuBar.hideAttributes.setChecked(attributeTree.isVisible());
3480 Global.saveWindowVisible("attributeTree", attributeTree.isVisible());
3481 logger.log(logger.HIGH, "Leaving NeverNote.toggleAttributeWindow");
3483 private void clearAttributeFilter() {
3484 Global.createdBeforeFilter.reset();
3485 Global.createdSinceFilter.reset();
3486 Global.changedBeforeFilter.reset();
3487 Global.changedSinceFilter.reset();
3488 Global.containsFilter.reset();
3489 attributeTreeSelected = null;
3490 attributeTree.blockSignals(true);
3491 attributeTree.clearSelection();
3492 attributeTree.blockSignals(false);
3496 //***************************************************************
3497 //***************************************************************
3498 //** These functions deal with the GUI Note index table
3499 //***************************************************************
3500 //***************************************************************
3501 // Initialize the note list table
3502 private void initializeNoteTable() {
3503 logger.log(logger.HIGH, "Entering NeverNote.initializeNoteTable");
3504 noteTableView.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection);
3505 noteTableView.selectionModel().selectionChanged.connect(this, "noteTableSelection()");
3506 logger.log(logger.HIGH, "Leaving NeverNote.initializeNoteTable");
3508 // Show/Hide trash window
3509 @SuppressWarnings("unused")
3510 private void toggleNoteListWindow() {
3511 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteListWindow");
3512 if (noteTableView.isVisible())
3513 noteTableView.hide();
3515 noteTableView.show();
3516 menuBar.hideNoteList.setChecked(noteTableView.isVisible());
3518 Global.saveWindowVisible("noteList", noteTableView.isVisible());
3519 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteListWindow");
3521 // Handle the event that a user selects a note from the table
3522 @SuppressWarnings("unused")
3523 private void noteTableSelection() {
3524 logger.log(logger.HIGH, "Entering NeverNote.noteTableSelection");
3528 // If the ctrl key is pressed, then they are selecting multiple
3529 // entries and we don't want to change the currently viewed note.
3530 if (QApplication.keyboardModifiers().isSet(KeyboardModifier.ControlModifier) &&
3531 QApplication.mouseButtons().isSet(MouseButton.LeftButton))
3534 if (historyGuids.size() == 0) {
3535 historyGuids.add(currentNoteGuid);
3536 historyPosition = 1;
3538 noteTableView.showColumn(Global.noteTableGuidPosition);
3540 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3541 if (!Global.isColumnVisible("guid"))
3542 noteTableView.hideColumn(Global.noteTableGuidPosition);
3544 if (selections.size() > 0) {
3546 menuBar.noteDuplicateAction.setEnabled(true);
3547 menuBar.noteOnlineHistoryAction.setEnabled(true);
3548 menuBar.noteMergeAction.setEnabled(true);
3549 selectedNoteGUIDs.clear();
3550 if (selections.size() != 1 || Global.showDeleted) {
3551 menuBar.noteDuplicateAction.setEnabled(false);
3553 if (selections.size() != 1 || !Global.isConnected) {
3554 menuBar.noteOnlineHistoryAction.setEnabled(false);
3556 if (selections.size() == 1) {
3557 menuBar.noteMergeAction.setEnabled(false);
3559 for (int i=0; i<selections.size(); i++) {
3560 int row = selections.get(i).row();
3562 upButton.setEnabled(false);
3564 upButton.setEnabled(true);
3565 if (row < listManager.getNoteTableModel().rowCount()-1)
3566 downButton.setEnabled(true);
3568 downButton.setEnabled(false);
3569 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
3570 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
3571 currentNoteGuid = (String)ix.values().toArray()[0];
3572 selectedNoteGUIDs.add(currentNoteGuid);
3576 nextButton.setEnabled(true);
3577 prevButton.setEnabled(true);
3579 int endPosition = historyGuids.size()-1;
3580 for (int j=historyPosition; j<=endPosition; j++) {
3581 historyGuids.remove(historyGuids.size()-1);
3583 historyGuids.add(currentNoteGuid);
3584 historyPosition = historyGuids.size();
3586 if (historyPosition <= 1)
3587 prevButton.setEnabled(false);
3588 if (historyPosition == historyGuids.size())
3589 nextButton.setEnabled(false);
3591 fromHistory = false;
3592 scrollToGuid(currentNoteGuid);
3593 refreshEvernoteNote(true);
3594 logger.log(logger.HIGH, "Leaving NeverNote.noteTableSelection");
3596 // Trigger a refresh when the note db has been updated
3597 private void noteIndexUpdated(boolean reload) {
3598 logger.log(logger.HIGH, "Entering NeverNote.noteIndexUpdated");
3600 refreshEvernoteNoteList();
3601 logger.log(logger.HIGH, "Calling note table reload in NeverNote.noteIndexUpdated() - "+reload);
3602 noteTableView.load(reload);
3603 if (currentNoteGuid == null || currentNoteGuid.equals("")) {
3605 if (noteTableView.proxyModel.sortOrder() == SortOrder.AscendingOrder)
3606 pos = noteTableView.proxyModel.rowCount();
3609 if (noteTableView.proxyModel.rowCount() == 0)
3612 QModelIndex i = noteTableView.proxyModel.index(pos-1, Global.noteTableGuidPosition);
3614 currentNoteGuid = (String)i.data();
3618 if (!noteTableView.isColumnHidden(Global.noteTableGuidPosition))
3620 scrollToGuid(currentNoteGuid);
3621 logger.log(logger.HIGH, "Leaving NeverNote.noteIndexUpdated");
3623 // Called when the list of notes is updated
3624 private void refreshEvernoteNoteList() {
3625 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNoteList");
3626 browserWindow.setDisabled(false);
3627 if (selectedNoteGUIDs == null)
3628 selectedNoteGUIDs = new ArrayList<String>();
3629 selectedNoteGUIDs.clear(); // clear out old entries
3631 String saveCurrentNoteGuid = new String();
3632 String tempNoteGuid = new String();
3634 historyGuids.clear();
3635 historyPosition = 0;
3636 prevButton.setEnabled(false);
3637 nextButton.setEnabled(false);
3639 if (currentNoteGuid == null)
3640 currentNoteGuid = new String();
3642 //determine current note guid
3643 for (Note note : listManager.getNoteIndex()) {
3644 tempNoteGuid = note.getGuid();
3645 if (currentNoteGuid.equals(tempNoteGuid)) {
3646 saveCurrentNoteGuid = tempNoteGuid;
3650 if (listManager.getNoteIndex().size() == 0) {
3651 currentNoteGuid = "";
3653 browserWindow.clear();
3654 browserWindow.setDisabled(true);
3657 if (!saveCurrentNoteGuid.equals("")) {
3658 refreshEvernoteNote(false);
3660 currentNoteGuid = "";
3662 reloadTagTree(false);
3664 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNoteList");
3666 // Called when the previous arrow button is clicked
3667 @SuppressWarnings("unused")
3668 private void previousViewedAction() {
3669 if (!prevButton.isEnabled())
3671 if (historyPosition == 0)
3674 if (historyPosition <= 0)
3676 String historyGuid = historyGuids.get(historyPosition-1);
3678 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3679 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3680 if (modelIndex != null) {
3681 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3682 String tableGuid = (String)ix.values().toArray()[0];
3683 if (tableGuid.equals(historyGuid)) {
3684 noteTableView.selectRow(i);
3690 @SuppressWarnings("unused")
3691 private void nextViewedAction() {
3692 if (!nextButton.isEnabled())
3694 String historyGuid = historyGuids.get(historyPosition);
3697 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3698 QModelIndex modelIndex = noteTableView.model().index(i, Global.noteTableGuidPosition);
3699 if (modelIndex != null) {
3700 SortedMap<Integer, Object> ix = noteTableView.model().itemData(modelIndex);
3701 String tableGuid = (String)ix.values().toArray()[0];
3702 if (tableGuid.equals(historyGuid)) {
3703 noteTableView.selectRow(i);
3709 // Called when the up arrow is clicked
3710 @SuppressWarnings("unused")
3711 private void upAction() {
3712 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3713 int row = selections.get(0).row();
3715 noteTableView.selectRow(row-1);
3718 // Called when the down arrow is clicked
3719 @SuppressWarnings("unused")
3720 private void downAction() {
3721 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3722 int row = selections.get(0).row();
3723 int max = listManager.getNoteTableModel().rowCount();
3725 noteTableView.selectRow(row+1);
3728 // Update a tag string for a specific note in the list
3729 @SuppressWarnings("unused")
3730 private void updateListTags(String guid, List<String> tags) {
3731 logger.log(logger.HIGH, "Entering NeverNote.updateListTags");
3732 StringBuffer tagBuffer = new StringBuffer();
3733 for (int i=0; i<tags.size(); i++) {
3734 tagBuffer.append(tags.get(i));
3735 if (i<tags.size()-1)
3736 tagBuffer.append(", ");
3739 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3740 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3741 if (modelIndex != null) {
3742 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3743 String tableGuid = (String)ix.values().toArray()[0];
3744 if (tableGuid.equals(guid)) {
3745 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition,tagBuffer.toString());
3746 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3747 noteTableView.proxyModel.invalidate();
3752 logger.log(logger.HIGH, "Leaving NeverNote.updateListTags");
3754 // Update a title for a specific note in the list
3755 @SuppressWarnings("unused")
3756 private void updateListAuthor(String guid, String author) {
3757 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3759 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3760 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3761 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3762 if (modelIndex != null) {
3763 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3764 String tableGuid = (String)ix.values().toArray()[0];
3765 if (tableGuid.equals(guid)) {
3766 listManager.getNoteTableModel().setData(i, Global.noteTableAuthorPosition,author);
3767 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3768 noteTableView.proxyModel.invalidate();
3774 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3776 private void updateListNoteNotebook(String guid, String notebook) {
3777 logger.log(logger.HIGH, "Entering NeverNote.updateListNoteNotebook");
3778 listManager.getNoteTableModel().updateNoteSyncStatus(guid, false);
3779 logger.log(logger.HIGH, "Leaving NeverNote.updateListNoteNotebook");
3781 // Update a title for a specific note in the list
3782 @SuppressWarnings("unused")
3783 private void updateListSourceUrl(String guid, String url) {
3784 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
3786 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3787 //QModelIndex modelIndex = noteTableView.proxyModel.index(i, Global.noteTableGuidPosition);
3788 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3789 if (modelIndex != null) {
3790 // SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(modelIndex);
3791 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3792 String tableGuid = (String)ix.values().toArray()[0];
3793 if (tableGuid.equals(guid)) {
3794 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3795 listManager.getNoteTableModel().setData(i, Global.noteTableSourceUrlPosition,url);
3796 noteTableView.proxyModel.invalidate();
3801 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
3803 @SuppressWarnings("unused")
3804 private void updateListGuid(String oldGuid, String newGuid) {
3805 logger.log(logger.HIGH, "Entering NeverNote.updateListTitle");
3807 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3808 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3809 if (modelIndex != null) {
3810 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3811 String tableGuid = (String)ix.values().toArray()[0];
3812 if (tableGuid.equals(oldGuid)) {
3813 listManager.getNoteTableModel().setData(i, Global.noteTableGuidPosition,newGuid);
3814 //listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3819 logger.log(logger.HIGH, "Leaving NeverNote.updateListTitle");
3821 private void updateListTagName(String guid) {
3822 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3824 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3825 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3826 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3828 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3829 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3830 if (modelIndex != null) {
3831 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3832 String noteGuid = (String)ix.values().toArray()[0];
3833 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3834 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3835 i=listManager.getNoteTableModel().rowCount();
3841 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3843 private void removeListTagName(String guid) {
3844 logger.log(logger.HIGH, "Entering NeverNote.updateTagName");
3846 for (int j=0; j<listManager.getNoteIndex().size(); j++) {
3847 if (listManager.getNoteIndex().get(j).getTagGuids().contains(guid)) {
3848 for (int i=listManager.getNoteIndex().get(j).getTagGuids().size()-1; i>=0; i--) {
3849 if (listManager.getNoteIndex().get(j).getTagGuids().get(i).equals(guid))
3850 listManager.getNoteIndex().get(j).getTagGuids().remove(i);
3853 String newName = listManager.getTagNamesForNote(listManager.getNoteIndex().get(j));
3854 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3855 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3856 if (modelIndex != null) {
3857 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3858 String noteGuid = (String)ix.values().toArray()[0];
3859 if (noteGuid.equalsIgnoreCase(listManager.getNoteIndex().get(j).getGuid())) {
3860 listManager.getNoteTableModel().setData(i, Global.noteTableTagPosition, newName);
3861 i=listManager.getNoteTableModel().rowCount();
3867 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebook");
3869 private void updateListNotebookName(String oldName, String newName) {
3870 logger.log(logger.HIGH, "Entering NeverNote.updateListNotebookName");
3872 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3873 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableNotebookPosition);
3874 if (modelIndex != null) {
3875 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3876 String tableName = (String)ix.values().toArray()[0];
3877 if (tableName.equalsIgnoreCase(oldName)) {
3878 listManager.getNoteTableModel().setData(i, Global.noteTableNotebookPosition, newName);
3882 logger.log(logger.HIGH, "Leaving NeverNote.updateListNotebookName");
3884 @SuppressWarnings("unused")
3885 private void updateListDateCreated(String guid, QDateTime date) {
3886 logger.log(logger.HIGH, "Entering NeverNote.updateListDateCreated");
3888 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3889 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3890 if (modelIndex != null) {
3891 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3892 String tableGuid = (String)ix.values().toArray()[0];
3893 if (tableGuid.equals(guid)) {
3894 listManager.getNoteTableModel().setData(i, Global.noteTableCreationPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3895 noteTableView.proxyModel.invalidate();
3900 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3902 @SuppressWarnings("unused")
3903 private void updateListDateSubject(String guid, QDateTime date) {
3904 logger.log(logger.HIGH, "Entering NeverNote.updateListDateSubject");
3906 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3907 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3908 if (modelIndex != null) {
3909 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3910 String tableGuid = (String)ix.values().toArray()[0];
3911 if (tableGuid.equals(guid)) {
3912 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3913 listManager.getNoteTableModel().setData(i, Global.noteTableSubjectDatePosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3914 noteTableView.proxyModel.invalidate();
3919 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateCreated");
3921 private void updateListDateChanged(String guid, QDateTime date) {
3922 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3924 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
3925 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
3926 if (modelIndex != null) {
3927 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
3928 String tableGuid = (String)ix.values().toArray()[0];
3929 if (tableGuid.equals(guid)) {
3930 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
3931 listManager.getNoteTableModel().setData(i, Global.noteTableChangedPosition, date.toString(Global.getDateFormat()+" " +Global.getTimeFormat()));
3936 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3938 private void updateListDateChanged() {
3939 logger.log(logger.HIGH, "Entering NeverNote.updateListDateChanged");
3940 QDateTime date = new QDateTime(QDateTime.currentDateTime());
3941 updateListDateChanged(currentNoteGuid, date);
3942 logger.log(logger.HIGH, "Leaving NeverNote.updateListDateChanged");
3945 private void scrollToCurrentGuid() {
3946 //scrollToGuid(currentNoteGuid);
3947 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
3948 if (selections.size() == 0)
3950 QModelIndex index = selections.get(0);
3951 int row = selections.get(0).row();
3952 String guid = (String)index.model().index(row, Global.noteTableGuidPosition).data();
3955 // Scroll to the current GUID in tthe list.
3956 // Scroll to a particular index item
3957 private void scrollToGuid(String guid) {
3958 if (currentNote == null || guid == null)
3960 if (currentNote.isActive() && Global.showDeleted) {
3961 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3962 if (!listManager.getNoteIndex().get(i).isActive()) {
3963 currentNote = listManager.getNoteIndex().get(i);
3964 currentNoteGuid = currentNote.getGuid();
3965 i = listManager.getNoteIndex().size();
3969 if (!currentNote.isActive() && !Global.showDeleted) {
3970 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
3971 if (listManager.getNoteIndex().get(i).isActive()) {
3972 currentNote = listManager.getNoteIndex().get(i);
3973 currentNoteGuid = currentNote.getGuid();
3974 i = listManager.getNoteIndex().size();
3979 for (int i=0; i<noteTableView.model().rowCount(); i++) {
3980 index = noteTableView.model().index(i, Global.noteTableGuidPosition);
3981 if (currentNoteGuid.equals(index.data())) {
3982 // noteTableView.selectionModel().blockSignals(true);
3983 noteTableView.selectRow(i);
3984 // noteTableView.selectionModel().blockSignals(false);
3985 noteTableView.scrollTo(index, ScrollHint.EnsureVisible); // This should work, but it doesn't
3986 i=listManager.getNoteTableModel().rowCount();
3989 noteTableView.repaint();
3991 // Show/Hide columns
3992 private void showColumns() {
3993 noteTableView.setColumnHidden(Global.noteTableCreationPosition, !Global.isColumnVisible("dateCreated"));
3994 noteTableView.setColumnHidden(Global.noteTableChangedPosition, !Global.isColumnVisible("dateChanged"));
3995 noteTableView.setColumnHidden(Global.noteTableSubjectDatePosition, !Global.isColumnVisible("dateSubject"));
3996 noteTableView.setColumnHidden(Global.noteTableAuthorPosition, !Global.isColumnVisible("author"));
3997 noteTableView.setColumnHidden(Global.noteTableSourceUrlPosition, !Global.isColumnVisible("sourceUrl"));
3998 noteTableView.setColumnHidden(Global.noteTableTagPosition, !Global.isColumnVisible("tags"));
3999 noteTableView.setColumnHidden(Global.noteTableNotebookPosition, !Global.isColumnVisible("notebook"));
4000 noteTableView.setColumnHidden(Global.noteTableSynchronizedPosition, !Global.isColumnVisible("synchronized"));
4001 noteTableView.setColumnHidden(Global.noteTableGuidPosition, !Global.isColumnVisible("guid"));
4002 noteTableView.setColumnHidden(Global.noteTableThumbnailPosition, !Global.isColumnVisible("thumbnail"));
4003 noteTableView.setColumnHidden(Global.noteTableTitlePosition, !Global.isColumnVisible("title"));
4005 // Title color has changed
4006 @SuppressWarnings("unused")
4007 private void titleColorChanged(Integer color) {
4008 logger.log(logger.HIGH, "Entering NeverNote.updateListAuthor");
4010 QColor backgroundColor = new QColor();
4011 QColor foregroundColor = new QColor(QColor.black);
4012 backgroundColor.setRgb(color);
4014 if (backgroundColor.rgb() == QColor.black.rgb() || backgroundColor.rgb() == QColor.blue.rgb())
4015 foregroundColor.setRgb(QColor.white.rgb());
4017 if (selectedNoteGUIDs.size() == 0)
4018 selectedNoteGUIDs.add(currentNoteGuid);
4020 for (int j=0; j<selectedNoteGUIDs.size(); j++) {
4021 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4022 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4023 if (modelIndex != null) {
4024 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4025 String tableGuid = (String)ix.values().toArray()[0];
4026 if (tableGuid.equals(selectedNoteGUIDs.get(j))) {
4027 for (int k=0; k<Global.noteTableColumnCount; k++) {
4028 listManager.getNoteTableModel().setData(i, k, backgroundColor, Qt.ItemDataRole.BackgroundRole);
4029 listManager.getNoteTableModel().setData(i, k, foregroundColor, Qt.ItemDataRole.ForegroundRole);
4030 listManager.updateNoteTitleColor(selectedNoteGUIDs.get(j), backgroundColor.rgb());
4032 i=listManager.getNoteTableModel().rowCount();
4037 logger.log(logger.HIGH, "Leaving NeverNote.updateListAuthor");
4039 // Wide list was chosen
4040 public void narrowListView() {
4041 saveNoteColumnPositions();
4042 saveNoteIndexWidth();
4044 int sortCol = noteTableView.proxyModel.sortColumn();
4045 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4046 Global.setSortColumn(sortCol);
4047 Global.setSortOrder(sortOrder);
4049 Global.setListView(Global.View_List_Narrow);
4051 menuBar.wideListView.blockSignals(true);
4052 menuBar.narrowListView.blockSignals(true);
4054 menuBar.wideListView.setChecked(false);
4055 menuBar.narrowListView.setChecked(true);
4057 menuBar.wideListView.blockSignals(false);
4058 menuBar.narrowListView.blockSignals(false);
4060 mainLeftRightSplitter.addWidget(noteTableView);
4061 mainLeftRightSplitter.addWidget(browserWindow);
4062 restoreWindowState(false);
4063 noteTableView.repositionColumns();
4064 noteTableView.resizeColumnWidths();
4065 noteTableView.resizeRowHeights();
4067 sortCol = Global.getSortColumn();
4068 sortOrder = Global.getSortOrder();
4069 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4072 noteTableView.load(false);
4073 refreshEvernoteNote(true);
4074 scrollToCurrentGuid();
4076 public void wideListView() {
4077 int sortCol = noteTableView.proxyModel.sortColumn();
4078 int sortOrder = noteTableView.proxyModel.sortOrder().value();
4079 Global.setSortColumn(sortCol);
4080 Global.setSortOrder(sortOrder);
4083 saveNoteColumnPositions();
4084 saveNoteIndexWidth();
4085 Global.setListView(Global.View_List_Wide);
4087 menuBar.wideListView.blockSignals(true);
4088 menuBar.narrowListView.blockSignals(true);
4090 menuBar.wideListView.setChecked(true);
4091 menuBar.narrowListView.setChecked(false);
4093 menuBar.wideListView.blockSignals(false);
4094 menuBar.narrowListView.blockSignals(false);
4095 browserIndexSplitter.setVisible(true);
4096 browserIndexSplitter.addWidget(noteTableView);
4097 browserIndexSplitter.addWidget(browserWindow);
4098 restoreWindowState(false);
4099 noteTableView.repositionColumns();
4100 noteTableView.resizeColumnWidths();
4101 noteTableView.resizeRowHeights();
4103 sortCol = Global.getSortColumn();
4104 sortOrder = Global.getSortOrder();
4105 noteTableView.sortByColumn(sortCol, SortOrder.resolve(sortOrder));
4108 noteTableView.load(false);
4109 scrollToCurrentGuid();
4113 //***************************************************************
4114 @SuppressWarnings("unused")
4115 private void evernoteLinkClick(String syncGuid, String locGuid) {
4117 if (conn.getNoteTable().guidExists(syncGuid)) {
4120 // If we didn't find it via the synchronized guid, look under the local guid
4121 // Iwe don't find it there, look to see if the GUID is posted under the local GUID, but was
4122 // later synchronized (that causes the guid to change so we need to find the new one).
4123 if (conn.getNoteTable().guidExists(locGuid))
4126 guid = conn.getNoteTable().findAlternateGuid(locGuid);
4129 openExternalEditor(guid);
4133 //If we've gotten this far, we can't find the note
4134 QMessageBox.information(this, tr("Note Not Found"), tr("Sorry, but I can't"+
4135 " seem to find that note."));
4137 //***************************************************************
4138 //***************************************************************
4139 //** External editor window functions
4140 //***************************************************************
4141 //***************************************************************
4142 private void listDoubleClick() {
4144 openExternalEditor(currentNoteGuid);
4146 private void openExternalEditor(String guid) {
4148 if (externalWindows.containsKey(guid)) {
4149 externalWindows.get(guid).raise();
4152 Note note = conn.getNoteTable().getNote(guid, true, true, false, true, true);
4153 // We have a new external editor to create
4154 QIcon appIcon = new QIcon(iconPath+"nevernote.png");
4155 ExternalBrowse newBrowser = new ExternalBrowse(conn);
4156 newBrowser.setWindowIcon(appIcon);
4157 externalWindows.put(guid, newBrowser);
4158 showEditorButtons(newBrowser.getBrowserWindow());
4159 loadNoteBrowserInformation(newBrowser.getBrowserWindow(), guid, note);
4160 setupBrowserWindowListeners(newBrowser.getBrowserWindow(), false);
4161 newBrowser.windowClosing.connect(this, "externalWindowClosing(String)");
4162 newBrowser.getBrowserWindow().noteSignal.titleChanged.connect(this, "externalWindowTitleEdited(String, String)");
4163 newBrowser.getBrowserWindow().noteSignal.tagsChanged.connect(this, "externalWindowTagsEdited(String, List)");
4164 newBrowser.contentsChanged.connect(this, "saveNoteExternalBrowser(String, String, Boolean, BrowserWindow)");
4165 newBrowser.getBrowserWindow().blockApplication.connect(this, "blockApplication(BrowserWindow)");
4166 newBrowser.getBrowserWindow().unblockApplication.connect(this, "unblockApplication()");
4168 browserWindow.noteSignal.tagsChanged.connect(newBrowser, "updateTags(String, List)");
4169 browserWindow.noteSignal.titleChanged.connect(newBrowser, "updateTitle(String, String)");
4170 browserWindow.noteSignal.notebookChanged.connect(newBrowser, "updateNotebook(String, String)");
4174 @SuppressWarnings("unused")
4175 private void externalWindowTitleEdited(String guid, String text) {
4176 if (guid.equals(currentNoteGuid)) {
4177 browserWindow.setTitle(text);
4180 @SuppressWarnings({ "rawtypes", "unused" })
4181 private void externalWindowTagsEdited(String guid, List values) {
4182 StringBuffer line = new StringBuffer(100);
4183 for (int i=0; i<values.size(); i++) {
4185 line.append(Global.tagDelimeter+" ");
4186 line.append(values.get(i));
4188 if (guid.equals(currentNoteGuid)) {
4189 browserWindow.setTag(line.toString());
4192 @SuppressWarnings("unused")
4193 private void externalWindowClosing(String guid) {
4194 externalWindows.remove(guid);
4199 //***************************************************************
4200 //***************************************************************
4201 //** These functions deal with Note specific things
4202 //***************************************************************
4203 //***************************************************************
4204 @SuppressWarnings("unused")
4205 private void setNoteDirty() {
4206 logger.log(logger.EXTREME, "Entering NeverNote.setNoteDirty()");
4208 // Find if the note is being edited externally. If it is, update it.
4209 if (externalWindows.containsKey(currentNoteGuid)) {
4210 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4211 QByteArray unicode = codec.fromUnicode(browserWindow.getContent());
4212 ExternalBrowse window = externalWindows.get(currentNoteGuid);
4213 window.getBrowserWindow().setContent(unicode);
4216 // If the note is dirty, then it is unsynchronized by default.
4220 // Set the note as dirty and check if its status is synchronized in the display table
4222 for (int i=0; i<listManager.getUnsynchronizedNotes().size(); i++) {
4223 if (listManager.getUnsynchronizedNotes().get(i).equals(currentNoteGuid))
4227 // If this wasn't already marked as unsynchronized, then we need to update the table
4228 listManager.getNoteTableModel().updateNoteSyncStatus(currentNoteGuid, false);
4229 /* listManager.getUnsynchronizedNotes().add(currentNoteGuid);
4230 for (int i=0; i<listManager.getNoteTableModel().rowCount(); i++) {
4231 QModelIndex modelIndex = listManager.getNoteTableModel().index(i, Global.noteTableGuidPosition);
4232 if (modelIndex != null) {
4233 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4234 String tableGuid = (String)ix.values().toArray()[0];
4235 if (tableGuid.equals(currentNoteGuid)) {
4236 listManager.getNoteTableModel().setData(i, Global.noteTableSynchronizedPosition, "false");
4242 logger.log(logger.EXTREME, "Leaving NeverNote.setNoteDirty()");
4244 @SuppressWarnings("unused")
4245 private void saveNoteExternalBrowser(String guid, String content, Boolean save, BrowserWindow browser) {
4246 QTextCodec codec = QTextCodec.codecForName("UTF-8");
4247 QByteArray unicode = codec.fromUnicode(content);
4248 noteCache.remove(guid);
4249 noteCache.put(guid, unicode.toString());
4250 if (guid.equals(currentNoteGuid)) {
4252 browserWindow.setContent(unicode);
4255 thumbnailRunner.addWork("GENERATE "+ guid);
4256 saveNote(guid, browser);
4260 private void saveNote() {
4262 saveNote(currentNoteGuid, browserWindow);
4263 thumbnailRunner.addWork("GENERATE "+ currentNoteGuid);
4267 private void saveNote(String guid, BrowserWindow window) {
4268 logger.log(logger.EXTREME, "Inside NeverNote.saveNote()");
4271 logger.log(logger.EXTREME, "Saving to cache");
4272 QTextCodec codec = QTextCodec.codecForLocale();
4273 // QTextDecoder decoder = codec.makeDecoder();
4274 codec = QTextCodec.codecForName("UTF-8");
4275 QByteArray unicode = codec.fromUnicode(window.getContent());
4276 noteCache.put(guid, unicode.toString());
4278 logger.log(logger.EXTREME, "updating list manager");
4279 listManager.updateNoteContent(guid, window.getContent());
4280 logger.log(logger.EXTREME, "Updating title");
4281 listManager.updateNoteTitle(guid, window.getTitle());
4282 updateListDateChanged();
4284 logger.log(logger.EXTREME, "Looking through note index for refreshed note");
4285 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4286 if (listManager.getNoteIndex().get(i).getGuid().equals(guid)) {
4287 currentNote = listManager.getNoteIndex().get(i);
4288 i = listManager.getNoteIndex().size();
4293 // Get a note from Evernote (and put it in the browser)
4294 private void refreshEvernoteNote(boolean reload) {
4295 logger.log(logger.HIGH, "Entering NeverNote.refreshEvernoteNote");
4297 if (Global.disableViewing) {
4298 browserWindow.setEnabled(false);
4303 if (Global.showDeleted || currentNoteGuid == null || currentNoteGuid.equals(""))
4305 Global.cryptCounter =0;
4307 browserWindow.setReadOnly(true);
4315 browserWindow.loadingData(true);
4317 currentNote = conn.getNoteTable().getNote(currentNoteGuid, true,true,false,false,true);
4318 if (currentNote == null)
4320 loadNoteBrowserInformation(browserWindow, currentNoteGuid, currentNote);
4323 private void loadNoteBrowserInformation(BrowserWindow browser, String guid, Note note) {
4324 NoteFormatter formatter = new NoteFormatter(logger, conn, tempFiles);
4325 formatter.setNote(note, Global.pdfPreview());
4326 formatter.setHighlight(listManager.getEnSearch());
4328 if (!noteCache.containsKey(guid)) {
4329 js = new QByteArray();
4330 // We need to prepend the note with <HEAD></HEAD> or encoded characters are ugly
4331 js.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
4332 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>");
4333 js.append("<style type=\"text/css\">en-hilight { background-color: rgb(255,255,0) }</style>");
4334 js.append("<style> img { max-width:100%; }</style>");
4335 js.append("<style type=\"text/css\">en-spell { text-decoration: none; border-bottom: dotted 1px #cc0000; }</style>");
4336 js.append("</head>");
4337 formatter.setNote(note, Global.pdfPreview());
4338 js.append(formatter.rebuildNoteHTML());
4339 js.append("</HTML>");
4340 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml.dtd'>", "");
4341 js.replace("<!DOCTYPE en-note SYSTEM 'http://xml.evernote.com/pub/enml2.dtd'>", "");
4342 js.replace("<?xml version='1.0' encoding='UTF-8'?>", "");
4343 // if (Global.enableHTMLEntitiesFix) {
4344 // browser.getBrowser().setContent(new QByteArray(StringEscapeUtils.unescapeHtml(js.toString())));
4346 browser.setContent(js);
4347 noteCache.put(guid, js.toString());
4349 if (formatter.resourceError)
4350 resourceErrorMessage();
4351 if (formatter.formatError) {
4353 QMessageBox.information(this, tr("Error"),
4354 tr("NeverNote had issues formatting this note." +
4355 " To protect your data this note is being marked as read-only."));
4358 readOnly = formatter.readOnly;
4359 inkNote = formatter.inkNote;
4361 readOnlyCache.put(guid, true);
4363 inkNoteCache.put(guid, true);
4365 logger.log(logger.HIGH, "Note content is being pulled from the cache");
4366 String cachedContent = formatter.modifyCachedTodoTags(noteCache.get(guid));
4367 js = new QByteArray(cachedContent);
4368 browser.setContent(js);
4369 if (readOnlyCache.containsKey(guid))
4371 if (inkNoteCache.containsKey(guid))
4374 if (conn.getNoteTable().isThumbnailNeeded(guid)) {
4375 thumbnailHTMLReady(guid, js, Global.calculateThumbnailZoom(js.toString()));
4377 if (readOnly || inkNote)
4378 browser.getBrowser().page().setContentEditable(false); // We don't allow editing of ink notes
4380 browser.getBrowser().page().setContentEditable(true);
4381 browser.setReadOnly(readOnly);
4382 deleteButton.setEnabled(!readOnly);
4383 tagButton.setEnabled(!readOnly);
4384 menuBar.noteDelete.setEnabled(!readOnly);
4385 menuBar.noteTags.setEnabled(!readOnly);
4386 browser.setNote(note);
4388 if (note != null && note.getNotebookGuid() != null &&
4389 conn.getNotebookTable().isLinked(note.getNotebookGuid())) {
4390 deleteButton.setEnabled(false);
4391 menuBar.notebookDeleteAction.setEnabled(false);
4393 deleteButton.setEnabled(true);
4394 menuBar.notebookDeleteAction.setEnabled(true);
4397 // Build a list of non-closed notebooks
4398 List<Notebook> nbooks = new ArrayList<Notebook>();
4399 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4400 boolean found=false;
4401 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4402 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid()))
4406 nbooks.add(listManager.getNotebookIndex().get(i));
4409 browser.setTitle(note.getTitle());
4410 browser.setTag(getTagNamesForNote(note));
4411 browser.setAuthor(note.getAttributes().getAuthor());
4413 browser.setAltered(note.getUpdated());
4414 browser.setCreation(note.getCreated());
4415 if (note.getAttributes().getSubjectDate() > 0)
4416 browser.setSubjectDate(note.getAttributes().getSubjectDate());
4418 browser.setSubjectDate(note.getCreated());
4419 browser.setUrl(note.getAttributes().getSourceURL());
4421 FilterEditorTags tagFilter = new FilterEditorTags(conn, logger);
4422 List<Tag> tagList = tagFilter.getValidTags(note);
4423 browser.setAllTags(tagList);
4425 browser.setCurrentTags(note.getTagNames());
4429 browser.loadingData(false);
4430 if (thumbnailViewer.isActiveWindow())
4433 FilterEditorNotebooks notebookFilter = new FilterEditorNotebooks(conn, logger);
4434 browser.setNotebookList(notebookFilter.getValidNotebooks(note, listManager.getNotebookIndex()));
4437 logger.log(logger.HIGH, "Leaving NeverNote.refreshEvernoteNote");
4439 // Save a generated thumbnail
4440 private void toggleNoteInformation() {
4441 logger.log(logger.HIGH, "Entering NeverNote.toggleNoteInformation");
4442 browserWindow.toggleInformation();
4443 menuBar.noteAttributes.setChecked(browserWindow.isExtended());
4444 Global.saveWindowVisible("noteInformation", browserWindow.isExtended());
4445 logger.log(logger.HIGH, "Leaving NeverNote.toggleNoteInformation");
4447 // Listener triggered when a print button is pressed
4448 @SuppressWarnings("unused")
4449 private void printNote() {
4450 logger.log(logger.HIGH, "Entering NeverNote.printNote");
4452 QPrintDialog dialog = new QPrintDialog();
4453 if (dialog.exec() == QDialog.DialogCode.Accepted.value()) {
4454 QPrinter printer = dialog.printer();
4455 browserWindow.getBrowser().print(printer);
4457 logger.log(logger.HIGH, "Leaving NeverNote.printNote");
4460 // Listener triggered when the email button is pressed
4461 @SuppressWarnings("unused")
4462 private void emailNote() {
4463 logger.log(logger.HIGH, "Entering NeverNote.emailNote");
4465 if (Desktop.isDesktopSupported()) {
4466 Desktop desktop = Desktop.getDesktop();
4468 String text2 = browserWindow.getContentsToEmail();
4469 QUrl url = new QUrl("mailto:");
4470 url.addQueryItem("subject", currentNote.getTitle());
4471 // url.addQueryItem("body", QUrl.toPercentEncoding(text2).toString());
4472 url.addQueryItem("body", text2);
4473 QDesktopServices.openUrl(url);
4477 if (desktop.isSupported(Desktop.Action.MAIL)) {
4478 URI uriMailTo = null;
4480 //String text = browserWindow.getBrowser().page().currentFrame().toPlainText();
4481 String text = browserWindow.getContentsToEmail();
4482 //text = "<b>" +text +"</b>";
4483 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4484 +"&BODY=" +text, null);
4485 uriMailTo = new URI("mailto", "&SUBJECT="+currentNote.getTitle()
4486 +"&ATTACHMENT=d:/test.pdf", null);
4487 desktop.mail(uriMailTo);
4488 } catch (URISyntaxException e) {
4489 e.printStackTrace();
4490 } catch (IOException e) {
4491 e.printStackTrace();
4498 logger.log(logger.HIGH, "Leaving NeverNote.emailNote");
4500 // Reindex all notes
4501 @SuppressWarnings("unused")
4502 private void fullReindex() {
4503 logger.log(logger.HIGH, "Entering NeverNote.fullReindex");
4504 indexRunner.addWork("REINDEXALL");
4505 setMessage(tr("Database will be reindexed."));
4506 logger.log(logger.HIGH, "Leaving NeverNote.fullReindex");
4508 // Listener when a user wants to reindex a specific note
4509 @SuppressWarnings("unused")
4510 private void reindexNote() {
4511 logger.log(logger.HIGH, "Entering NeverNote.reindexNote");
4512 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4513 indexRunner.addWork("REINDEXNOTE "+selectedNoteGUIDs.get(i));
4515 if (selectedNotebookGUIDs.size() > 1)
4516 setMessage(tr("Notes will be reindexed."));
4518 setMessage(tr("Note will be reindexed."));
4519 logger.log(logger.HIGH, "Leaving NeverNote.reindexNote");
4522 @SuppressWarnings("unused")
4523 private void deleteNote() {
4524 logger.log(logger.HIGH, "Entering NeverNote.deleteNote");
4525 if (currentNote == null)
4527 if (currentNoteGuid.equals(""))
4529 String title = null;
4530 if (selectedNoteGUIDs.size() == 1)
4531 title = conn.getNoteTable().getNote(selectedNoteGUIDs.get(0),false,false,false,false,false).getTitle();
4533 // If we are deleting non-trash notes
4534 if (currentNote.isActive()) {
4535 if (Global.verifyDelete()) {
4537 if (selectedNoteGUIDs.size() > 1) {
4538 msg = new String(tr("Delete ") +selectedNoteGUIDs.size() +" notes?");
4541 msg = new String(tr("Delete note \"") +title +"\"?");
4543 msg = new String(tr("Delete note selected note?"));
4545 if (QMessageBox.question(this, tr("Confirmation"), msg,
4546 QMessageBox.StandardButton.Yes,
4547 QMessageBox.StandardButton.No)==StandardButton.No.value() && Global.verifyDelete() == true) {
4551 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4552 selectedNoteGUIDs.add(currentNoteGuid);
4553 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4554 listManager.deleteNote(selectedNoteGUIDs.get(i));
4557 // If we are deleting from the trash.
4558 if (Global.verifyDelete()) {
4560 if (selectedNoteGUIDs.size() > 1) {
4561 msg = new String(tr("Permanently delete ") +selectedNoteGUIDs.size() +" notes?");
4564 msg = new String(tr("Permanently delete note \"") +title +"\"?");
4566 msg = new String(tr("Permanently delete note selected note?"));
4568 if (QMessageBox.question(this, "Confirmation", msg,
4569 QMessageBox.StandardButton.Yes,
4570 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
4574 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4575 selectedNoteGUIDs.add(currentNoteGuid);
4576 for (int i=selectedNoteGUIDs.size()-1; i>=0; i--) {
4577 for (int j=listManager.getNoteTableModel().rowCount()-1; j>=0; j--) {
4578 QModelIndex modelIndex = listManager.getNoteTableModel().index(j, Global.noteTableGuidPosition);
4579 if (modelIndex != null) {
4580 SortedMap<Integer, Object> ix = listManager.getNoteTableModel().itemData(modelIndex);
4581 String tableGuid = (String)ix.values().toArray()[0];
4582 if (tableGuid.equals(selectedNoteGUIDs.get(i))) {
4583 listManager.getNoteTableModel().removeRow(j);
4588 listManager.expungeNote(selectedNoteGUIDs.get(i));
4591 currentNoteGuid = "";
4592 listManager.loadNotesIndex();
4593 noteIndexUpdated(false);
4594 refreshEvernoteNote(true);
4595 scrollToGuid(currentNoteGuid);
4596 logger.log(logger.HIGH, "Leaving NeverNote.deleteNote");
4599 @SuppressWarnings("unused")
4600 private void addNote() {
4601 logger.log(logger.HIGH, "Inside NeverNote.addNote");
4602 // browserWindow.setEnabled(true);
4603 browserWindow.setReadOnly(false);
4605 Calendar currentTime = new GregorianCalendar();
4606 StringBuffer noteString = new StringBuffer(100);
4607 noteString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
4608 "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n" +
4611 if (Global.overrideDefaultFont()) {
4612 noteString.append("<font face=\"" +Global.getDefaultFont() +"\" >");
4613 noteString.append("<span style=\"font-size:" +Global.getDefaultFontSize() +"pt;\">");
4614 noteString.append("<br clear=\"none\" />\n");
4615 noteString.append("</span>\n</font>\n");
4617 noteString.append("<br clear=\"none\" />\n");
4618 noteString.append("</en-note>");
4620 Long l = new Long(currentTime.getTimeInMillis());
4621 String randint = new String(Long.toString(l));
4623 // Find a notebook. We first look for a selected notebook (the "All Notebooks" one doesn't count).
4625 // for the first non-archived notebook. Finally, if nothing else we
4626 // pick the first notebook in the list.
4627 String notebook = null;
4628 listManager.getNotebookIndex().get(0).getGuid();
4629 List<QTreeWidgetItem> selectedNotebook = notebookTree.selectedItems();
4630 if (selectedNotebook.size() > 0 && !selectedNotebook.get(0).text(0).equalsIgnoreCase("All Notebooks")) {
4631 QTreeWidgetItem currentSelectedNotebook = selectedNotebook.get(0);
4632 notebook = currentSelectedNotebook.text(2);
4634 boolean found = false;
4635 List<Notebook> goodNotebooks = new ArrayList<Notebook>();
4636 for (int i=0; i<listManager.getNotebookIndex().size(); i++) {
4637 boolean match = false;
4638 for (int j=0; j<listManager.getArchiveNotebookIndex().size(); j++) {
4639 if (listManager.getArchiveNotebookIndex().get(j).getGuid().equals(listManager.getNotebookIndex().get(i).getGuid())) {
4641 j = listManager.getArchiveNotebookIndex().size();
4645 //goodNotebooks.add(listManager.getNotebookIndex().get(i).deepCopy());
4646 goodNotebooks.add((Notebook)Global.deepCopy(listManager.getNotebookIndex().get(i)));
4648 // Now we have a list of good notebooks, so we can look for the default
4650 for (int i=0; i<goodNotebooks.size(); i++) {
4651 if (goodNotebooks.get(i).isDefaultNotebook()) {
4652 notebook = goodNotebooks.get(i).getGuid();
4654 i = goodNotebooks.size();
4658 if (goodNotebooks.size() > 0 && !found)
4659 notebook = goodNotebooks.get(0).getGuid();
4662 notebook = listManager.getNotebookIndex().get(0).getGuid();
4665 Note newNote = new Note();
4666 newNote.setUpdateSequenceNum(0);
4667 newNote.setGuid(randint);
4668 newNote.setNotebookGuid(notebook);
4669 newNote.setTitle("Untitled Note");
4670 newNote.setContent(noteString.toString());
4671 newNote.setDeleted(0);
4672 newNote.setCreated(System.currentTimeMillis());
4673 newNote.setUpdated(System.currentTimeMillis());
4674 newNote.setActive(true);
4675 NoteAttributes na = new NoteAttributes();
4676 na.setLatitude(0.0);
4677 na.setLongitude(0.0);
4678 na.setAltitude(0.0);
4679 newNote.setAttributes(new NoteAttributes());
4680 newNote.setTagGuids(new ArrayList<String>());
4681 newNote.setTagNames(new ArrayList<String>());
4683 // If new notes are to be created based upon the selected tags, then we need to assign the tags
4684 if (Global.newNoteWithSelectedTags()) {
4685 List<QTreeWidgetItem> selections = tagTree.selectedItems();
4686 QTreeWidgetItem currentSelection;
4687 for (int i=0; i<selections.size(); i++) {
4688 currentSelection = selections.get(i);
4689 newNote.getTagGuids().add(currentSelection.text(2));
4690 newNote.getTagNames().add(currentSelection.text(0));
4694 conn.getNoteTable().addNote(newNote, true);
4695 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4696 listManager.addNote(newNote);
4697 // noteTableView.insertRow(newNote, true, -1);
4699 currentNote = newNote;
4700 currentNoteGuid = currentNote.getGuid();
4701 noteTableView.clearSelection();
4702 refreshEvernoteNote(true);
4703 listManager.countNotebookResults(listManager.getNoteIndex());
4704 browserWindow.titleLabel.setFocus();
4705 browserWindow.titleLabel.selectAll();
4706 // notebookTree.updateCounts(listManager.getNotebookIndex(), listManager.getNotebookCounter());
4708 // If the window is hidden, then we want to popup this in an external window &
4712 logger.log(logger.HIGH, "Leaving NeverNote.addNote");
4714 // Restore a note from the trash;
4715 @SuppressWarnings("unused")
4716 private void restoreNote() {
4718 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
4719 selectedNoteGUIDs.add(currentNoteGuid);
4720 for (int i=0; i<selectedNoteGUIDs.size(); i++) {
4721 listManager.restoreNote(selectedNoteGUIDs.get(i));
4723 currentNoteGuid = "";
4724 listManager.loadNotesIndex();
4725 noteIndexUpdated(false);
4728 // Search a note for specific txt
4729 @SuppressWarnings("unused")
4730 private void findText() {
4732 find.setFocusOnTextField();
4734 @SuppressWarnings("unused")
4735 private void doFindText() {
4736 browserWindow.getBrowser().page().findText(find.getText(), find.getFlags());
4739 @SuppressWarnings("unused")
4740 private void updateNoteTitle(String guid, String title) {
4741 listManager.setNoteSynchronized(guid, false);
4743 // Signal received that note content has changed. Normally we just need the guid to remove
4744 // it from the cache.
4745 @SuppressWarnings("unused")
4746 private void invalidateNoteCache(String guid, String content) {
4747 noteCache.remove(guid);
4748 refreshEvernoteNote(true);
4750 // Signal received that a note guid has changed
4751 @SuppressWarnings("unused")
4752 private void noteGuidChanged(String oldGuid, String newGuid) {
4753 if (noteCache.containsKey(oldGuid)) {
4754 if (!oldGuid.equals(currentNoteGuid)) {
4755 String cache = noteCache.get(oldGuid);
4756 noteCache.put(newGuid, cache);
4757 noteCache.remove(oldGuid);
4759 noteCache.remove(oldGuid);
4760 noteCache.put(newGuid, browserWindow.getContent());
4764 listManager.updateNoteGuid(oldGuid, newGuid, false);
4765 if (currentNoteGuid.equals(oldGuid)) {
4766 if (currentNote != null)
4767 currentNote.setGuid(newGuid);
4768 currentNoteGuid = newGuid;
4771 if (externalWindows.containsKey(oldGuid)) {
4772 ExternalBrowse b = externalWindows.get(oldGuid);
4773 externalWindows.remove(oldGuid);
4774 b.getBrowserWindow().getNote().setGuid(newGuid);
4775 externalWindows.put(newGuid, b);
4778 for (int i=0; i<listManager.getNoteIndex().size(); i++) {
4779 if (listManager.getNoteIndex().get(i).getGuid().equals(newGuid)) {
4780 noteTableView.proxyModel.addGuid(newGuid);
4781 i=listManager.getNoteIndex().size();
4785 if (listManager.getNoteTableModel().titleColors.containsKey(oldGuid)) {
4786 int color = listManager.getNoteTableModel().titleColors.get(oldGuid);
4787 listManager.getNoteTableModel().titleColors.put(newGuid, color);
4788 listManager.getNoteTableModel().titleColors.remove(oldGuid);
4792 // Toggle the note editor button bar
4793 private void toggleEditorButtonBar() {
4794 if (browserWindow.buttonsVisible) {
4795 browserWindow.hideButtons();
4796 menuBar.showEditorBar.setChecked(browserWindow.buttonsVisible);
4797 // Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4799 browserWindow.buttonsVisible = true;
4800 showEditorButtons(browserWindow);
4802 Global.saveWindowVisible("editorButtonBar", browserWindow.buttonsVisible);
4804 // Show editor buttons
4805 private void showEditorButtons(BrowserWindow browser) {
4806 browser.buttonLayout.setVisible(true);
4807 browser.undoAction.setVisible(false);
4809 browser.undoButton.setVisible(false);
4811 browser.undoAction.setVisible(Global.isEditorButtonVisible("undo"));
4812 browser.redoAction.setVisible(Global.isEditorButtonVisible("redo"));
4813 browser.cutAction.setVisible(Global.isEditorButtonVisible("cut"));
4814 browser.copyAction.setVisible(Global.isEditorButtonVisible("copy"));
4815 browser.pasteAction.setVisible(Global.isEditorButtonVisible("paste"));
4816 browser.strikethroughAction.setVisible(Global.isEditorButtonVisible("strikethrough"));
4817 browser.underlineAction.setVisible(Global.isEditorButtonVisible("underline"));
4818 browser.boldAction.setVisible(Global.isEditorButtonVisible("bold"));
4819 browser.italicAction.setVisible(Global.isEditorButtonVisible("italic"));
4820 browser.hlineAction.setVisible(Global.isEditorButtonVisible("hline"));
4821 browser.indentAction.setVisible(Global.isEditorButtonVisible("indent"));
4822 browser.outdentAction.setVisible(Global.isEditorButtonVisible("outdent"));
4823 browser.bulletListAction.setVisible(Global.isEditorButtonVisible("bulletList"));
4824 browser.numberListAction.setVisible(Global.isEditorButtonVisible("numberList"));
4825 browser.fontListAction.setVisible(Global.isEditorButtonVisible("font"));
4826 browser.fontSizeAction.setVisible(Global.isEditorButtonVisible("fontSize"));
4827 browser.fontColorAction.setVisible(Global.isEditorButtonVisible("fontColor"));
4828 browser.fontHilightAction.setVisible(Global.isEditorButtonVisible("fontHilight"));
4829 browser.leftAlignAction.setVisible(Global.isEditorButtonVisible("alignLeft"));
4830 browser.centerAlignAction.setVisible(Global.isEditorButtonVisible("alignCenter"));
4831 browser.rightAlignAction.setVisible(Global.isEditorButtonVisible("alignRight"));
4832 browser.spellCheckAction.setVisible(Global.isEditorButtonVisible("spellCheck"));
4833 browser.todoAction.setVisible(Global.isEditorButtonVisible("todo"));
4835 private void duplicateNote(String guid) {
4837 Note oldNote = conn.getNoteTable().getNote(guid, true, false,false,false,true);
4838 List<Resource> resList = conn.getNoteTable().noteResourceTable.getNoteResources(guid, true);
4839 oldNote.setContent(conn.getNoteTable().getNoteContentBinary(guid));
4840 oldNote.setResources(resList);
4841 duplicateNote(oldNote);
4843 private void duplicateNote(Note oldNote) {
4845 // Now that we have a good notebook guid, we need to move the conflicting note
4846 // to the local notebook
4847 Calendar currentTime = new GregorianCalendar();
4848 Long l = new Long(currentTime.getTimeInMillis());
4849 String newGuid = new String(Long.toString(l));
4851 // Note newNote = oldNote.deepCopy();
4852 Note newNote = (Note)Global.deepCopy(oldNote);
4853 newNote.setUpdateSequenceNum(0);
4854 newNote.setGuid(newGuid);
4855 newNote.setDeleted(0);
4856 newNote.setActive(true);
4859 List<String> tagNames = new ArrayList<String>();
4860 List<String> tagGuids = new ArrayList<String>();;
4861 for (int i=0; i<oldNote.getTagGuidsSize(); i++) {
4862 tagNames.add(oldNote.getTagNames().get(i));
4863 tagGuids.add(oldNote.getTagGuids().get(i));
4866 // Sort note Tags to make them look nice
4867 for (int i=0; i<tagNames.size()-1; i++) {
4868 if (tagNames.get(i).compareTo(tagNames.get(i+1))<0) {
4869 String n1 = tagNames.get(i);
4870 String n2 = tagNames.get(i+1);
4871 tagNames.set(i, n2);
4872 tagNames.set(i+1, n1);
4875 newNote.setTagGuids(tagGuids);
4876 newNote.setTagNames(tagNames);
4878 // Add tag guids to note
4881 // Duplicate resources
4882 List<Resource> resList = oldNote.getResources();
4883 if (resList == null)
4884 resList = new ArrayList<Resource>();
4886 for (int i=0; i<resList.size(); i++) {
4888 while (l == prevGuid) {
4889 currentTime = new GregorianCalendar();
4890 l = new Long(currentTime.getTimeInMillis());
4893 String newResGuid = new String(Long.toString(l));
4894 resList.get(i).setNoteGuid(newGuid);
4895 resList.get(i).setGuid(newResGuid);
4896 resList.get(i).setUpdateSequenceNum(0);
4897 resList.get(i).setActive(true);
4898 conn.getNoteTable().noteResourceTable.saveNoteResource(
4899 (Resource)Global.deepCopy(resList.get(i)), true);
4901 newNote.setResources(resList);
4903 // Add note to the database
4904 listManager.addNote(newNote);
4905 conn.getNoteTable().addNote(newNote, true);
4906 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
4907 noteTableView.insertRow(newNote, true, -1);
4908 currentNoteGuid = newNote.getGuid();
4909 currentNote = newNote;
4910 refreshEvernoteNote(true);
4911 listManager.countNotebookResults(listManager.getNoteIndex());
4915 @SuppressWarnings("unused")
4916 private void allNotes() {
4917 clearAttributeFilter();
4918 clearNotebookFilter();
4919 clearSavedSearchFilter();
4922 searchField.clear();
4923 if (Global.mimicEvernoteInterface) {
4924 notebookTree.selectGuid("");
4926 notebookTreeSelection();
4927 refreshEvernoteNote(true);
4930 @SuppressWarnings("unused")
4931 private void mergeNotes() {
4932 logger.log(logger.HIGH, "Merging notes");
4935 String masterGuid = null;
4936 List<String> sources = new ArrayList<String>();
4938 for (int i=0; i<noteTableView.selectionModel().selectedRows().size(); i++) {
4939 int r = noteTableView.selectionModel().selectedRows().get(i).row();
4940 index = noteTableView.proxyModel.index(r, Global.noteTableGuidPosition);
4941 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
4943 masterGuid = (String)ix.values().toArray()[0];
4945 sources.add((String)ix.values().toArray()[0]);
4948 logger.log(logger.EXTREME, "Master guid=" +masterGuid);
4949 logger.log(logger.EXTREME, "Children count: "+sources.size());
4950 mergeNoteContents(masterGuid, sources);
4951 currentNoteGuid = masterGuid;
4952 noteIndexUpdated(false);
4953 refreshEvernoteNote(true);
4956 private void mergeNoteContents(String targetGuid, List<String> sources) {
4957 Note target = conn.getNoteTable().getNote(targetGuid, true, false, false, false, false);
4958 String newContent = target.getContent();
4959 newContent = newContent.replace("</en-note>", "<br></br>");
4961 for (int i=0; i<sources.size(); i++) {
4962 Note source = conn.getNoteTable().getNote(sources.get(i), true, true, false, false, false);
4963 if (source.isSetTitle()) {
4964 newContent = newContent +("<table bgcolor=\"lightgrey\"><tr><td><font size=\"6\"><b>" +source.getTitle() +"</b></font></td></tr></table>");
4966 String sourceContent = source.getContent();
4967 logger.log(logger.EXTREME, "Merging contents into note");
4968 logger.log(logger.EXTREME, sourceContent);
4969 logger.log(logger.EXTREME, "End of content");
4970 int startOfNote = sourceContent.indexOf("<en-note>");
4971 sourceContent = sourceContent.substring(startOfNote+9);
4972 int endOfNote = sourceContent.indexOf("</en-note>");
4973 sourceContent = sourceContent.substring(0,endOfNote);
4974 newContent = newContent + sourceContent;
4975 logger.log(logger.EXTREME, "New note content");
4976 logger.log(logger.EXTREME, newContent);
4977 logger.log(logger.EXTREME, "End of content");
4978 for (int j=0; j<source.getResourcesSize(); j++) {
4979 logger.log(logger.EXTREME, "Reassigning resource: "+source.getResources().get(j).getGuid());
4980 Resource r = source.getResources().get(j);
4981 Resource newRes = conn.getNoteTable().noteResourceTable.getNoteResource(r.getGuid(), true);
4983 Calendar currentTime = new GregorianCalendar();
4984 Long l = new Long(currentTime.getTimeInMillis());
4988 while (l == prevGuid) {
4989 currentTime = new GregorianCalendar();
4990 l = new Long(currentTime.getTimeInMillis());
4992 String newResGuid = new String(Long.toString(l));
4993 newRes.setNoteGuid(targetGuid);
4994 newRes.setGuid(newResGuid);
4995 newRes.setUpdateSequenceNum(0);
4996 newRes.setActive(true);
4997 conn.getNoteTable().noteResourceTable.saveNoteResource(newRes, true);
5000 logger.log(logger.EXTREME, "Updating note");
5001 conn.getNoteTable().updateNoteContent(targetGuid, newContent +"</en-note>");
5002 for (int i=0; i<sources.size(); i++) {
5003 logger.log(logger.EXTREME, "Deleting note " +sources.get(i));
5004 listManager.deleteNote(sources.get(i));
5006 logger.log(logger.EXTREME, "Exiting merge note");
5008 // A resource within a note has had a guid change
5009 @SuppressWarnings("unused")
5010 private void noteResourceGuidChanged(String noteGuid, String oldGuid, String newGuid) {
5011 if (oldGuid != null && !oldGuid.equals(newGuid))
5012 Global.resourceMap.put(oldGuid, newGuid);
5014 // View a thumbnail of the note
5015 public void thumbnailView() {
5017 String thumbnailName = Global.getFileManager().getResDirPath("thumbnail-" + currentNoteGuid + ".png");
5018 QFile thumbnail = new QFile(thumbnailName);
5019 if (!thumbnail.exists()) {
5021 QImage img = new QImage();
5022 img.loadFromData(conn.getNoteTable().getThumbnail(currentNoteGuid));
5023 thumbnailViewer.setThumbnail(img);
5025 thumbnailViewer.setThumbnail(thumbnailName);
5026 if (!thumbnailViewer.isVisible())
5027 thumbnailViewer.showFullScreen();
5029 // An error happened while saving a note. Inform the user
5030 @SuppressWarnings("unused")
5031 private void saveRunnerError(String guid, String msg) {
5033 String title = "*Unknown*";
5034 for (int i=0; i<listManager.getMasterNoteIndex().size(); i++) {
5035 if (listManager.getMasterNoteIndex().get(i).getGuid().equals(guid)) {
5036 title = listManager.getMasterNoteIndex().get(i).getTitle();
5037 i=listManager.getMasterNoteIndex().size();
5040 msg = tr("An error has happened while saving the note \"") +title+
5041 tr("\".\n\nThis is probably due to a document that is too complex for Nevernote to process. "+
5042 "As a result, changes to the note may not be saved properly in the database."+
5043 "\n\nA cached copy is being preserved so you can recover any data, but data may" +
5044 "\nbe lost. Please review the note to recover any critical data before restarting.");
5046 QMessageBox.information(this, tr("Error Saving Note"), tr(msg));
5049 private void thumbnailHTMLReady(String guid, QByteArray html, Integer zoom) {
5050 logger.log(logger.HIGH, "Entering thumnailHTMLReady()");
5051 logger.log(logger.HIGH, "Thumbnail ready for " +guid);
5052 // Find an idle preview object
5053 for (int i=0; i<thumbGenerators.size(); i++) {
5054 if (thumbGenerators.get(i).mutex.tryLock()) {
5055 logger.log(logger.EXTREME, "Idle generator found - loading thumbnail for " +guid);
5056 thumbGenerators.get(i).loadContent(guid, html, zoom);
5060 if (thumbGenerators.size() >= 1) {
5061 logger.log(logger.EXTREME, "No available thumbnail generators. Aborting " +guid);
5065 logger.log(logger.EXTREME, "Creating new thumbnail generator " +guid);
5066 Thumbnailer preview = new Thumbnailer(logger, conn, listManager, thumbnailRunner);
5067 thumbGenerators.add(preview);
5069 if (preview.mutex.tryLock()) {
5070 logger.log(logger.EXTREME, "Loading thumbnail for " +guid);
5071 preview.loadContent(guid, html, zoom);
5073 logger.log(logger.HIGH, "Exiting thumnailHTMLReady()");
5078 //**********************************************************
5079 //**********************************************************
5080 //* Online user actions
5081 //**********************************************************
5082 //**********************************************************
5083 private void setupOnlineMenu() {
5084 if (!Global.isConnected) {
5085 menuBar.noteOnlineHistoryAction.setEnabled(false);
5086 menuBar.selectiveSyncAction.setEnabled(false);
5089 menuBar.noteOnlineHistoryAction.setEnabled(true);
5090 menuBar.selectiveSyncAction.setEnabled(true);
5093 @SuppressWarnings("unused")
5094 private void viewNoteHistory() {
5095 if (currentNoteGuid == null || currentNoteGuid.equals(""))
5097 if (currentNote.getUpdateSequenceNum() == 0) {
5098 setMessage(tr("Note has never been synchronized."));
5099 QMessageBox.information(this, tr("Error"), tr("This note has never been sent to Evernote, so there is no history."));
5103 setMessage(tr("Getting Note History"));
5105 Note currentOnlineNote = null;
5108 if (Global.isPremium())
5109 versions = syncRunner.localNoteStore.listNoteVersions(syncRunner.authToken, currentNoteGuid);
5111 versions = new ArrayList<NoteVersionId>();
5112 currentOnlineNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true, true, false, false);
5113 } catch (EDAMUserException e) {
5114 setMessage("EDAMUserException: " +e.getMessage());
5116 } catch (EDAMSystemException e) {
5117 setMessage("EDAMSystemException: " +e.getMessage());
5119 } catch (EDAMNotFoundException e) {
5120 setMessage(tr("Note not found on server."));
5121 QMessageBox.information(this, tr("Error"), tr("This note could not be found on Evernote's servers."));
5123 } catch (TException e) {
5124 setMessage("EDAMTransactionException: " +e.getMessage());
5128 // If we've gotten this far, we have a good note.
5129 if (historyWindow == null) {
5130 historyWindow = new OnlineNoteHistory(logger, conn);
5131 historyWindow.historyCombo.activated.connect(this, "reloadHistoryWindow(String)");
5132 historyWindow.restoreAsNew.clicked.connect(this, "restoreHistoryNoteAsNew()");
5133 historyWindow.restore.clicked.connect(this, "restoreHistoryNote()");
5135 historyWindow.historyCombo.clear();
5137 boolean isDirty = conn.getNoteTable().isNoteDirty(currentNoteGuid);
5138 if (currentNote.getUpdateSequenceNum() != currentOnlineNote.getUpdateSequenceNum())
5140 historyWindow.setCurrent(isDirty);
5142 loadHistoryWindowContent(currentOnlineNote);
5143 historyWindow.load(versions);
5144 setMessage(tr("History retrieved"));
5146 historyWindow.exec();
5148 private Note reloadHistoryWindow(String selection) {
5150 String fmt = Global.getDateFormat() + " " + Global.getTimeFormat();
5151 String dateTimeFormat = new String(fmt);
5152 SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat);
5156 for (int i=0; i<versions.size(); i++) {
5157 StringBuilder versionDate = new StringBuilder(simple.format(versions.get(i).getSaved()));
5158 if (versionDate.toString().equals(selection))
5162 if (index > -1 || selection.indexOf("Current") > -1) {
5163 Note historyNote = null;
5166 usn = versions.get(index).getUpdateSequenceNum();
5167 historyNote = syncRunner.localNoteStore.getNoteVersion(syncRunner.authToken, currentNoteGuid, usn, true, true, true);
5169 historyNote = syncRunner.localNoteStore.getNote(syncRunner.authToken, currentNoteGuid, true,true,true,true);
5170 } catch (EDAMUserException e) {
5171 setMessage("EDAMUserException: " +e.getMessage());
5174 } catch (EDAMSystemException e) {
5175 setMessage("EDAMSystemException: " +e.getMessage());
5178 } catch (EDAMNotFoundException e) {
5179 setMessage("EDAMNotFoundException: " +e.getMessage());
5182 } catch (TException e) {
5183 setMessage("EDAMTransactionException: " +e.getMessage());
5189 if (historyNote != null)
5190 historyWindow.setContent(historyNote);
5196 private void loadHistoryWindowContent(Note note) {
5197 note.setUpdateSequenceNum(0);
5198 historyWindow.setContent(note);
5200 @SuppressWarnings("unused")
5201 private void restoreHistoryNoteAsNew() {
5202 setMessage(tr("Restoring as new note."));
5203 duplicateNote(reloadHistoryWindow(historyWindow.historyCombo.currentText()));
5204 setMessage(tr("Note has been restored as a new note."));
5206 @SuppressWarnings("unused")
5207 private void restoreHistoryNote() {
5208 setMessage(tr("Restoring note."));
5209 Note n = reloadHistoryWindow(historyWindow.historyCombo.currentText());
5210 conn.getNoteTable().expungeNote(n.getGuid(), true, false);
5213 for (int i=0; i<n.getResourcesSize(); i++) {
5214 n.getResources().get(i).setActive(true);
5215 conn.getNoteTable().noteResourceTable.saveNoteResource(n.getResources().get(i), true);
5217 listManager.addNote(n);
5218 conn.getNoteTable().addNote(n, true);
5219 refreshEvernoteNote(true);
5220 setMessage(tr("Note has been restored."));
5222 @SuppressWarnings("unused")
5223 private void setupSelectiveSync() {
5225 // Get a list of valid notebooks
5226 List<Notebook> notebooks = null;
5227 List<Tag> tags = null;
5228 List<LinkedNotebook> linkedNotebooks = null;
5230 notebooks = syncRunner.localNoteStore.listNotebooks(syncRunner.authToken);
5231 tags = syncRunner.localNoteStore.listTags(syncRunner.authToken);
5232 linkedNotebooks = syncRunner.localNoteStore.listLinkedNotebooks(syncRunner.authToken);
5233 } catch (EDAMUserException e) {
5234 setMessage("EDAMUserException: " +e.getMessage());
5236 } catch (EDAMSystemException e) {
5237 setMessage("EDAMSystemException: " +e.getMessage());
5239 } catch (TException e) {
5240 setMessage("EDAMTransactionException: " +e.getMessage());
5242 } catch (EDAMNotFoundException e) {
5243 setMessage("EDAMNotFoundException: " +e.getMessage());
5247 // Split up notebooks into synchronized & non-synchronized
5248 List<Notebook> ignoredBooks = new ArrayList<Notebook>();
5249 List<String> dbIgnoredNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5251 for (int i=notebooks.size()-1; i>=0; i--) {
5252 for (int j=0; j<dbIgnoredNotebooks.size(); j++) {
5253 if (notebooks.get(i).getGuid().equalsIgnoreCase(dbIgnoredNotebooks.get(j))) {
5254 ignoredBooks.add(notebooks.get(i));
5255 j=dbIgnoredNotebooks.size();
5260 // split up tags into synchronized & non-synchronized
5261 List<Tag> ignoredTags = new ArrayList<Tag>();
5262 List<String> dbIgnoredTags = conn.getSyncTable().getIgnoreRecords("TAG");
5264 for (int i=tags.size()-1; i>=0; i--) {
5265 for (int j=0; j<dbIgnoredTags.size(); j++) {
5266 if (tags.get(i).getGuid().equalsIgnoreCase(dbIgnoredTags.get(j))) {
5267 ignoredTags.add(tags.get(i));
5268 j=dbIgnoredTags.size();
5273 // split up linked notebooks into synchronized & non-synchronized
5274 List<LinkedNotebook> ignoredLinkedNotebooks = new ArrayList<LinkedNotebook>();
5275 List<String> dbIgnoredLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5276 for (int i=linkedNotebooks.size()-1; i>=0; i--) {
5277 String notebookGuid = linkedNotebooks.get(i).getGuid();
5278 for (int j=0; j<dbIgnoredLinkedNotebooks.size(); j++) {
5279 if (notebookGuid.equalsIgnoreCase(dbIgnoredLinkedNotebooks.get(j))) {
5280 ignoredLinkedNotebooks.add(linkedNotebooks.get(i));
5281 j=dbIgnoredLinkedNotebooks.size();
5286 IgnoreSync ignore = new IgnoreSync(notebooks, ignoredBooks, tags, ignoredTags, linkedNotebooks, ignoredLinkedNotebooks);
5288 if (!ignore.okClicked())
5293 // Clear out old notebooks & add the new ones
5294 List<String> oldIgnoreNotebooks = conn.getSyncTable().getIgnoreRecords("NOTEBOOK");
5295 for (int i=0; i<oldIgnoreNotebooks.size(); i++) {
5296 conn.getSyncTable().deleteRecord("IGNORENOTEBOOK-"+oldIgnoreNotebooks.get(i));
5299 List<String> newNotebooks = new ArrayList<String>();
5300 for (int i=ignore.getIgnoredBookList().count()-1; i>=0; i--) {
5301 String text = ignore.getIgnoredBookList().takeItem(i).text();
5302 for (int j=0; j<notebooks.size(); j++) {
5303 if (notebooks.get(j).getName().equalsIgnoreCase(text)) {
5304 Notebook n = notebooks.get(j);
5305 conn.getSyncTable().addRecord("IGNORENOTEBOOK-"+n.getGuid(), n.getGuid());
5307 newNotebooks.add(n.getGuid());
5312 // Clear out old tags & add new ones
5313 List<String> oldIgnoreTags = conn.getSyncTable().getIgnoreRecords("TAG");
5314 for (int i=0; i<oldIgnoreTags.size(); i++) {
5315 conn.getSyncTable().deleteRecord("IGNORETAG-"+oldIgnoreTags.get(i));
5318 List<String> newTags = new ArrayList<String>();
5319 for (int i=ignore.getIgnoredTagList().count()-1; i>=0; i--) {
5320 String text = ignore.getIgnoredTagList().takeItem(i).text();
5321 for (int j=0; j<tags.size(); j++) {
5322 if (tags.get(j).getName().equalsIgnoreCase(text)) {
5323 Tag t = tags.get(j);
5324 conn.getSyncTable().addRecord("IGNORETAG-"+t.getGuid(), t.getGuid());
5325 newTags.add(t.getGuid());
5331 // Clear out old tags & add new ones
5332 List<String> oldIgnoreLinkedNotebooks = conn.getSyncTable().getIgnoreRecords("LINKEDNOTEBOOK");
5333 for (int i=0; i<oldIgnoreLinkedNotebooks.size(); i++) {
5334 conn.getSyncTable().deleteRecord("IGNORELINKEDNOTEBOOK-"+oldIgnoreLinkedNotebooks.get(i));
5337 List<String> newLinked = new ArrayList<String>();
5338 for (int i=ignore.getIgnoredLinkedNotebookList().count()-1; i>=0; i--) {
5339 String text = ignore.getIgnoredLinkedNotebookList().takeItem(i).text();
5340 for (int j=0; j<linkedNotebooks.size(); j++) {
5341 if (linkedNotebooks.get(j).getShareName().equalsIgnoreCase(text)) {
5342 LinkedNotebook t = linkedNotebooks.get(j);
5343 conn.getSyncTable().addRecord("IGNORELINKEDNOTEBOOK-"+t.getGuid(), t.getGuid());
5344 newLinked.add(t.getGuid());
5345 j=linkedNotebooks.size();
5350 conn.getNoteTable().expungeIgnoreSynchronizedNotes(newNotebooks, newTags, newLinked);
5356 //**********************************************************
5357 //**********************************************************
5358 //* XML Modifying methods
5359 //**********************************************************
5360 //**********************************************************
5361 // An error has happended fetching a resource. let the user know
5362 private void resourceErrorMessage() {
5366 QMessageBox.information(this, tr("DOUGH!!!"), tr("Well, this is embarrassing."+
5367 "\n\nSome attachments or images for this note appear to be missing from my database.\n"+
5368 "In a perfect world this wouldn't happen, but it has.\n" +
5369 "It is embarasing when a program like me, designed to save all your\n"+
5370 "precious data, has a problem finding data.\n\n" +
5371 "I guess life isn't fair, but I'll survive. Somehow...\n\n" +
5372 "In the mean time, I'm not going to let you make changes to this note.\n" +
5373 "Don't get angry. I'm doing it to prevent you from messing up\n"+
5374 "this note on the Evernote servers. Sorry."+
5375 "\n\nP.S. You might want to re-synchronize to see if it corrects this problem.\nWho knows, you might get lucky."));
5377 browserWindow.setReadOnly(true);
5384 //**********************************************************
5385 //**********************************************************
5387 //**********************************************************
5388 //**********************************************************
5389 // We should now do a sync with Evernote
5390 private void syncTimer() {
5391 logger.log(logger.EXTREME, "Entering NeverNote.syncTimer()");
5392 syncRunner.syncNeeded = true;
5393 syncRunner.disableUploads = Global.disableUploads;
5395 logger.log(logger.EXTREME, "Leaving NeverNote.syncTimer()");
5397 private void syncStart() {
5398 logger.log(logger.EXTREME, "Entering NeverNote.syncStart()");
5400 if (!syncRunning && Global.isConnected) {
5401 syncRunner.setConnected(true);
5402 syncRunner.setKeepRunning(Global.keepRunning);
5403 syncRunner.syncDeletedContent = Global.synchronizeDeletedContent();
5405 if (syncThreadsReady > 0) {
5406 thumbnailRunner.interrupt = true;
5407 saveNoteIndexWidth();
5408 saveNoteColumnPositions();
5409 if (syncRunner.addWork("SYNC")) {
5411 syncRunner.syncNeeded = true;
5416 logger.log(logger.EXTREME, "Leaving NeverNote.syncStart");
5418 @SuppressWarnings("unused")
5419 private void syncThreadComplete(Boolean refreshNeeded) {
5420 setMessage(tr("Finalizing Synchronization"));
5422 syncRunning = false;
5423 syncRunner.syncNeeded = false;
5424 synchronizeAnimationTimer.stop();
5425 synchronizeButton.setIcon(new QIcon(iconPath+"synchronize.png"));
5427 if (currentNote == null) {
5428 currentNote = conn.getNoteTable().getNote(currentNoteGuid, false, false, false, false, true);
5430 listManager.setUnsynchronizedNotes(conn.getNoteTable().getUnsynchronizedGUIDs());
5431 noteIndexUpdated(false);
5432 noteTableView.selectionModel().blockSignals(true);
5433 scrollToGuid(currentNoteGuid);
5434 noteTableView.selectionModel().blockSignals(false);
5435 refreshEvernoteNote(false);
5436 scrollToGuid(currentNoteGuid);
5439 // Check to see if there were any shared notebook errors
5440 if (syncRunner.error && syncRunner.errorSharedNotebooks.size() > 0) {
5441 String guid = syncRunner.errorSharedNotebooks.get(0);
5442 String notebookGuid = conn.getLinkedNotebookTable().getLocalNotebookGuid(guid);
5443 String localName = listManager.getNotebookNameByGuid(notebookGuid);
5444 SharedNotebookSyncError syncDialog = new SharedNotebookSyncError(localName);
5446 if (syncDialog.okPressed()) {
5447 if (syncDialog.doNothing.isChecked()) {
5448 syncRunner.errorSharedNotebooksIgnored.put(guid, guid);
5451 if (syncDialog.deleteNotebook.isChecked()) {
5452 conn.getNoteTable().expungeNotesByNotebook(notebookGuid, true, false);
5453 conn.getNotebookTable().expungeNotebook(notebookGuid, false);
5454 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5455 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5458 /* if (syncDialog.convertToLocal.isChecked()) {
5459 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, true);
5460 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5463 if (syncDialog.convertToShared.isChecked()) {
5464 conn.getLinkedNotebookTable().expungeNotebook(guid, false);
5465 conn.getNotebookTable().convertFromSharedNotebook(notebookGuid, false);
5473 // Finalize the synchronization
5474 if (!syncRunner.error)
5475 setMessage(tr("Synchronization Complete"));
5477 setMessage(tr("Synchronization completed with errors. Please check the log for details."));
5478 logger.log(logger.MEDIUM, "Sync complete.");
5480 public void saveUploadAmount(long t) {
5481 Global.saveUploadAmount(t);
5483 public void saveUserInformation(User user) {
5484 Global.saveUserInformation(user);
5486 public void saveEvernoteUpdateCount(int i) {
5487 Global.saveEvernoteUpdateCount(i);
5489 public void refreshLists() {
5490 logger.log(logger.EXTREME, "Entering NeverNote.refreshLists");
5492 listManager.refreshLists(currentNote, noteDirty, browserWindow.getContent());
5493 tagIndexUpdated(true);
5494 notebookIndexUpdated();
5495 savedSearchIndexUpdated();
5496 listManager.loadNotesIndex();
5498 noteTableView.selectionModel().blockSignals(true);
5499 noteIndexUpdated(true);
5500 noteTableView.selectionModel().blockSignals(false);
5501 logger.log(logger.EXTREME, "Leaving NeverNote.refreshLists");
5505 @SuppressWarnings("unused")
5506 private void authTimer() {
5507 Calendar cal = Calendar.getInstance();
5509 // If we are not connected let's get out of here
5510 if (!Global.isConnected)
5513 // If this is the first time through, then we need to set this
5514 // if (syncRunner.authRefreshTime == 0 || cal.getTimeInMillis() > syncRunner.authRefreshTime)
5515 // syncRunner.authRefreshTime = cal.getTimeInMillis();
5517 // long now = new Date().getTime();
5518 // if (now > Global.authRefreshTime && Global.isConnected) {
5519 syncRunner.authRefreshNeeded = true;
5523 @SuppressWarnings("unused")
5524 private void authRefreshComplete(boolean goodSync) {
5525 logger.log(logger.EXTREME, "Entering NeverNote.authRefreshComplete");
5526 Global.isConnected = syncRunner.isConnected;
5528 // authTimer.start((int)syncRunner.authTimeRemaining/4);
5529 authTimer.start(1000*60*15);
5530 logger.log(logger.LOW, "Authentication token has been renewed");
5531 // setMessage("Authentication token has been renewed.");
5533 authTimer.start(1000*60*5);
5534 logger.log(logger.LOW, "Authentication token renew has failed - retry in 5 minutes.");
5535 // setMessage("Authentication token renew has failed - retry in 5 minutes.");
5537 logger.log(logger.EXTREME, "Leaving NeverNote.authRefreshComplete");
5541 @SuppressWarnings("unused")
5542 private synchronized void indexTimer() {
5543 logger.log(logger.EXTREME, "Index timer activated. Sync running="+syncRunning);
5546 if (!indexDisabled && indexRunner.idle) {
5547 thumbnailRunner.interrupt = true;
5548 indexRunner.addWork("SCAN");
5550 logger.log(logger.EXTREME, "Leaving neverNote index timer");
5553 @SuppressWarnings("unused")
5554 private void indexStarted() {
5555 setMessage(tr("Indexing notes"));
5557 @SuppressWarnings("unused")
5558 private void indexComplete() {
5559 setMessage(tr("Index complete"));
5561 @SuppressWarnings("unused")
5562 private synchronized void toggleNoteIndexing() {
5563 logger.log(logger.HIGH, "Entering NeverNote.toggleIndexing");
5564 indexDisabled = !indexDisabled;
5566 setMessage(tr("Indexing is now enabled."));
5568 setMessage(tr("Indexing is now disabled."));
5569 menuBar.disableIndexing.setChecked(indexDisabled);
5570 logger.log(logger.HIGH, "Leaving NeverNote.toggleIndexing");
5573 @SuppressWarnings("unused")
5574 private void threadMonitorCheck() {
5579 alive = listManager.threadCheck(Global.tagCounterThreadId);
5582 if (tagDeadCount > MAX && !disableTagThreadCheck) {
5583 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the tag counter thread has died. I recommend "+
5584 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5585 disableTagThreadCheck = true;
5590 alive = listManager.threadCheck(Global.notebookCounterThreadId);
5592 notebookThreadDeadCount++;
5593 if (notebookThreadDeadCount > MAX && !disableNotebookThreadCheck) {
5594 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the notebook counter thread has died. I recommend "+
5595 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5596 disableNotebookThreadCheck=true;
5599 notebookThreadDeadCount=0;
5601 alive = listManager.threadCheck(Global.trashCounterThreadId);
5604 if (trashDeadCount > MAX && !disableTrashThreadCheck) {
5605 QMessageBox.information(this, tr("A thread has died."), ("It appears as the trash counter thread has died. I recommend "+
5606 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5607 disableTrashThreadCheck = true;
5612 alive = listManager.threadCheck(Global.saveThreadId);
5614 saveThreadDeadCount++;
5615 if (saveThreadDeadCount > MAX && !disableSaveThreadCheck) {
5616 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the note saver thread has died. I recommend "+
5617 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5618 disableSaveThreadCheck = true;
5621 saveThreadDeadCount=0;
5623 if (!syncThread.isAlive()) {
5624 syncThreadDeadCount++;
5625 if (syncThreadDeadCount > MAX && !disableSyncThreadCheck) {
5626 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the synchronization thread has died. I recommend "+
5627 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5628 disableSyncThreadCheck = true;
5631 syncThreadDeadCount=0;
5633 if (!indexThread.isAlive()) {
5634 indexThreadDeadCount++;
5635 if (indexThreadDeadCount > MAX && !disableIndexThreadCheck) {
5636 QMessageBox.information(this, tr("A thread has died."), tr("It appears as the index thread has died. I recommend "+
5637 "checking stopping NeverNote, saving the logs for later viewing, and restarting. Sorry."));
5638 disableIndexThreadCheck = true;
5641 indexThreadDeadCount=0;
5646 private void thumbnailTimer() {
5647 if (Global.enableThumbnails() && !syncRunning && indexRunner.idle) {
5648 thumbnailRunner.addWork("SCAN");
5652 //**************************************************
5653 //* Backup & Restore
5654 //**************************************************
5655 @SuppressWarnings("unused")
5656 private void databaseBackup() {
5657 QFileDialog fd = new QFileDialog(this);
5658 fd.setFileMode(FileMode.AnyFile);
5659 fd.setConfirmOverwrite(true);
5660 fd.setWindowTitle(tr("Backup Database"));
5661 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5662 fd.setAcceptMode(AcceptMode.AcceptSave);
5663 if (saveLastPath == null || saveLastPath.equals(""))
5664 fd.setDirectory(System.getProperty("user.home"));
5666 fd.setDirectory(saveLastPath);
5667 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5673 saveLastPath = fd.selectedFiles().get(0);
5674 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5675 setMessage(tr("Backing up database"));
5677 // conn.backupDatabase(Global.getUpdateSequenceNumber(), Global.getSequenceDate());
5679 ExportData noteWriter = new ExportData(conn, true);
5680 String fileName = fd.selectedFiles().get(0);
5682 if (!fileName.endsWith(".nnex"))
5683 fileName = fileName +".nnex";
5684 noteWriter.exportData(fileName);
5685 setMessage(tr("Database backup completed."));
5690 @SuppressWarnings("unused")
5691 private void databaseRestore() {
5692 if (QMessageBox.question(this, tr("Confirmation"),
5693 tr("This is used to restore a database from backups.\n" +
5694 "It is HIGHLY recommened that this only be used to populate\n" +
5695 "an empty database. Restoring into a database that\n already has data" +
5696 " can cause problems.\n\nAre you sure you want to continue?"),
5697 QMessageBox.StandardButton.Yes,
5698 QMessageBox.StandardButton.No)==StandardButton.No.value()) {
5703 QFileDialog fd = new QFileDialog(this);
5704 fd.setFileMode(FileMode.ExistingFile);
5705 fd.setConfirmOverwrite(true);
5706 fd.setWindowTitle(tr("Restore Database"));
5707 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5708 fd.setAcceptMode(AcceptMode.AcceptOpen);
5709 if (saveLastPath == null || saveLastPath.equals(""))
5710 fd.setDirectory(System.getProperty("user.home"));
5712 fd.setDirectory(saveLastPath);
5713 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5719 saveLastPath = fd.selectedFiles().get(0);
5720 saveLastPath = saveLastPath.substring(0,saveLastPath.lastIndexOf("/"));
5722 setMessage(tr("Restoring database"));
5723 ImportData noteReader = new ImportData(conn, true);
5724 noteReader.importData(fd.selectedFiles().get(0));
5726 if (noteReader.lastError != 0) {
5727 setMessage(noteReader.getErrorMessage());
5728 logger.log(logger.LOW, "Restore problem: " +noteReader.lastError);
5733 listManager.loadNoteTitleColors();
5735 refreshEvernoteNote(true);
5736 setMessage(tr("Database has been restored."));
5739 @SuppressWarnings("unused")
5740 private void exportNotes() {
5741 QFileDialog fd = new QFileDialog(this);
5742 fd.setFileMode(FileMode.AnyFile);
5743 fd.setConfirmOverwrite(true);
5744 fd.setWindowTitle(tr("Backup Database"));
5745 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5746 fd.setAcceptMode(AcceptMode.AcceptSave);
5747 fd.setDirectory(System.getProperty("user.home"));
5748 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5754 setMessage(tr("Exporting Notes"));
5757 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5758 selectedNoteGUIDs.add(currentNoteGuid);
5760 ExportData noteWriter = new ExportData(conn, false, selectedNoteGUIDs);
5761 String fileName = fd.selectedFiles().get(0);
5763 if (!fileName.endsWith(".nnex"))
5764 fileName = fileName +".nnex";
5765 noteWriter.exportData(fileName);
5766 setMessage(tr("Export completed."));
5772 @SuppressWarnings("unused")
5773 private void importNotes() {
5774 QFileDialog fd = new QFileDialog(this);
5775 fd.setFileMode(FileMode.ExistingFile);
5776 fd.setConfirmOverwrite(true);
5777 fd.setWindowTitle(tr("Import Notes"));
5778 fd.setFilter(tr("NeverNote Export (*.nnex);;All Files (*.*)"));
5779 fd.setAcceptMode(AcceptMode.AcceptOpen);
5780 if (saveLastPath == null || saveLastPath.equals(""))
5781 fd.setDirectory(System.getProperty("user.home"));
5783 fd.setDirectory(saveLastPath);
5784 if (fd.exec() == 0 || fd.selectedFiles().size() == 0) {
5790 setMessage(tr("Importing Notes"));
5793 if (selectedNoteGUIDs.size() == 0 && !currentNoteGuid.equals(""))
5794 selectedNoteGUIDs.add(currentNoteGuid);
5796 ImportData noteReader = new ImportData(conn, false);
5797 String fileName = fd.selectedFiles().get(0);
5798 // saveLastPath.substring(0,fileName.lastIndexOf("/"));
5800 if (!fileName.endsWith(".nnex"))
5801 fileName = fileName +".nnex";
5802 if (selectedNotebookGUIDs != null && selectedNotebookGUIDs.size() > 0)
5803 noteReader.setNotebookGuid(selectedNotebookGUIDs.get(0));
5805 noteReader.setNotebookGuid(listManager.getNotebookIndex().get(0).getGuid());
5807 noteReader.importData(fileName);
5809 if (noteReader.lastError != 0) {
5810 setMessage(noteReader.getErrorMessage());
5811 logger.log(logger.LOW, "Import problem: " +noteReader.lastError);
5816 listManager.loadNoteTitleColors();
5818 refreshEvernoteNote(false);
5819 setMessage(tr("Notes have been imported."));
5822 setMessage(tr("Import completed."));
5829 //**************************************************
5830 //* Duplicate a note
5831 //**************************************************
5832 @SuppressWarnings("unused")
5833 private void duplicateNote() {
5835 duplicateNote(currentNoteGuid);
5838 //**************************************************
5839 //* Action from when a user clicks Copy As URL
5840 //**************************************************
5841 @SuppressWarnings("unused")
5842 private void copyAsUrlClicked() {
5843 QClipboard clipboard = QApplication.clipboard();
5844 QMimeData mime = new QMimeData();
5846 mime.setText(currentNoteGuid);
5847 List<QUrl> urls = new ArrayList<QUrl>();
5849 // Start building the URL
5850 User user = Global.getUserInformation();
5852 // Check that we have everything we need
5853 if ((user.getShardId().equals("") || user.getId() == 0) && !Global.bypassSynchronizationWarning()) {
5854 SynchronizationRequiredWarning warning = new SynchronizationRequiredWarning(this);
5856 if (!warning.neverSynchronize())
5859 Global.setBypassSynchronizationWarning(true);
5860 user.setShardId("s0");
5866 // Start building a list of URLs based upon the selected notes
5867 noteTableView.showColumn(Global.noteTableGuidPosition);
5869 List<QModelIndex> selections = noteTableView.selectionModel().selectedRows();
5870 if (!Global.isColumnVisible("guid"))
5871 noteTableView.hideColumn(Global.noteTableGuidPosition);
5873 // Check that the note is either synchronized, or in a local notebook
5874 for (int i=0; i<selections.size(); i++) {
5876 int row = selections.get(i).row();
5877 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5878 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5879 String selectedGuid = (String)ix.values().toArray()[0];
5881 Note n = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5882 if (n.getUpdateSequenceNum() == 0 && !conn.getNotebookTable().isNotebookLocal(n.getNotebookGuid())) {
5883 QMessageBox.critical(this, tr("Please Synchronize") ,tr("Please either synchronize or move any " +
5884 "new notes to a local notebook."));
5889 // Start building the URLs
5890 for (int i=0; i<selections.size(); i++) {
5892 int row = selections.get(i).row();
5893 index = noteTableView.proxyModel.index(row, Global.noteTableGuidPosition);
5894 SortedMap<Integer, Object> ix = noteTableView.proxyModel.itemData(index);
5895 String selectedGuid = (String)ix.values().toArray()[0];
5896 mime.setText(selectedGuid);
5900 Note selectedNote = conn.getNoteTable().getNote(selectedGuid, false, false, false, false, false);
5901 if (selectedNote.getUpdateSequenceNum() > 0) {
5905 gid = "00000000-0000-0000-0000-000000000000";
5908 url = new String("evernote://///view/") + new String(user.getId() + "/" +user.getShardId() +"/"
5910 urls.add(new QUrl(url));
5913 clipboard.setMimeData(mime);
5917 //**************************************************
5919 //**************************************************
5920 public void setupFolderImports() {
5921 List<WatchFolderRecord> records = conn.getWatchFolderTable().getAll();
5923 if (importKeepWatcher == null)
5924 importKeepWatcher = new QFileSystemWatcher();
5925 if (importDeleteWatcher == null) {
5926 importDeleteWatcher = new QFileSystemWatcher();
5927 for (int i=0; i<records.size(); i++) {
5928 if (!records.get(i).keep)
5929 folderImportDelete(records.get(i).folder);
5935 // importKeepWatcher.addPath(records.get(i).folder.replace('\\', '/'));
5936 for (int i=0; i<records.size(); i++) {
5937 if (records.get(i).keep)
5938 importKeepWatcher.addPath(records.get(i).folder);
5940 importDeleteWatcher.addPath(records.get(i).folder);
5943 importKeepWatcher.directoryChanged.connect(this, "folderImportKeep(String)");
5944 importDeleteWatcher.directoryChanged.connect(this, "folderImportDelete(String)");
5946 // Look at the files already there so we don't import them again if a new file is created
5947 if (importedFiles == null) {
5948 importedFiles = new ArrayList<String>();
5949 for (int j=0; j<records.size(); j++) {
5950 QDir dir = new QDir(records.get(j).folder);
5951 List<QFileInfo> list = dir.entryInfoList();
5952 for (int k=0; k<list.size(); k++) {
5953 if (list.get(k).isFile())
5954 importedFiles.add(list.get(k).absoluteFilePath());
5959 public void folderImport() {
5960 List<WatchFolderRecord> recs = conn.getWatchFolderTable().getAll();
5961 WatchFolder dialog = new WatchFolder(recs, listManager.getNotebookIndex());
5963 if (!dialog.okClicked())
5966 // We have some sort of update.
5967 if (importKeepWatcher.directories().size() > 0)
5968 importKeepWatcher.removePaths(importKeepWatcher.directories());
5969 if (importDeleteWatcher.directories().size() > 0)
5970 importDeleteWatcher.removePaths(importDeleteWatcher.directories());
5972 conn.getWatchFolderTable().expungeAll();
5973 // Start building from the table
5974 for (int i=0; i<dialog.table.rowCount(); i++) {
5975 QTableWidgetItem item = dialog.table.item(i, 0);
5976 String dir = item.text();
5977 item = dialog.table.item(i, 1);
5978 String notebook = item.text();
5979 item = dialog.table.item(i, 2);
5981 if (item.text().equalsIgnoreCase("Keep"))
5986 String guid = conn.getNotebookTable().findNotebookByName(notebook);
5987 conn.getWatchFolderTable().addWatchFolder(dir, guid, keep, 0);
5989 setupFolderImports();
5992 public void folderImportKeep(String dirName) throws NoSuchAlgorithmException {
5994 String whichOS = System.getProperty("os.name");
5995 if (whichOS.contains("Windows"))
5996 dirName = dirName.replace('/','\\');
5998 FileImporter importer = new FileImporter(logger, conn);
6000 QDir dir = new QDir(dirName);
6001 List<QFileInfo> list = dir.entryInfoList();
6002 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6004 for (int i=0; i<list.size(); i++){
6006 boolean redundant = false;
6007 // Check if we've already imported this one or if it existed before
6008 for (int j=0; j<importedFiles.size(); j++) {
6009 if (importedFiles.get(j).equals(list.get(i).absoluteFilePath()))
6014 importer.setFileInfo(list.get(i));
6015 importer.setFileName(list.get(i).absoluteFilePath());
6018 if (list.get(i).isFile() && importer.isValidType()) {
6020 if (!importer.importFile()) {
6021 // If we can't get to the file, it is probably locked. We'll try again later.
6022 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6023 importFilesKeep.add(list.get(i).absoluteFilePath());
6027 Note newNote = importer.getNote();
6028 newNote.setNotebookGuid(notebook);
6029 newNote.setTitle(dir.at(i));
6030 listManager.addNote(newNote);
6031 conn.getNoteTable().addNote(newNote, true);
6032 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
6033 noteTableView.insertRow(newNote, true, -1);
6034 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6035 listManager.countNotebookResults(listManager.getNoteIndex());
6036 importedFiles.add(list.get(i).absoluteFilePath());
6044 public void folderImportDelete(String dirName) {
6046 String whichOS = System.getProperty("os.name");
6047 if (whichOS.contains("Windows"))
6048 dirName = dirName.replace('/','\\');
6050 FileImporter importer = new FileImporter(logger, conn);
6051 QDir dir = new QDir(dirName);
6052 List<QFileInfo> list = dir.entryInfoList();
6053 String notebook = conn.getWatchFolderTable().getNotebook(dirName);
6055 for (int i=0; i<list.size(); i++){
6056 importer.setFileInfo(list.get(i));
6057 importer.setFileName(list.get(i).absoluteFilePath());
6059 if (list.get(i).isFile() && importer.isValidType()) {
6061 if (!importer.importFile()) {
6062 // If we can't get to the file, it is probably locked. We'll try again later.
6063 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6064 importFilesKeep.add(list.get(i).absoluteFilePath());
6068 Note newNote = importer.getNote();
6069 newNote.setNotebookGuid(notebook);
6070 newNote.setTitle(dir.at(i));
6071 listManager.addNote(newNote);
6072 conn.getNoteTable().addNote(newNote, true);
6073 listManager.getUnsynchronizedNotes().add(newNote.getGuid());
6074 noteTableView.insertRow(newNote, true, -1);
6075 listManager.updateNoteContent(newNote.getGuid(), importer.getNoteContent());
6076 listManager.countNotebookResults(listManager.getNoteIndex());
6077 dir.remove(dir.at(i));
6083 //**************************************************
6085 //**************************************************
6086 private void externalFileEdited(String fileName) throws NoSuchAlgorithmException {
6087 logger.log(logger.HIGH, "Entering exernalFileEdited");
6089 // Strip URL prefix and base dir path
6090 String dPath = FileUtils.toForwardSlashedPath(Global.getFileManager().getResDirPath());
6091 String name = fileName.replace(dPath, "");
6092 int pos = name.lastIndexOf('.');
6095 guid = guid.substring(0,pos);
6097 pos = name.lastIndexOf(Global.attachmentNameDelimeter);
6099 guid = name.substring(0, pos);
6102 QFile file = new QFile(fileName);
6103 if (!file.open(new QIODevice.OpenMode(QIODevice.OpenModeFlag.ReadOnly))) {
6104 // If we can't get to the file, it is probably locked. We'll try again later.
6105 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6106 externalFiles.add(fileName);
6109 QByteArray binData = file.readAll();
6111 if (binData.size() == 0) {
6112 // If we can't get to the file, it is probably locked. We'll try again later.
6113 logger.log(logger.LOW, "Unable to save externally edited file. Saving for later.");
6114 externalFiles.add(fileName);
6118 Resource r = conn.getNoteTable().noteResourceTable.getNoteResource(guid, true);
6120 r = conn.getNoteTable().noteResourceTable.getNoteResource(Global.resourceMap.get(guid), true);
6121 if (r == null || r.getData() == null || r.getData().getBody() == null)
6123 String oldHash = Global.byteArrayToHexString(r.getData().getBodyHash());
6124 MessageDigest md = MessageDigest.getInstance("MD5");
6125 md.update(binData.toByteArray());
6126 byte[] hash = md.digest();
6127 String newHash = Global.byteArrayToHexString(hash);
6128 if (r.getNoteGuid().equalsIgnoreCase(currentNoteGuid)) {
6129 updateResourceContentHash(browserWindow, r.getGuid(), oldHash, newHash);
6131 if (externalWindows.containsKey(r.getNoteGuid())) {
6132 updateResourceContentHash(externalWindows.get(r.getNoteGuid()).getBrowserWindow(),
6133 r.getGuid(), oldHash, newHash);
6135 conn.getNoteTable().updateResourceContentHash(r.getNoteGuid(), oldHash, newHash);
6136 Data data = r.getData();
6137 data.setBody(binData.toByteArray());
6138 data.setBodyHash(hash);
6139 logger.log(logger.LOW, "externalFileEdited: " +data.getSize() +" bytes");
6141 conn.getNoteTable().noteResourceTable.updateNoteResource(r,true);
6143 if (r.getNoteGuid().equals(currentNoteGuid)) {
6144 QWebSettings.setMaximumPagesInCache(0);
6145 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6146 refreshEvernoteNote(true);
6147 browserWindow.getBrowser().triggerPageAction(WebAction.Reload);
6150 if (externalWindows.containsKey(r.getNoteGuid())) {
6151 QWebSettings.setMaximumPagesInCache(0);
6152 QWebSettings.setObjectCacheCapacities(0, 0, 0);
6153 externalWindows.get(r.getNoteGuid()).getBrowserWindow().getBrowser().triggerPageAction(WebAction.Reload);
6157 logger.log(logger.HIGH, "Exiting externalFielEdited");
6159 // This is a timer event that tries to save any external files that were edited. This
6160 // is only needed if we couldn't save a file earlier.
6161 public void externalFileEditedSaver() {
6162 for (int i=externalFiles.size()-1; i>=0; i--) {
6164 logger.log(logger.MEDIUM, "Trying to save " +externalFiles.get(i));
6165 externalFileEdited(externalFiles.get(i));
6166 externalFiles.remove(i);
6167 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6169 for (int i=0; i<importFilesKeep.size(); i++) {
6171 logger.log(logger.MEDIUM, "Trying to save " +importFilesKeep.get(i));
6172 folderImportKeep(importFilesKeep.get(i));
6173 importFilesKeep.remove(i);
6174 } catch (NoSuchAlgorithmException e) {e.printStackTrace();}
6176 for (int i=0; i<importFilesDelete.size(); i++) {
6177 logger.log(logger.MEDIUM, "Trying to save " +importFilesDelete.get(i));
6178 folderImportDelete(importFilesDelete.get(i));
6179 importFilesDelete.remove(i);
6186 // If an attachment on the current note was edited, we need to update the current notes's hash
6187 // Update a note content's hash. This happens if a resource is edited outside of NN
6188 public void updateResourceContentHash(BrowserWindow browser, String guid, String oldHash, String newHash) {
6189 int position = browserWindow.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=");
6191 for (;position>-1;) {
6192 endPos = browser.getContent().indexOf(">", position+1);
6193 String oldSegment = browser.getContent().substring(position,endPos);
6194 int hashPos = oldSegment.indexOf("hash=\"");
6195 int hashEnd = oldSegment.indexOf("\"", hashPos+7);
6196 String hash = oldSegment.substring(hashPos+6, hashEnd);
6197 if (hash.equalsIgnoreCase(oldHash)) {
6198 String newSegment = oldSegment.replace(oldHash, newHash);
6199 String content = browser.getContent().substring(0,position) +
6201 browser.getContent().substring(endPos);
6202 browser.setContent(new QByteArray(content));;
6205 position = browser.getContent().indexOf("en-tag=\"en-media\" guid=\""+guid+"\" type=", position+1);
6210 //*************************************************
6211 //* Minimize to tray
6212 //*************************************************
6214 public void changeEvent(QEvent e) {
6215 if (e.type() == QEvent.Type.WindowStateChange) {
6216 if (isMinimized() && Global.showTrayIcon()) {
6218 QTimer.singleShot(10, this, "hide()");
6222 windowMaximized = true;
6224 windowMaximized = false;
6228 //*************************************************
6229 //* Check database userid & passwords
6230 //*************************************************
6231 private static boolean databaseCheck(String url,String userid, String userPassword, String cypherPassword) {
6232 Connection connection;
6235 Class.forName("org.h2.Driver");
6236 } catch (ClassNotFoundException e1) {
6237 e1.printStackTrace();
6242 String passwordString = null;
6243 if (cypherPassword==null || cypherPassword.trim().equals(""))
6244 passwordString = userPassword;
6246 passwordString = cypherPassword+" "+userPassword;
6247 connection = DriverManager.getConnection(url,userid,passwordString);
6248 } catch (SQLException e) {
6253 } catch (SQLException e) {
6254 e.printStackTrace();
6259 //*************************************************
6260 //* View / Hide source HTML for a note
6261 //*************************************************
6262 public void viewSource() {
6263 browserWindow.showSource(menuBar.viewSource.isChecked());
6265 //*************************************************
6266 // Block the program. This is used for things
6267 // like async web calls.
6268 //*************************************************
6269 @SuppressWarnings("unused")
6270 private void blockApplication(BrowserWindow b) {
6271 // Block all signals
6275 blockTimer = new QTimer();
6276 blockTimer.setSingleShot(true);
6277 blockTimer.setInterval(15000);
6278 blockTimer.timeout.connect(this, "unblockApplication()");
6283 @SuppressWarnings("unused")
6284 private void unblockApplication() {
6286 if (blockingWindow != null && new GregorianCalendar().getTimeInMillis() > blockingWindow.unblockTime && blockingWindow.unblockTime != -1) {
6287 QMessageBox.critical(null, tr("No Response from CodeCogs") ,tr("Unable to contact CodeCogs for LaTeX formula."));
6288 blockingWindow.unblockTime = -1;
6289 blockingWindow.awaitingHttpResponse = false;
6291 blockingWindow = null;
6292 blockSignals(false);